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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ModisNorthImage.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/operator/ModisNorthImage.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.watermask.operator;
import org.esa.snap.core.image.ImageHeader;
import org.esa.snap.core.util.ImageUtils;
import org.esa.snap.core.util.jai.SingleBandedSampleModel;
import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.SourcelessOpImage;
import java.awt.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* OpImage to read from GlobCover-based water mask images.
*
* @author Thomas Storm
*/
public class ModisNorthImage extends SourcelessOpImage {
private final ZipFile zipFile;
static ModisNorthImage create(Properties properties, File zipFile) throws IOException {
final ImageHeader imageHeader = ImageHeader.load(properties, null);
return new ModisNorthImage(imageHeader, zipFile);
}
private ModisNorthImage(ImageHeader imageHeader, File zipFile) throws IOException {
super(imageHeader.getImageLayout(),
null,
ImageUtils.createSingleBandedSampleModel(DataBuffer.TYPE_BYTE,
imageHeader.getImageLayout().getSampleModel(null).getWidth(),
imageHeader.getImageLayout().getSampleModel(null).getHeight()),
imageHeader.getImageLayout().getMinX(null),
imageHeader.getImageLayout().getMinY(null),
imageHeader.getImageLayout().getWidth(null),
imageHeader.getImageLayout().getHeight(null));
this.zipFile = new ZipFile(zipFile);
// this image uses its own tile cache in order not to disturb the GPF tile cache.
setTileCache(JAI.createTileCache(50L * 1024 * 1024));
}
@Override
public Raster computeTile(int tileX, int tileY) {
Raster raster;
try {
raster = computeRawRaster(tileX, tileY);
} catch (IOException e) {
throw new RuntimeException(MessageFormat.format("Failed to read image tile ''{0} | {1}''.", tileX, tileY), e);
}
return raster;
}
private Raster computeRawRaster(int tileX, int tileY) throws IOException {
final String fileName = getFileName(tileX, tileY);
final WritableRaster targetRaster = createWritableRaster(tileX, tileY);
final ZipEntry zipEntry = zipFile.getEntry(fileName);
InputStream inputStream = null;
try {
inputStream = zipFile.getInputStream(zipEntry);
BufferedImage image = ImageIO.read(inputStream);
Raster imageData = image.getData();
for (int x = 0; x < imageData.getWidth(); x++) {
int xPos = tileXToX(tileX) + x;
for (int y = 0; y < imageData.getHeight(); y++) {
byte sample = (byte) imageData.getSample(x, y, 0);
sample = (byte) Math.abs(sample - 1);
int yPos = tileYToY(tileY) + y;
targetRaster.setSample(xPos, yPos, 0, sample);
}
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return targetRaster;
}
private WritableRaster createWritableRaster(int tileX, int tileY) {
final Point location = new Point(tileXToX(tileX), tileYToY(tileY));
final SampleModel sampleModel = new SingleBandedSampleModel(DataBuffer.TYPE_BYTE, WatermaskClassifier.GC_TILE_WIDTH, WatermaskClassifier.GC_TILE_HEIGHT);
return createWritableRaster(sampleModel, location);
}
private String getFileName(int tileX, int tileY) {
return String.format("%d-%d.png", tileX, tileY);
}
}
| 4,558 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
WatermaskUtils.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/operator/WatermaskUtils.java | package gov.nasa.gsfc.seadas.watermask.operator;
public class WatermaskUtils {
private WatermaskUtils() {
}
/**
* Computes the side length of the images to be generated for the given resolution.
*
* @param resolution The resolution.
*
* @return The side length of the images to be generated.
*/
public static int computeSideLength(int resolution) {
final int pixelXCount = 40024000 / resolution;
final int pixelXCountPerTile = pixelXCount / 360;
// these two lines needed to create a multiple of 8
final int temp = pixelXCountPerTile / 8;
return temp * 8;
}
/**
* Creates the name of the img file for the given latitude and longitude.
*
* @param lat latitude in degree
* @param lon longitude in degree
*
* @return the name of the img file
*/
public static String createImgFileName(float lat, float lon) {
final boolean geoPosIsWest = lon < 0;
final boolean geoPosIsSouth = lat < 0;
StringBuilder result = new StringBuilder();
final String eastOrWest = geoPosIsWest ? "w" : "e";
result.append(eastOrWest);
int positiveLon = (int) Math.abs(Math.floor(lon));
if (positiveLon >= 10 && positiveLon < 100) {
result.append("0");
} else if (positiveLon < 10) {
result.append("00");
}
result.append(positiveLon);
final String northOrSouth = geoPosIsSouth ? "s" : "n";
result.append(northOrSouth);
final int positiveLat = (int) Math.abs(Math.floor(lat));
if (positiveLat < 10) {
result.append("0");
}
result.append(positiveLat);
result.append(".img");
return result.toString();
}
}
| 1,796 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
WatermaskClassifier.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/operator/WatermaskClassifier.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.watermask.operator;
import gov.nasa.gsfc.seadas.watermask.util.ImageDescriptor;
import gov.nasa.gsfc.seadas.watermask.util.ImageDescriptorBuilder;
import gov.nasa.gsfc.seadas.watermask.util.ResourceInstallationUtils;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.PixelPos;
import javax.media.jai.OpImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Properties;
/**
* Classifies a pixel given by its geo-coordinate as water pixel.
*/
@SuppressWarnings({"ResultOfMethodCallIgnored"})
public class WatermaskClassifier {
public static final int WATER_VALUE = 1;
public static final int INVALID_VALUE = 127;
public static final int LAND_VALUE = 0;
public static final int RESOLUTION_50m = 50;
public static final int RESOLUTION_150m = 150;
public static final int RESOLUTION_1km = 1000;
public static final int RESOLUTION_10km = 10000;
public static final String FILENAME_SRTM_GC_50m = "50m.zip";
public static final String FILENAME_SRTM_GC_150m = "150m.zip";
public static final String FILENAME_GSHHS_1km = "GSHHS_water_mask_1km.zip";
public static final String FILENAME_GSHHS_10km = "GSHHS_water_mask_10km.zip";
public static final String FILENAME_USE_DEFAULT = "DEFAULT";
public static String GC_WATER_MASK_FILE = "GC_water_mask.zip";
public enum Mode {
MODIS("MODIS"),
SRTM_GC("SRTM_GC"),
GSHHS("GSHHS"),
DEFAULT("DEFAULT");
public String SRTM_GC_DESCRIPTION = "SRTM (Shuttle Radar Topography Mission) and GC(GlobCover World Map)";
public String GSHHS_DESCRIPTION = "GSHHS (Global Self-consistent, Hierarchical, High-resolution Shoreline Database)";
public String MODIS_DESCRIPTION = "";
public String DEFAULT_DESCRIPTION = "Determines mode based on input resolution";
private final String name;
private Mode(String name) {
this.name = name;
}
public String getDescription() {
switch (this) {
case MODIS:
return MODIS_DESCRIPTION;
case SRTM_GC:
return SRTM_GC_DESCRIPTION;
case GSHHS:
return GSHHS_DESCRIPTION;
case DEFAULT:
return DEFAULT_DESCRIPTION;
}
return null;
}
public String toString() {
return name;
}
}
static final int GC_TILE_WIDTH = 576;
static final int GC_TILE_HEIGHT = 491;
static final int GC_IMAGE_WIDTH = 129600;
static final int GC_IMAGE_HEIGHT = 10800;
static final int GSHHS_1_TILE_WIDTH = 500;
static final int GSHHS_1_TILE_HEIGHT = 250;
static final int GSHHS_1_IMAGE_WIDTH = 36000;
static final int GSHHS_1_IMAGE_HEIGHT = 18000;
static final int GSHHS_10_TILE_WIDTH = 250;
static final int GSHHS_10_TILE_HEIGHT = 125;
static final int GSHHS_10_IMAGE_WIDTH = 3600;
static final int GSHHS_10_IMAGE_HEIGHT = 1800;
static final int MODIS_IMAGE_WIDTH = 155520;
static final int MODIS_IMAGE_HEIGHT = 12960;
static final int MODIS_TILE_WIDTH = 640;
static final int MODIS_TILE_HEIGHT = 540;
// private SRTMOpImage centerImage;
// private final PNGSourceImage gshhsImage;
// private final PNGSourceImage aboveSixtyNorthImage;
// private final PNGSourceImage belowSixtySouthImage;
private SRTMOpImage centerImage;
private PNGSourceImage gshhsImage;
private PNGSourceImage aboveSixtyNorthImage;
private PNGSourceImage belowSixtySouthImage;
private Mode mode;
private int resolution;
private String filename;
/**
* Creates a new classifier instance on the given resolution.
* The classifier uses a tiled image in background to determine the if a
* given geo-position is over land or over water.
* Tiles do not exist if the whole region of the tile would only cover land or water.
* Where a tile does not exist a so called fill algorithm can be performed.
* In this case the next existing tile is searched and the nearest classification value
* for the given geo-position is returned.
* If the fill algorithm is not performed a value indicating invalid is returned.
*
* @param resolution The resolution specifying the source data which is to be queried. The units are in meters.
* Needs to be <code>RESOLUTION_50m</code>, <code>RESOLUTION_150m</code>,
* <code>RESOLUTION_1km</code> or <code>RESOLUTION_10km</code>
* @param mode The mode the classifier shall run in. Must be one of <code>MODE_MODIS</code>,
* <code>Mode.SRTM_GC</code> or <code>Mode.GSHHS</code>.
* <p/>
* If <code>Mode.MODIS</code> is chosen, the watermask is based on MODIS above 60° north,
* on SRTM-shapefiles between 60° north and 60° south, and on MODIS below 60°
* south.
* <p/>
* If <code>Mode.SRTM_GC</code> is chosen, the watermask is based on GlobCover above 60° north,
* on SRTM-shapefiles between 60° north and 60° south, and on MODIS below 60° south.
* <p/>
* If <code>Mode.GSHHS</code> is chosen, the watermask is based on the Global Self-consistent,
* Hierarchical, High-resolution Shoreline Database
* @throws java.io.IOException If some IO-error occurs creating the sources.
*/
public WatermaskClassifier(int resolution, Mode mode, String filename) throws IOException {
if (resolution != RESOLUTION_50m && resolution != RESOLUTION_150m && resolution != RESOLUTION_1km && resolution != RESOLUTION_10km) {
throw new IllegalArgumentException(
MessageFormat.format("Resolution needs to be {0}, {1}, {2} or {3}.", RESOLUTION_50m, RESOLUTION_150m, RESOLUTION_1km, RESOLUTION_10km));
}
if (FILENAME_USE_DEFAULT.equals(filename)) {
switch (resolution) {
case RESOLUTION_50m:
filename = FILENAME_SRTM_GC_50m;
break;
case RESOLUTION_150m:
filename = FILENAME_SRTM_GC_150m;
break;
case RESOLUTION_1km:
filename = FILENAME_GSHHS_1km;
break;
case RESOLUTION_10km:
filename = FILENAME_GSHHS_10km;
break;
default:
String msg = String.format("Unknown resolution for setting default filename '%d'. Known resolutions are {%d, %d, %d, %d}", resolution, RESOLUTION_50m, RESOLUTION_150m, RESOLUTION_1km, RESOLUTION_10km);
}
}
if (mode == Mode.DEFAULT) {
switch (resolution) {
case RESOLUTION_50m:
mode = Mode.SRTM_GC;
break;
case RESOLUTION_150m:
mode = Mode.SRTM_GC;
break;
case RESOLUTION_1km:
mode = Mode.GSHHS;
break;
case RESOLUTION_10km:
mode = Mode.GSHHS;
break;
default:
String msg = String.format("Unknown resolution for setting default mode '%d'. Known resolutions are {%d, %d, %d, %d}", resolution, RESOLUTION_50m, RESOLUTION_150m, RESOLUTION_1km, RESOLUTION_10km);
}
}
if (mode != Mode.SRTM_GC && mode != Mode.GSHHS && mode != Mode.MODIS) {
throw new IllegalArgumentException(
MessageFormat.format("Mode needs to be {0}, {1} or {2}.", Mode.SRTM_GC, Mode.GSHHS, Mode.MODIS));
}
this.mode = mode;
this.resolution = resolution;
this.filename = filename;
final File auxdataDir = ResourceInstallationUtils.installAuxdata(WatermaskClassifier.class, filename).getParentFile();
if (mode == Mode.GSHHS) {
ImageDescriptor gshhsDescriptor = getGshhsDescriptor(auxdataDir);
if (gshhsDescriptor != null) {
gshhsImage = createImage(auxdataDir, gshhsDescriptor);
}
} else if (mode == Mode.SRTM_GC) {
centerImage = createSrtmImage(auxdataDir);
ImageDescriptor northDescriptor = getNorthDescriptor(auxdataDir);
aboveSixtyNorthImage = createImage(auxdataDir, northDescriptor);
ImageDescriptor southDescriptor = getSouthDescriptor(auxdataDir);
belowSixtySouthImage = createImage(auxdataDir, southDescriptor);
}
}
private ImageDescriptor getGshhsDescriptor(File auxdataDir) {
ImageDescriptor imageDescriptor = null;
String zipname = filename;
if (resolution == RESOLUTION_1km) {
imageDescriptor = new ImageDescriptorBuilder()
.width(GSHHS_1_IMAGE_WIDTH)
.height(GSHHS_1_IMAGE_HEIGHT)
.tileWidth(GSHHS_1_TILE_WIDTH)
.tileHeight(GSHHS_1_TILE_HEIGHT)
.auxdataDir(auxdataDir)
.zipFileName(zipname)
.build();
} else if (resolution == RESOLUTION_10km) {
imageDescriptor = new ImageDescriptorBuilder()
.width(GSHHS_10_IMAGE_WIDTH)
.height(GSHHS_10_IMAGE_HEIGHT)
.tileWidth(GSHHS_10_TILE_WIDTH)
.tileHeight(GSHHS_10_TILE_HEIGHT)
.auxdataDir(auxdataDir)
.zipFileName(zipname)
.build();
}
return imageDescriptor;
}
private ImageDescriptor getSouthDescriptor(File auxdataDir) {
ImageDescriptor southDescriptor;
switch (mode) {
case MODIS:
southDescriptor = new ImageDescriptorBuilder()
.width(MODIS_IMAGE_WIDTH)
.height(MODIS_IMAGE_HEIGHT)
.tileWidth(MODIS_TILE_WIDTH)
.tileHeight(MODIS_TILE_HEIGHT)
.auxdataDir(auxdataDir)
.zipFileName("MODIS_south_water_mask.zip")
.build();
break;
case SRTM_GC:
southDescriptor = new ImageDescriptorBuilder()
.width(GC_IMAGE_WIDTH)
.height(GC_IMAGE_HEIGHT)
.tileWidth(GC_TILE_WIDTH)
.tileHeight(GC_TILE_HEIGHT)
.auxdataDir(auxdataDir)
.zipFileName(GC_WATER_MASK_FILE)
.build();
break;
default:
String msg = String.format("Unknown mode '%d'. Known modes are {%d, %d, %d}", mode, Mode.MODIS, Mode.SRTM_GC, Mode.GSHHS);
throw new IllegalArgumentException(msg);
}
return southDescriptor;
}
//
// private ImageDescriptor getSouthDescriptor(File auxdataDir) {
// return new ImageDescriptorBuilder()
// .width(MODIS_IMAGE_WIDTH)
// .height(MODIS_IMAGE_HEIGHT)
// .tileWidth(MODIS_TILE_WIDTH)
// .tileHeight(MODIS_TILE_HEIGHT)
// .auxdataDir(auxdataDir)
// .zipFileName("MODIS_south_water_mask.zip")
// .build();
// }
private ImageDescriptor getNorthDescriptor(File auxdataDir) {
ImageDescriptor northDescriptor;
switch (mode) {
case MODIS:
northDescriptor = new ImageDescriptorBuilder()
.width(MODIS_IMAGE_WIDTH)
.height(MODIS_IMAGE_HEIGHT)
.tileWidth(MODIS_TILE_WIDTH)
.tileHeight(MODIS_TILE_HEIGHT)
.auxdataDir(auxdataDir)
.zipFileName("MODIS_north_water_mask.zip")
.build();
break;
case SRTM_GC:
northDescriptor = new ImageDescriptorBuilder()
.width(GC_IMAGE_WIDTH)
.height(GC_IMAGE_HEIGHT)
.tileWidth(GC_TILE_WIDTH)
.tileHeight(GC_TILE_HEIGHT)
.auxdataDir(auxdataDir)
.zipFileName(GC_WATER_MASK_FILE)
.build();
break;
default:
String msg = String.format("Unknown mode '%d'. Known modes are {%d, %d, %d}", mode, Mode.MODIS, Mode.SRTM_GC, Mode.GSHHS);
throw new IllegalArgumentException(msg);
}
return northDescriptor;
}
private SRTMOpImage createSrtmImage(File auxdataDir) throws IOException {
int tileSize = WatermaskUtils.computeSideLength(resolution);
int width = tileSize * 360;
int height = tileSize * 180;
final Properties properties = new Properties();
properties.setProperty("width", String.valueOf(width));
properties.setProperty("height", String.valueOf(height));
properties.setProperty("tileWidth", String.valueOf(tileSize));
properties.setProperty("tileHeight", String.valueOf(tileSize));
final URL imageProperties = getClass().getResource("image.properties");
properties.load(imageProperties.openStream());
// File zipFile = new File(auxdataDir, resolution + "m.zip");
File zipFile = new File(auxdataDir, filename);
return SRTMOpImage.create(properties, zipFile);
}
private PNGSourceImage createImage(File auxdataDir2, ImageDescriptor descriptor) throws IOException {
int width = descriptor.getImageWidth();
int tileWidth = descriptor.getTileWidth();
int height = descriptor.getImageHeight();
int tileHeight = descriptor.getTileHeight();
final Properties properties = new Properties();
properties.setProperty("width", String.valueOf(width));
properties.setProperty("height", String.valueOf(height));
properties.setProperty("tileWidth", String.valueOf(tileWidth));
properties.setProperty("tileHeight", String.valueOf(tileHeight));
final URL imageProperties = getClass().getResource("image.properties");
properties.load(imageProperties.openStream());
final File auxdataDir = descriptor.getAuxdataDir();
final String zipFileName = descriptor.getZipFileName();
File zipFile = new File(auxdataDir, zipFileName);
return PNGSourceImage.create(properties, zipFile, mode, resolution);
}
/**
* Returns the sample value at the given geo-position, regardless of the source resolution.
*
* @param lat The latitude value.
* @param lon The longitude value.
* @return 0 if the given position is over land, 1 if it is over water, 2 if no definite statement can be made
* gov.nasa.gsfc.seadas.about the position.
*/
public int getWaterMaskSample(float lat, float lon) {
double tempLon = lon + 180.0;
if (tempLon >= 360) {
tempLon %= 360;
}
float normLat = Math.abs(lat - 90.0f);
if (tempLon < 0.0 || tempLon > 360.0 || normLat < 0.0 || normLat > 180.0) {
return INVALID_VALUE;
}
if (mode == Mode.GSHHS) {
return getSample(normLat, tempLon, 180.0, 360.0, 0.0, gshhsImage);
} else {
if (normLat < 150.0f && normLat > 30.0f) {
return getSample(normLat, tempLon, 180.0, 360.0, 0.0, centerImage);
} else if (normLat <= 30.0f) {
return getSample(normLat, tempLon, 30.0, 360.0, 0.0, aboveSixtyNorthImage);
} else if (normLat >= 150.0f) {
// return WATER_VALUE;
return getSample(normLat, tempLon, 30.0, 360.0, 0.0, belowSixtySouthImage);
}
}
throw new IllegalStateException("Cannot come here");
}
private int getSample(double lat, double lon, double latDiff, double lonDiff, double offset, OpImage image) {
final double pixelSizeX = lonDiff / image.getWidth();
final double pixelSizeY = latDiff / image.getHeight();
final int x = (int) Math.floor(lon / pixelSizeX);
final int y = (int) (Math.floor((lat - offset) / pixelSizeY));
final Raster tile = image.getTile(image.XToTileX(x), image.YToTileY(y));
if (tile == null) {
return INVALID_VALUE;
}
return tile.getSample(x, y, 0);
}
/**
* Returns the fraction of water for the given region, considering a subsampling factor.
*
* @param geoCoding The geo coding of the product the watermask fraction shall be computed for.
* @param pixelPos The pixel position the watermask fraction shall be computed for.
* @param subsamplingFactorX The factor between the high resolution water mask and the - lower resolution -
* source image in x direction. Only values in [1..M] are sensible,
* with M = (source image resolution in m/pixel) / (50 m/pixel)
* @param subsamplingFactorY The factor between the high resolution water mask and the - lower resolution -
* source image in y direction. Only values in [1..M] are sensible,
* with M = (source image resolution in m/pixel) / (50 m/pixel)
* @return The fraction of water in the given geographic rectangle, in the range [0..100].
*/
public byte getWaterMaskFraction(GeoCoding geoCoding, PixelPos pixelPos, int subsamplingFactorX, int subsamplingFactorY) {
float valueSum = 0;
double xStep = 1.0 / subsamplingFactorX;
double yStep = 1.0 / subsamplingFactorY;
final GeoPos geoPos = new GeoPos();
final PixelPos currentPos = new PixelPos();
int invalidCount = 0;
for (int sx = 0; sx < subsamplingFactorX; sx++) {
currentPos.x = (float) (pixelPos.x + sx * xStep);
for (int sy = 0; sy < subsamplingFactorY; sy++) {
currentPos.y = (float) (pixelPos.y + sy * yStep);
geoCoding.getGeoPos(currentPos, geoPos);
int waterMaskSample = getWaterMaskSample(geoPos);
if (waterMaskSample != WatermaskClassifier.INVALID_VALUE) {
valueSum += waterMaskSample;
} else {
invalidCount++;
}
}
}
return computeAverage(subsamplingFactorX, subsamplingFactorY, valueSum, invalidCount);
}
private byte computeAverage(int subsamplingFactorX, int subsamplingFactorY, float valueSum, int invalidCount) {
final boolean allValuesInvalid = invalidCount == subsamplingFactorX * subsamplingFactorY;
if (allValuesInvalid) {
return WatermaskClassifier.INVALID_VALUE;
} else {
return (byte) (100 * valueSum / (subsamplingFactorX * subsamplingFactorY));
}
}
private int getWaterMaskSample(GeoPos geoPos) {
final int waterMaskSample;
if (geoPos.isValid()) {
waterMaskSample = getWaterMaskSample((float)geoPos.lat, (float)geoPos.lon);
} else {
waterMaskSample = WatermaskClassifier.INVALID_VALUE;
}
return waterMaskSample;
}
/**
* Classifies the given geo-position as water or land.
*
* @param lat The latitude value.
* @param lon The longitude value.
* @return true, if the geo-position is over water, false otherwise.
* @throws java.io.IOException If some IO-error occurs reading the source file.
*/
public boolean isWater(float lat, float lon) throws IOException {
final int waterMaskSample = getWaterMaskSample(lat, lon);
return waterMaskSample == WATER_VALUE;
}
}
| 21,065 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
WatermaskOp.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/operator/WatermaskOp.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.watermask.operator;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.gpf.Operator;
import org.esa.snap.core.gpf.OperatorException;
import org.esa.snap.core.gpf.OperatorSpi;
import org.esa.snap.core.gpf.Tile;
import org.esa.snap.core.gpf.annotations.OperatorMetadata;
import org.esa.snap.core.gpf.annotations.Parameter;
import org.esa.snap.core.gpf.annotations.SourceProduct;
import org.esa.snap.core.gpf.annotations.TargetProduct;
import org.esa.snap.core.util.ProductUtils;
import org.esa.snap.rcp.imgfilter.model.Filter;
import java.awt.*;
import java.io.IOException;
import java.text.MessageFormat;
/**
* The watermask operator is a GPF-Operator. It takes the geographic bounds of the input product and creates a new
* product with the same bounds. The output product contains a single band, which is a land/water fraction mask.
* For each pixel, it contains the fraction of water; a value of 0.0 indicates land, a value of 100.0 indicates water,
* and every value in between indicates a mixed pixel.
* <br/>
* The water mask is based on data given by SRTM-shapefiles between 60° north and 60° south, and by the GlobCover world
* map above 60° north.
* Since the base data may exhibit a higher resolution than the input product, a subsampling ≥1 may be specified;
* therefore, mixed pixels may occur.
*
* @author Daniel Knowles, Marco Peters, Thomas Storm
*/
@SuppressWarnings({"FieldCanBeLocal"})
@OperatorMetadata(alias = "CoastlineLandWaterMasks",
category = "Raster/Masks",
version = "1.0",
authors = "Daniel Knowles, Marco Peters",
copyright = "",
description = "Operator creating a target product with a single band containing a land/water-mask," +
" which is based on SRTM-shapefiles (between 60° north and 60° south) and the " +
"GlobCover world map (above 60° north) and therefore very accurate.")
public class WatermaskOp extends Operator {
public static final String LAND_WATER_FRACTION_BAND_NAME = "water_fraction";
public static final String LAND_WATER_FRACTION_SMOOTHED_BAND_NAME = "water_fraction_mean";
public static final String COAST_BAND_NAME = "coast";
@SourceProduct(alias = "source", description = "The Product the land/water-mask shall be computed for.",
label = "Name")
private Product sourceProduct;
@Parameter(description = "Specifies on which resolution the water mask shall be based. This needs to match data worldSourceDataFilename resolution", unit = "m/pixel",
label = "Resolution", defaultValue = "1000", valueSet = {"50", "150", "1000", "10000"}, notNull = false)
private int resolution;
@Parameter(description = "Data source file for determining land/water: if default then determined based on selected resolution",
label = "worldSourceDataFilename", defaultValue = "DEFAULT",
valueSet = {"DEFAULT", "50m.zip", "150m.zip", "GSHHS_water_mask_1km.zip", "GSHHS_water_mask_10km.zip"}, notNull = false)
private String worldSourceDataFilename;
@Parameter(description = "Specifies the factor to divide up a target pixel when determining match with land source data" +
". A value of '1' means no subsampling at all.",
label = "Supersampling factor", defaultValue = "3", notNull = false)
private int superSamplingFactor;
@Parameter(description = "Specifies the watermaskClassifier mode: uses SRTM_GC for the 50m and 150m files",
label = "Mode", defaultValue = "DEFAULT", valueSet = {"DEFAULT", "GSHHS", "SRTM_GC"}, notNull = false)
private WatermaskClassifier.Mode mode;
@Parameter(description = "Output file is copy of source file with land data added",
label = "Copy Source File", defaultValue = "true", notNull = false)
private boolean copySourceFile;
@Parameter(description = "Specifies a filter grid size to apply to determine the coastal mask. (e.g. 3 = 3x3 matrix)",
label = "Coastal grid box size", defaultValue = "3", notNull = false)
private int coastalGridSize;
@Parameter(description = "Specifies percent of coastal grid matrix to mask",
label = "Coastal size tolerance", defaultValue = "50", notNull = false)
private int coastalSizeTolerance;
@Parameter(description = "Color of water mask",
label = "Color of water mask", defaultValue = "0, 125, 255", notNull = false)
private Color waterMaskColor;
@Parameter(description = "Color of coastal mask",
label = "Color of coastal mask", defaultValue = "0, 0, 0", notNull = false)
private Color coastalMaskColor;
@Parameter(description = "Color of land mask",
label = "Color of land mask", defaultValue = "51, 51, 51", notNull = false)
private Color landMaskColor;
@Parameter(description = "Includes the masks (otherwise only land band is created)",
label = "includeMasks", defaultValue = "true", notNull = false)
private boolean includeMasks;
@Parameter(description = "Water mask transparency",
label = "Water mask transparency", defaultValue = "0", notNull = false)
private double waterMaskTransparency;
@Parameter(description = "Land mask transparency",
label = "Land mask transparency", defaultValue = "0", notNull = false)
private double landMaskTransparency;
@Parameter(description = "Coastal mask transparency",
label = "Coastal mask transparency", defaultValue = "0", notNull = false)
private double coastalMaskTransparency;
// @Parameter(description = "Specifies the resolutionInfo which contains resolution, mode",
// label = "Resolution Info", defaultValue = "1 km GSHHS", notNull = true)
// private SourceFileInfo resolutionInfo;
@TargetProduct
private Product targetProduct;
private WatermaskClassifier classifier;
@Override
public void initialize() throws OperatorException {
validateParameter();
validateSourceProduct();
initTargetProduct();
try {
classifier = new WatermaskClassifier(resolution, mode, worldSourceDataFilename);
} catch (IOException e) {
throw new OperatorException("Error creating class WatermaskClassifier.", e);
}
}
@Override
public void computeTile(Band targetBand, Tile targetTile, ProgressMonitor pm) throws OperatorException {
final Rectangle rectangle = targetTile.getRectangle();
try {
final String targetBandName = targetBand.getName();
final PixelPos pixelPos = new PixelPos();
final GeoCoding geoCoding = sourceProduct.getSceneGeoCoding();
for (int x = rectangle.x; x < rectangle.x + rectangle.width; x++) {
for (int y = rectangle.y; y < rectangle.y + rectangle.height; y++) {
pixelPos.x = x;
pixelPos.y = y;
int dataValue = 0;
if (targetBandName.equals(LAND_WATER_FRACTION_BAND_NAME)) {
dataValue = classifier.getWaterMaskFraction(geoCoding, pixelPos,
superSamplingFactor,
superSamplingFactor);
} else if (targetBandName.equals(COAST_BAND_NAME)) {
final boolean coastline = isCoastline(geoCoding, pixelPos,
superSamplingFactor,
superSamplingFactor);
dataValue = coastline ? 1 : 0;
}
targetTile.setSample(x, y, dataValue);
}
}
} catch (Exception e) {
throw new OperatorException("Error computing tile '" + targetTile.getRectangle().toString() + "'.", e);
}
}
private boolean isCoastline(GeoCoding geoCoding, PixelPos pixelPos, int superSamplingX, int superSamplingY) {
double xStep = 1.0 / superSamplingX;
double yStep = 1.0 / superSamplingY;
final GeoPos geoPos = new GeoPos();
final PixelPos currentPos = new PixelPos();
for (int sx = 0; sx < superSamplingX; sx++) {
currentPos.x = (float) (pixelPos.x + sx * xStep);
for (int sy = 0; sy < superSamplingY; sy++) {
currentPos.y = (float) (pixelPos.y + sy * yStep);
geoCoding.getGeoPos(currentPos, geoPos);
// Todo: Implement coastline algorithm here
//
}
}
return false;
}
private void validateParameter() {
if (resolution != WatermaskClassifier.RESOLUTION_50m &&
resolution != WatermaskClassifier.RESOLUTION_150m &&
resolution != WatermaskClassifier.RESOLUTION_1km &&
resolution != WatermaskClassifier.RESOLUTION_10km) {
throw new OperatorException(String.format("Resolution needs to be either %d, %d, %d or %d.",
WatermaskClassifier.RESOLUTION_50m,
WatermaskClassifier.RESOLUTION_150m,
WatermaskClassifier.RESOLUTION_1km,
WatermaskClassifier.RESOLUTION_10km));
}
if (superSamplingFactor < 1) {
String message = MessageFormat.format(
"Supersampling factor needs to be greater than or equal to 1; was: ''{0}''.", superSamplingFactor);
throw new OperatorException(message);
}
}
private void validateSourceProduct() {
final GeoCoding geoCoding = sourceProduct.getSceneGeoCoding();
if (geoCoding == null) {
throw new OperatorException("The source product must be geo-coded.");
}
if (!geoCoding.canGetGeoPos()) {
throw new OperatorException("The geo-coding of the source product can not be used.\n" +
"It does not provide the geo-position for a pixel position.");
}
}
private void copySourceToTarget() {
// final HashMap<String, Object> copyOpParameters = new HashMap<String, Object>();
//
//
// HashMap<String, Product> copyOpProducts = new HashMap<String, Product>();
// copyOpProducts.put("source", sourceProduct);
// targetProduct = GPF.createProduct("Copy", copyOpParameters, copyOpProducts);
int width = sourceProduct.getSceneRasterWidth();
int height = sourceProduct.getSceneRasterHeight();
targetProduct = new Product(sourceProduct.getName() + "_LW-Mask", "CoastlineLandWaterMasks", width, height);
ProductUtils.copyMetadata(sourceProduct, targetProduct);
ProductUtils.copyTiePointGrids(sourceProduct, targetProduct);
copyFlagCodingsIfPossible(sourceProduct, targetProduct);
copyIndexCodingsIfPossible(sourceProduct, targetProduct);
// copying GeoCoding from product to product, bands which do not have a GC yet will be geo-coded afterwards
ProductUtils.copyGeoCoding(sourceProduct, targetProduct);
ProductUtils.copyMasks(sourceProduct, targetProduct);
ProductUtils.copyVectorData(sourceProduct, targetProduct);
targetProduct.setDescription(sourceProduct.getDescription());
if (sourceProduct.getStartTime() != null && sourceProduct.getEndTime() != null) {
targetProduct.setStartTime(sourceProduct.getStartTime());
targetProduct.setEndTime(sourceProduct.getEndTime());
}
}
private static void copyFlagCodingsIfPossible(Product source, Product target) {
int numCodings = source.getFlagCodingGroup().getNodeCount();
for (int n = 0; n < numCodings; n++) {
FlagCoding sourceFlagCoding = source.getFlagCodingGroup().get(n);
final String sourceFlagCodingName = sourceFlagCoding.getName();
if (target.containsBand(sourceFlagCodingName) &&
target.getBand(sourceFlagCodingName).hasIntPixels()) {
ProductUtils.copyFlagCoding(sourceFlagCoding, target);
target.getBand(sourceFlagCodingName).setSampleCoding(sourceFlagCoding);
}
}
}
private static void copyIndexCodingsIfPossible(Product source, Product target) {
int numCodings = source.getIndexCodingGroup().getNodeCount();
for (int n = 0; n < numCodings; n++) {
IndexCoding sourceIndexCoding = source.getIndexCodingGroup().get(n);
final String sourceIndexCodingName = sourceIndexCoding.getName();
if (target.containsBand(sourceIndexCodingName) &&
target.getBand(sourceIndexCodingName).hasIntPixels()) {
ProductUtils.copyIndexCoding(sourceIndexCoding, target);
target.getBand(sourceIndexCodingName).setSampleCoding(sourceIndexCoding);
}
}
}
private void initTargetProduct() {
if (copySourceFile) {
copySourceToTarget();
} else {
targetProduct = new Product("LW-Mask", ProductData.TYPESTRING_UINT8, sourceProduct.getSceneRasterWidth(),
sourceProduct.getSceneRasterHeight());
}
final Band waterBand = targetProduct.addBand(LAND_WATER_FRACTION_BAND_NAME, ProductData.TYPE_FLOAT32);
waterBand.setNoDataValue(WatermaskClassifier.INVALID_VALUE);
waterBand.setNoDataValueUsed(true);
// final Kernel arithmeticMean3x3Kernel = new Kernel(3, 3, 1.0 / 9.0,
// new double[]{
// +1, +1, +1,
// +1, +1, +1,
// +1, +1, +1,
// });
if (includeMasks) {
final Filter meanFilter = new Filter("Mean " + Integer.toString(coastalGridSize) + "x" + Integer.toString(coastalGridSize), "mean" + Integer.toString(coastalGridSize), Filter.Operation.MEAN, coastalGridSize, coastalGridSize);
final Kernel meanKernel = new Kernel(meanFilter.getKernelWidth(),
meanFilter.getKernelHeight(),
meanFilter.getKernelOffsetX(),
meanFilter.getKernelOffsetY(),
1.0 / meanFilter.getKernelQuotient(),
meanFilter.getKernelElements());
int count = 1;
// final ConvolutionFilterBand filteredCoastlineBand = new ConvolutionFilterBand(
// LAND_WATER_FRACTION_SMOOTHED_BAND_NAME,
// waterBand,
// arithmeticMean3x3Kernel, count);
String filteredCoastlineBandName = LAND_WATER_FRACTION_SMOOTHED_BAND_NAME + Integer.toString(coastalGridSize);
final FilterBand filteredCoastlineBand = new GeneralFilterBand(filteredCoastlineBandName, waterBand, GeneralFilterBand.OpType.MEAN, meanKernel, count);
if (waterBand instanceof Band) {
ProductUtils.copySpectralBandProperties((Band) waterBand, filteredCoastlineBand);
}
targetProduct.addBand(filteredCoastlineBand);
final ProductNodeGroup<Mask> maskGroup = targetProduct.getMaskGroup();
double min = 50 - coastalSizeTolerance / 2;
double max = 50 + coastalSizeTolerance / 2;
String coastlineMaskExpression = filteredCoastlineBandName + " > " + Double.toString(min) + " and " + filteredCoastlineBandName + " < " + Double.toString(max);
Mask coastlineMask = Mask.BandMathsType.create(
"CoastalMask",
"Coastal masked pixels",
targetProduct.getSceneRasterWidth(),
targetProduct.getSceneRasterHeight(),
coastlineMaskExpression,
coastalMaskColor,
coastalMaskTransparency);
maskGroup.add(coastlineMask);
Mask landMask = Mask.BandMathsType.create(
"LandMask",
"Land masked pixels",
targetProduct.getSceneRasterWidth(),
targetProduct.getSceneRasterHeight(),
LAND_WATER_FRACTION_BAND_NAME + "== 0",
landMaskColor,
landMaskTransparency);
maskGroup.add(landMask);
Mask waterMask = Mask.BandMathsType.create(
"WaterMask",
"Water masked pixels",
targetProduct.getSceneRasterWidth(),
targetProduct.getSceneRasterHeight(),
LAND_WATER_FRACTION_BAND_NAME + "> 0",
waterMaskColor,
waterMaskTransparency);
maskGroup.add(waterMask);
String[] bandNames = targetProduct.getBandNames();
for (String bandName : bandNames) {
RasterDataNode raster = targetProduct.getRasterDataNode(bandName);
}
}
ProductUtils.copyGeoCoding(sourceProduct, targetProduct);
}
@SuppressWarnings({"UnusedDeclaration"})
public static class Spi extends OperatorSpi {
public Spi() {
super(WatermaskOp.class);
}
}
}
| 17,920 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ModisSouthImage.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/operator/ModisSouthImage.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.watermask.operator;
import org.esa.snap.core.image.ImageHeader;
import org.esa.snap.core.util.ImageUtils;
import org.esa.snap.core.util.jai.SingleBandedSampleModel;
import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.SourcelessOpImage;
import java.awt.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* OpImage to read from MODIS-based water mask images for below 60° south.
*
* @author Thomas Storm
*/
public class ModisSouthImage extends SourcelessOpImage {
private final ZipFile zipFile;
static ModisSouthImage create(Properties properties, File zipFile) throws IOException {
final ImageHeader imageHeader = ImageHeader.load(properties, null);
return new ModisSouthImage(imageHeader, zipFile);
}
private ModisSouthImage(ImageHeader imageHeader, File zipFile) throws IOException {
super(imageHeader.getImageLayout(),
null,
ImageUtils.createSingleBandedSampleModel(DataBuffer.TYPE_BYTE,
imageHeader.getImageLayout().getSampleModel(null).getWidth(),
imageHeader.getImageLayout().getSampleModel(null).getHeight()),
imageHeader.getImageLayout().getMinX(null),
imageHeader.getImageLayout().getMinY(null),
imageHeader.getImageLayout().getWidth(null),
imageHeader.getImageLayout().getHeight(null));
this.zipFile = new ZipFile(zipFile);
// this image uses its own tile cache in order not to disturb the GPF tile cache.
setTileCache(JAI.createTileCache(50L * 1024 * 1024));
}
@Override
public Raster computeTile(int tileX, int tileY) {
Raster raster;
try {
raster = computeRawRaster(tileX, tileY);
} catch (IOException e) {
throw new RuntimeException(MessageFormat.format("Failed to read image tile ''{0} | {1}''.", tileX, tileY), e);
}
return raster;
}
private Raster computeRawRaster(int tileX, int tileY) throws IOException {
final String fileName = getFileName(tileX, tileY);
final WritableRaster targetRaster = createWritableRaster(tileX, tileY);
final ZipEntry zipEntry = zipFile.getEntry(fileName);
InputStream inputStream = null;
try {
inputStream = zipFile.getInputStream(zipEntry);
BufferedImage image = ImageIO.read(inputStream);
Raster imageData = image.getData();
for (int x = 0; x < imageData.getWidth(); x++) {
int xPos = tileXToX(tileX) + x;
for (int y = 0; y < imageData.getHeight(); y++) {
byte sample = (byte) imageData.getSample(x, y, 0);
sample = (byte) Math.abs(sample - 1);
int yPos = tileYToY(tileY) + y;
targetRaster.setSample(xPos, yPos, 0, sample);
}
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return targetRaster;
}
private WritableRaster createWritableRaster(int tileX, int tileY) {
final Point location = new Point(tileXToX(tileX), tileYToY(tileY));
final SampleModel sampleModel = new SingleBandedSampleModel(DataBuffer.TYPE_BYTE, WatermaskClassifier.GC_TILE_WIDTH, WatermaskClassifier.GC_TILE_HEIGHT);
return createWritableRaster(sampleModel, location);
}
private String getFileName(int tileX, int tileY) {
return String.format("%d-%d.png", tileX, tileY);
}
}
| 4,575 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
SRTMOpImage.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/operator/SRTMOpImage.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.watermask.operator;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.image.ImageHeader;
import org.esa.snap.core.util.ImageUtils;
import javax.media.jai.JAI;
import javax.media.jai.SourcelessOpImage;
import java.awt.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
/**
* Responsible for tiled access on the data below 60° northern latitude.
*
* @author Thomas Storm
*/
public class SRTMOpImage extends SourcelessOpImage {
private ZipFile zipFile;
private Properties missingTiles;
private SampleModel rawImgSampleModel;
private WritableRaster landRaster;
private WritableRaster waterRaster;
private WritableRaster invalidRaster;
public static SRTMOpImage create(Properties defaultImageProperties, File zipFile) throws IOException {
final ImageHeader imageHeader = ImageHeader.load(defaultImageProperties, null);
return new SRTMOpImage(imageHeader, zipFile);
}
private SRTMOpImage(ImageHeader imageHeader, File zipFile) throws IOException {
super(imageHeader.getImageLayout(),
null,
ImageUtils.createSingleBandedSampleModel(DataBuffer.TYPE_BYTE,
imageHeader.getImageLayout().getSampleModel(null).getWidth(),
imageHeader.getImageLayout().getSampleModel(null).getHeight()),
imageHeader.getImageLayout().getMinX(null),
imageHeader.getImageLayout().getMinY(null),
imageHeader.getImageLayout().getWidth(null),
imageHeader.getImageLayout().getHeight(null));
// this.zipFile = new ZipFile(zipFile);
try {
this.zipFile = new ZipFile(zipFile);
} catch (ZipException e) {
throw new ZipException();
} catch (IOException e) {
throw new IOException();
}
missingTiles = new Properties();
missingTiles.load(getClass().getResourceAsStream("MissingTiles.properties"));
// this image uses its own tile cache in order not to disturb the GPF tile cache.
setTileCache(JAI.createTileCache(50L * 1024 * 1024));
rawImgSampleModel = imageHeader.getImageLayout().getSampleModel(null);
}
@Override
public Raster computeTile(int tileX, int tileY) {
try {
return readRawDataTile(tileX, tileY);
} catch (IOException e) {
throw new RuntimeException(MessageFormat.format("Failed to read image tile ''{0} | {1}''.", tileX, tileY), e);
}
}
@Override
public void dispose() {
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private Raster readRawDataTile(int tileX, int tileY) throws IOException {
final Point location = new Point(tileXToX(tileX), tileYToY(tileY));
// 89 not 90, because tile coordinates are given for lower left corner
final String imgFileName = WatermaskUtils.createImgFileName(89 - tileY, tileX - 180);
final String missingTileValue = missingTiles.getProperty(imgFileName.substring(0, imgFileName.indexOf('.')));
final boolean tileIsMissing = missingTileValue != null;
if (tileIsMissing) {
final byte tileValue = Byte.parseByte(missingTileValue);
switch (tileValue) {
case 0:
return getLandRaster(location, tileValue);
case 1:
return getWaterRaster(location, tileValue);
default:
return getInvalidRaster(location, tileValue);
}
}
final InputStream inputStream = createInputStream(imgFileName);
final WritableRaster targetRaster = createWritableRaster(rawImgSampleModel, location);
final byte[] data = ((DataBufferByte) targetRaster.getDataBuffer()).getData();
try {
int count = 0;
int amount = data.length;
while (count < data.length) {
if (count + amount > data.length) {
amount = data.length - count;
}
count += inputStream.read(data, count, amount);
}
Assert.state(count == data.length, "Not all data have been read.");
} finally {
inputStream.close();
}
return targetRaster;
}
private Raster getLandRaster(Point location, byte tileValue) {
if (landRaster == null) {
landRaster = createRaster(tileValue);
}
return landRaster.createTranslatedChild(location.x, location.y);
}
private Raster getWaterRaster(Point location, byte tileValue) {
if (waterRaster == null) {
waterRaster = createRaster(tileValue);
}
return waterRaster.createTranslatedChild(location.x, location.y);
}
private Raster getInvalidRaster(Point location, byte tileValue) {
if (invalidRaster == null) {
invalidRaster = createRaster(tileValue);
}
return invalidRaster.createTranslatedChild(location.x, location.y);
}
private WritableRaster createRaster(byte tileValue) {
WritableRaster raster = createWritableRaster(sampleModel, new Point(0, 0));
final byte[] data = ((DataBufferByte) raster.getDataBuffer()).getData();
Arrays.fill(data, tileValue);
return raster;
}
private InputStream createInputStream(String imgFileName) throws IOException {
final ZipEntry entry = zipFile.getEntry(imgFileName);
return zipFile.getInputStream(entry);
}
}
| 6,585 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
PNGSourceImage.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/operator/PNGSourceImage.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.watermask.operator;
import org.esa.snap.core.image.ImageHeader;
import org.esa.snap.core.util.ImageUtils;
import org.esa.snap.core.util.jai.SingleBandedSampleModel;
import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.SourcelessOpImage;
import java.awt.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* OpImage to read from GlobCover-based water mask images.
*
* @author Thomas Storm
*/
public class PNGSourceImage extends SourcelessOpImage {
private final ZipFile zipFile;
private WatermaskClassifier.Mode mode;
private int resolution;
static PNGSourceImage create(Properties properties, File zipFile, WatermaskClassifier.Mode mode, int resolution) throws IOException {
final ImageHeader imageHeader = ImageHeader.load(properties, null);
return new PNGSourceImage(imageHeader, zipFile,mode,resolution);
}
private PNGSourceImage(ImageHeader imageHeader, File zipFile, WatermaskClassifier.Mode mode, int resolution) throws IOException {
super(imageHeader.getImageLayout(),
null,
ImageUtils.createSingleBandedSampleModel(DataBuffer.TYPE_BYTE,
imageHeader.getImageLayout().getSampleModel(null).getWidth(),
imageHeader.getImageLayout().getSampleModel(null).getHeight()),
imageHeader.getImageLayout().getMinX(null),
imageHeader.getImageLayout().getMinY(null),
imageHeader.getImageLayout().getWidth(null),
imageHeader.getImageLayout().getHeight(null));
this.zipFile = new ZipFile(zipFile);
this.mode = mode;
this.resolution = resolution;
// this image uses its own tile cache in order not to disturb the GPF tile cache.
setTileCache(JAI.createTileCache(50L * 1024 * 1024));
}
@Override
public Raster computeTile(int tileX, int tileY) {
Raster raster;
try {
raster = computeRawRaster(tileX, tileY);
} catch (IOException e) {
throw new RuntimeException(MessageFormat.format("Failed to read image tile ''{0} | {1}''.", tileX, tileY), e);
}
return raster;
}
private Raster computeRawRaster(int tileX, int tileY) throws IOException {
final String fileName = getFileName(tileX, tileY);
final WritableRaster targetRaster = createWritableRaster(tileX, tileY);
final ZipEntry zipEntry = zipFile.getEntry(fileName);
InputStream inputStream = null;
try {
inputStream = zipFile.getInputStream(zipEntry);
BufferedImage image = ImageIO.read(inputStream);
Raster imageData = image.getData();
for (int y = 0; y < imageData.getHeight(); y++) {
int yPos = tileYToY(tileY) + y;
for (int x = 0; x < imageData.getWidth(); x++) {
byte sample = (byte) imageData.getSample(x, y, 0);
sample = (byte) Math.abs(sample - 1);
int xPos = tileXToX(tileX) + x;
targetRaster.setSample(xPos, yPos, 0, sample);
}
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return targetRaster;
}
private WritableRaster createWritableRaster(int tileX, int tileY) {
final Point location = new Point(tileXToX(tileX), tileYToY(tileY));
final SampleModel sampleModel = new SingleBandedSampleModel(DataBuffer.TYPE_BYTE, getTileWidth(), getTileHeight());
return createWritableRaster(sampleModel, location);
}
private String getFileName(int tileX, int tileY) {
if (mode == WatermaskClassifier.Mode.GSHHS){
String res = String.valueOf(resolution/1000);
return String.format("gshhs_%s_%02d_%02d.png", res, tileY, tileX);
} else {
return String.format("%d_%d.png", tileX, tileY);
}
}
}
| 4,982 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ResourceInstallationUtils.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/util/ResourceInstallationUtils.java | package gov.nasa.gsfc.seadas.watermask.util;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.core.util.ResourceInstaller;
import org.esa.snap.core.util.SystemUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Path;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 1/17/13
* Time: 2:56 PM
* To change this template use File | Settings | File Templates.
*/
public class ResourceInstallationUtils {
public static String WATERMASK_MODULE_NAME = "seadas-watermask-operator";
public static String AUXDIR = "auxdata";
public static String WATERMASK_PATH = "gov/nasa/gsfc/seadas/watermask/";
public static String AUXPATH = WATERMASK_PATH + "operator/" + AUXDIR + "/";
public static String ICON_PATH = WATERMASK_PATH + "ui/icons/";
public static String getIconFilename(String icon, Class sourceClass) {
Path sourceUrl = ResourceInstaller.findModuleCodeBasePath(sourceClass);
String iconFilename = sourceUrl.toString() + ICON_PATH + icon;
return iconFilename;
}
public static void writeFileFromUrlOld(URL sourceUrl, File targetFile) throws IOException {
try {
InputStreamReader inputStreamReader = new InputStreamReader(sourceUrl.openStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
boolean exist = targetFile.createNewFile();
if (!exist) {
// file already exists
} else {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(targetFile));
String line;
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
}
bufferedWriter.close();
}
bufferedReader.close();
} catch (Exception e) {
throw new IOException("failed to write file from url: " + e.getMessage());
}
}
public static void writeFileFromUrl(URL sourceUrl, File targetFile) throws IOException {
HttpURLConnection connection = (HttpURLConnection) sourceUrl.openConnection();
connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream(targetFile);
FileCopy(in, out, 1024);
out.close();
}
public static void FileCopy(InputStream input, OutputStream output, int bufferSize) throws IOException {
byte[] buf = new byte[bufferSize];
int n = input.read(buf);
while (n >= 0) {
output.write(buf, 0, n);
n = input.read(buf);
}
output.flush();
}
public static File getTargetDir() {
File targetModuleDir = new File(SystemUtils.getApplicationDataDir(), WATERMASK_MODULE_NAME);
File targetDir = new File(targetModuleDir, AUXDIR);
return targetDir;
}
public static File getModuleDir(String moduleName) {
if (moduleName == null) {
return null;
}
return new File(SystemUtils.getApplicationDataDir(), moduleName);
}
public static File getTargetFile(String filename) {
File targetModuleDir = new File(SystemUtils.getApplicationDataDir(), WATERMASK_MODULE_NAME);
File targetDir = new File(targetModuleDir, AUXDIR);
File targetFile = new File(targetDir, filename);
return targetFile;
}
public static void installAuxdata(URL sourceUrl, String filename) throws IOException {
File targetFile = getTargetFile(filename);
try {
writeFileFromUrl(sourceUrl, targetFile);
} catch (IOException e) {
targetFile.delete();
throw new IOException();
}
}
public static File installAuxdata(Class sourceClass, String filename) {
File targetFile = getTargetFile(filename);
if (!targetFile.canRead()) {
Path moduleBasePath = ResourceInstaller.findModuleCodeBasePath(ResourceInstallationUtils.class);
Path sourcePath = moduleBasePath.resolve(AUXPATH).toAbsolutePath();
Path targetPath = targetFile.getParentFile().toPath();
ResourceInstaller resourceInstaller = new ResourceInstaller(sourcePath, targetPath);
try {
// System.out.println("source class: " + sourceClass.getName() + " module base path: " + moduleBasePath + " source: " + sourcePath);
// System.out.println("target: " + targetPath);
resourceInstaller.install(".*.zip", ProgressMonitor.NULL);
} catch (Exception e) {
e.printStackTrace();
System.out.println("file failed: " + e.getMessage());
}
}
return targetFile;
}
}
| 4,853 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ModisMosaicer.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/util/ModisMosaicer.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.watermask.util;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.image.ImageHeader;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Properties;
/**
* @author Thomas Storm
*/
public class ModisMosaicer {
static final int MODIS_IMAGE_WIDTH = 155520;
static final int MODIS_IMAGE_HEIGHT = 12960;
private static final int MODIS_TILE_WIDTH = 576;
private static final int MODIS_TILE_HEIGHT = 480;
static final int NORTH_MODE = 0;
public static void main(String[] args) throws IOException {
GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis();
final String pathname;
int mode = Integer.parseInt(args[0]);
if (mode == NORTH_MODE) {
pathname ="C:\\dev\\projects\\beam-watermask\\MODIS\\north";
} else {
pathname = "C:\\dev\\projects\\beam-watermask\\MODIS\\south";
}
final File[] files = new File(pathname).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".dim");
}
});
Product[] products = new Product[files.length];
for (int i = 0, filesLength = files.length; i < filesLength; i++) {
final Product product = ProductIO.readProduct(files[i]);
products[i] = product;
}
int width = MODIS_IMAGE_WIDTH;
int height = MODIS_IMAGE_HEIGHT;
final Properties properties = new Properties();
properties.setProperty("width", String.valueOf(width));
properties.setProperty("dataType", "0");
properties.setProperty("height", String.valueOf(height));
properties.setProperty("tileWidth", String.valueOf(MODIS_TILE_WIDTH));
properties.setProperty("tileHeight", String.valueOf(MODIS_TILE_HEIGHT));
final ImageHeader imageHeader = ImageHeader.load(properties, null);
final TemporaryMODISImage temporaryMODISImage = new TemporaryMODISImage(imageHeader, products, mode);
final Product product = new Product("MODIS_lw", "lw", MODIS_IMAGE_WIDTH, MODIS_IMAGE_HEIGHT);
final Band band = product.addBand("lw-mask", ProductData.TYPE_UINT8);
band.setSourceImage(temporaryMODISImage);
final String filePath;
if(mode == NORTH_MODE) {
filePath = "C:\\temp\\modis_north.dim";
} else {
filePath = "C:\\temp\\modis_south.dim";
}
ProductIO.writeProduct(product, filePath, "BEAM-DIMAP");
}
}
| 3,510 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
RasterImageOutputter.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/util/RasterImageOutputter.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.watermask.util;
import gov.nasa.gsfc.seadas.watermask.operator.WatermaskUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.core.util.math.Histogram;
import org.esa.snap.core.util.math.Range;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
class RasterImageOutputter {
private static final int TILE_WIDTH = WatermaskUtils.computeSideLength(50);
public static void main(String[] args) throws IOException {
final File file = new File(args[0]);
if (file.isDirectory()) {
final File[] imgFiles = file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".img");
}
});
final ExecutorService executorService = Executors.newFixedThreadPool(6);
for (File imgFile : imgFiles) {
final File outputFile = FileUtils.exchangeExtension(imgFile, ".png");
if (!outputFile.exists()) {
executorService.submit(new ImageWriterRunnable(imgFile, outputFile));
}
}
executorService.shutdown();
while (!executorService.isTerminated()) {
try {
executorService.awaitTermination(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
final InputStream inputStream;
if (file.getName().toLowerCase().endsWith(".zip")) {
ZipFile zipFile = new ZipFile(file);
String shapefile = args[1];
final ZipEntry entry = zipFile.getEntry(shapefile);
inputStream = zipFile.getInputStream(entry);
} else {
inputStream = new FileInputStream(file);
}
writeImage(inputStream, new File(args[args.length - 1]));
}
}
private static boolean writeImage(InputStream inputStream, File outputFile) throws IOException {
WritableRaster targetRaster = Raster.createPackedRaster(0, TILE_WIDTH, TILE_WIDTH, 1, 1,
new Point(0, 0));
final byte[] data = ((DataBufferByte) targetRaster.getDataBuffer()).getData();
inputStream.read(data);
final BufferedImage image = new BufferedImage(TILE_WIDTH, TILE_WIDTH, BufferedImage.TYPE_BYTE_BINARY);
image.setData(targetRaster);
boolean valid = validateImage(image);
ImageIO.write(image, "png", outputFile);
return valid;
}
private static boolean validateImage(BufferedImage image) {
final Histogram histogram = Histogram.computeHistogram(image, null, 3, new Range(0, 3));
final int[] binCounts = histogram.getBinCounts();
// In both bins must be values
for (int binCount : binCounts) {
if (binCount == 0) {
return false;
}
}
return true;
}
private static class ImageWriterRunnable implements Runnable {
private File inputFile;
private File outputFile;
private ImageWriterRunnable(File inputFile, File outputFile) {
this.inputFile = inputFile;
this.outputFile = outputFile;
}
@Override
public void run() {
InputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(inputFile);
final boolean valid = writeImage(fileInputStream, outputFile);
if(!valid) {
System.out.printf("Not valid: %s%n", outputFile);
}else {
System.out.printf("Written: %s%n", outputFile);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
} | 5,333 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ImageDescriptor.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/util/ImageDescriptor.java | package gov.nasa.gsfc.seadas.watermask.util;
import java.io.*;
/**
*/
public interface ImageDescriptor {
int getImageWidth();
int getImageHeight();
int getTileWidth();
int getTileHeight();
File getAuxdataDir();
String getZipFileName();
}
| 271 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MissingTilesPropertyFileGenerator.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/util/MissingTilesPropertyFileGenerator.java | package gov.nasa.gsfc.seadas.watermask.util;
import gov.nasa.gsfc.seadas.watermask.operator.WatermaskClassifier;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Product;
import java.awt.*;
import java.awt.image.Raster;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
/* Creates a property file which will contain the land-water classification for all tiles
which do not exist in the shape-file set.
To determine the classification for missing tiles a IGBP map was used.
namely: gigbp1_2g.img
To use this map, the correct reader must be included.
<dependency>
<groupId>org.esa.beam</groupId>
<artifactId>beam-igbp-glcc-reader</artifactId>
<version>2.0-SNAPSHOT</version>
</dependency>
3 tiles are not correctly classified, these are handled separately
*/
class MissingTilesPropertyFileGenerator {
private MissingTilesPropertyFileGenerator() {
}
public static void main(String[] args) throws IOException {
final Properties properties = new Properties();
final File directory = new File(args[0]);
final Product product = ProductIO.readProduct(new File(args[1]));
final Band land_water = product.getBandAt(0);
for (int x = -180; x < 180; x++) {
for (int y = 89; y >= -90; y--) {
final String tileFileName = getTileFileName(x, y);
final String propertyKey = tileFileName.substring(0, tileFileName.indexOf('.'));
if (y >= 60 || y <= -60) {
properties.setProperty(propertyKey, WatermaskClassifier.INVALID_VALUE + "");
} else if (!new File(directory, tileFileName).exists()) {
System.out.printf("Not existing: %s%n", tileFileName);
final int landWater = getLandWaterValue(land_water, x, y);
properties.setProperty(propertyKey, String.valueOf(landWater));
}
}
}
// these tiles are not correctly classified by the IGBP reference
properties.setProperty("e034n18", "0");
properties.setProperty("e019n09", "0");
properties.setProperty("e026n00", "0");
final FileWriter writer = new FileWriter(new File(directory, "MissingTiles.properties"));
try {
properties.store(writer, null);
} finally {
writer.close();
}
}
private static int getLandWaterValue(Band landWaterBand, int x, int y) {
final PixelPos pixelPos = landWaterBand.getGeoCoding().getPixelPos(new GeoPos(y, x), null);
final Raster raster = landWaterBand.getSourceImage().getData(
new Rectangle((int) pixelPos.getX(), (int) pixelPos.getY(), 1, 1));
final int sample = raster.getSample((int) pixelPos.getX(), (int) pixelPos.getY(), 0);
return sample == 17 ? WatermaskClassifier.WATER_VALUE : WatermaskClassifier.LAND_VALUE;
}
static String getTileFileName(double lon, double lat) {
final boolean geoPosIsWest = lon < 0;
final boolean geoPosIsSouth = lat < 0;
final String eastOrWest = geoPosIsWest ? "w" : "e";
final String northOrSouth = geoPosIsSouth ? "s" : "n";
return String.format("%s%03d%s%02d.img",
eastOrWest, (int) Math.abs(Math.floor(lon)),
northOrSouth, (int) Math.abs(Math.floor(lat)));
}
}
| 3,638 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
TemporaryMODISImage.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/util/TemporaryMODISImage.java | package gov.nasa.gsfc.seadas.watermask.util;
import com.bc.ceres.glevel.MultiLevelImage;
import gov.nasa.gsfc.seadas.watermask.operator.WatermaskClassifier;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.image.ImageHeader;
import org.esa.snap.core.util.ImageUtils;
import javax.media.jai.JAI;
import javax.media.jai.SourcelessOpImage;
import java.awt.*;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.util.ArrayList;
/**
*/
class TemporaryMODISImage extends SourcelessOpImage {
private final Product[] products;
private int count = 0;
private Strategy strategy;
public TemporaryMODISImage(ImageHeader imageHeader, Product[] products, int mode) {
super(imageHeader.getImageLayout(),
null,
ImageUtils.createSingleBandedSampleModel(DataBuffer.TYPE_BYTE,
imageHeader.getImageLayout().getSampleModel(null).getWidth(),
imageHeader.getImageLayout().getSampleModel(null).getHeight()),
imageHeader.getImageLayout().getMinX(null),
imageHeader.getImageLayout().getMinY(null),
imageHeader.getImageLayout().getWidth(null),
imageHeader.getImageLayout().getHeight(null));
this.products = products;
if (mode == ModisMosaicer.NORTH_MODE) {
strategy = new NorthStrategy();
} else {
strategy = new SouthStrategy();
}
setTileCache(JAI.createTileCache(50L * 1024 * 1024));
}
@Override
public Raster computeTile(int tileX, int tileY) {
count++;
final int numTiles = getNumXTiles() * getNumYTiles();
System.out.println("Writing tile '" + tileX + ", " + tileY + "', which is tile " + count + "/" + numTiles + ".");
Point location = new Point(tileXToX(tileX), tileYToY(tileY));
WritableRaster dest = createWritableRaster(getSampleModel(), location);
final PixelPos pixelPos = new PixelPos();
for (int x = dest.getMinX(); x < dest.getMinX() + dest.getWidth(); x++) {
for (int y = dest.getMinY(); y < dest.getMinY() + dest.getHeight(); y++) {
// fill invalid MODIS data areas with land
if (strategy.isSourceInvalid(x, y)) {
dest.setSample(x, y, 0, WatermaskClassifier.LAND_VALUE);
continue;
}
int xOffset = strategy.xOffset(x);
int yOffset = strategy.yOffset(y);
dest.setSample(x, y, 0, WatermaskClassifier.WATER_VALUE);
final GeoPos geoPos = strategy.getGeoPos(x + xOffset, y + yOffset);
final Product[] products = getProducts(geoPos);
for (Product product : products) {
product.getSceneGeoCoding().getPixelPos(geoPos, pixelPos);
final Band band = product.getBand("water_mask");
final MultiLevelImage sourceImage = band.getSourceImage();
final Raster tile = sourceImage.getTile(sourceImage.XToTileX((int) pixelPos.x), sourceImage.YToTileY((int) pixelPos.y));
final int sample = tile.getSample((int) pixelPos.x, (int) pixelPos.y, 0);
if (sample != band.getNoDataValue()) {
dest.setSample(x, y, 0, sample);
break;
}
}
}
}
return dest;
}
private Product[] getProducts(GeoPos geoPos) {
final java.util.List<Product> result = new ArrayList<Product>();
for (Product product : products) {
final PixelPos pixelPos = product.getSceneGeoCoding().getPixelPos(geoPos, null);
if (pixelPos.isValid() &&
pixelPos.x > 0 &&
pixelPos.x < product.getSceneRasterWidth() &&
pixelPos.y > 0 &&
pixelPos.y < product.getSceneRasterHeight()) {
result.add(product);
}
}
return result.toArray(new Product[result.size()]);
}
private interface Strategy {
GeoPos getGeoPos(int x, int y);
int xOffset(int x);
int yOffset(int y);
boolean isSourceInvalid(int x, int y);
}
private class SouthStrategy implements Strategy {
public int xOffset(int x) {
int xOffset = 0;
if (x == 77758) {
xOffset = -1;
} else if (x == 77759) {
xOffset = -2;
} else if (x == 77760) {
xOffset = 1;
}
return xOffset;
}
public int yOffset(int y) {
int yOffset = 0;
if (y == 4286 || y == 8601) {
yOffset = -1;
}
return yOffset;
}
public boolean isSourceInvalid(int x, int y) {
return y > 10860 || (y > 10473 && x > 154127) || (y > 10486 && x < 1436)
|| (y > 10491 && x > 153820)
|| (y > 10548 && x > 1432 && x < 1675);
}
public GeoPos getGeoPos(int x, int y) {
final double pixelSizeX = 360.0 / ModisMosaicer.MODIS_IMAGE_WIDTH;
final double pixelSizeY = -30.0 / ModisMosaicer.MODIS_IMAGE_HEIGHT;
double lon = -180.0 + x * pixelSizeX;
double lat = -60.0 + y * pixelSizeY;
return new GeoPos((float) lat, (float) lon);
}
}
private class NorthStrategy implements Strategy {
public int xOffset(int x) {
return 0;
}
public int yOffset(int y) {
return 0;
}
public boolean isSourceInvalid(int x, int y) {
return false;
}
public GeoPos getGeoPos(int x, int y) {
final double pixelSizeX = 360.0 / ModisMosaicer.MODIS_IMAGE_WIDTH;
final double pixelSizeY = 30.0 / ModisMosaicer.MODIS_IMAGE_HEIGHT;
double lon = -180.0 + x * pixelSizeX;
double lat = -90.0 + y * pixelSizeY;
return new GeoPos((float) lat, (float) lon);
}
}
}
| 6,355 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ImageDescriptorBuilder.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/util/ImageDescriptorBuilder.java | package gov.nasa.gsfc.seadas.watermask.util;
import java.io.*;
public class ImageDescriptorBuilder {
private int imageWidth;
private int imageHeight;
private int tileWidth;
private int tileHeight;
private File auxdataDir;
private String zipFileName;
public ImageDescriptorBuilder width(int imageWidth) {
this.imageWidth = imageWidth;
return this;
}
public ImageDescriptorBuilder height(int imageHeight) {
this.imageHeight = imageHeight;
return this;
}
public ImageDescriptorBuilder tileWidth(int tileWidth) {
this.tileWidth = tileWidth;
return this;
}
public ImageDescriptorBuilder tileHeight(int tileHeight) {
this.tileHeight = tileHeight;
return this;
}
public ImageDescriptorBuilder auxdataDir(File auxdataDir) {
this.auxdataDir = auxdataDir;
return this;
}
public ImageDescriptorBuilder zipFileName(String fileName) {
this.zipFileName = fileName;
return this;
}
public ImageDescriptor build() {
final ImageDescriptorImpl imageDescriptor = new ImageDescriptorImpl();
imageDescriptor.imageWidth = imageWidth;
imageDescriptor.imageHeight = imageHeight;
imageDescriptor.tileWidth = tileWidth;
imageDescriptor.tileHeight = tileHeight;
imageDescriptor.auxdataDir = auxdataDir;
imageDescriptor.zipFileName = zipFileName;
return imageDescriptor;
}
private class ImageDescriptorImpl implements ImageDescriptor {
private int imageWidth;
private int imageHeight;
private int tileWidth;
private int tileHeight;
private File auxdataDir;
private String zipFileName;
@Override
public int getImageWidth() {
return imageWidth;
}
@Override
public int getImageHeight() {
return imageHeight;
}
@Override
public int getTileWidth() {
return tileWidth;
}
@Override
public int getTileHeight() {
return tileHeight;
}
@Override
public File getAuxdataDir() {
return auxdataDir;
}
@Override
public String getZipFileName() {
return zipFileName;
}
}
}
| 2,358 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ModisProductHandler.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/util/ModisProductHandler.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.watermask.util;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.OperatorSpi;
import org.esa.snap.core.gpf.common.reproject.ReprojectionOp;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Thomas Storm
*/
public class ModisProductHandler {
private final List<Product> products = new ArrayList<Product>();
private final List<Product> reprojectedProducts = new ArrayList<Product>();
private final String[] args;
ModisProductHandler(String[] args) {
this.args = args;
GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis();
}
public static void main(String[] args) throws IOException {
final ModisProductHandler modisProductHandler = new ModisProductHandler(args);
modisProductHandler.getProducts();
modisProductHandler.reproject();
modisProductHandler.write();
modisProductHandler.printTargetLocations();
}
private void printTargetLocations() throws IOException {
final String source = "C:\\dev\\MODIS_reproj";
final String[] files = new File(source).list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".dim");
}
});
List<String> southProducts = new ArrayList<String>();
List<String> northProducts = new ArrayList<String>();
for (String file : files) {
final Product product = ProductIO.readProduct(new File(source, file));
final GeoCoding geoCoding = product.getSceneGeoCoding();
PixelPos sceneLL = new PixelPos(0 + 0.5f, product.getSceneRasterHeight() - 1 + 0.5f);
PixelPos sceneLR = new PixelPos(product.getSceneRasterWidth() - 1 + 0.5f,
product.getSceneRasterHeight() - 1 + 0.5f);
final GeoPos gp1 = new GeoPos();
final GeoPos gp2 = new GeoPos();
geoCoding.getGeoPos(sceneLL, gp1);
geoCoding.getGeoPos(sceneLR, gp2);
if (gp1.getLat() <= -60.0f || gp2.getLat() <= -60.0f) {
southProducts.add(product.getFileLocation().getAbsolutePath());
continue;
}
PixelPos sceneUL = new PixelPos(0.5f, 0.5f);
PixelPos sceneUR = new PixelPos(product.getSceneRasterWidth() - 1 + 0.5f, 0.5f);
geoCoding.getGeoPos(sceneUL, gp1);
geoCoding.getGeoPos(sceneUR, gp2);
if (gp1.getLat() >= 60.0f || gp2.getLat() >= 60.0f) {
northProducts.add(product.getFileLocation().getAbsolutePath());
}
}
System.out.println("South:");
for (String southProduct : southProducts) {
System.out.println(southProduct);
}
System.out.println("North:");
System.out.println("\n####################\n");
for (String northProduct : northProducts) {
System.out.println(northProduct);
}
}
private void getProducts() throws IOException {
final String inputPath = args[0];
final File[] products = new File(inputPath).listFiles();
GeoPos gp = new GeoPos();
for (File file : products) {
final Product product = ProductIO.readProduct(file);
PixelPos sceneLL = new PixelPos(0 + 0.5f, product.getSceneRasterHeight() - 1 + 0.5f);
final GeoCoding geoCoding = product.getSceneGeoCoding();
geoCoding.getGeoPos(sceneLL, gp);
if (gp.getLat() <= -60.0f) {
this.products.add(product);
System.out.println(MessageFormat.format(
"Added product ''{0}'' to products because lower left lat is ''{1}''.",
product.toString(),
gp.getLat()));
continue;
}
PixelPos sceneLR = new PixelPos(product.getSceneRasterWidth() - 1 + 0.5f,
product.getSceneRasterHeight() - 1 + 0.5f);
geoCoding.getGeoPos(sceneLR, gp);
if (gp.getLat() <= -60.0f) {
System.out.println(MessageFormat.format(
"Added product ''{0}'' to products because lower right lat is ''{1}''.",
product.toString(),
gp.getLat()));
this.products.add(product);
continue;
}
PixelPos sceneUL = new PixelPos(0.5f, 0.5f);
geoCoding.getGeoPos(sceneUL, gp);
if (gp.getLat() >= 60.0f) {
System.out.println(MessageFormat.format(
"Added product ''{0}'' to products because upper left lat is ''{1}''.",
product.toString(),
gp.getLat()));
this.products.add(product);
continue;
}
PixelPos sceneUR = new PixelPos(product.getSceneRasterWidth() - 1 + 0.5f, 0.5f);
geoCoding.getGeoPos(sceneUR, gp);
if (gp.getLat() >= 60.0f) {
System.out.println(MessageFormat.format(
"Added product ''{0}'' to products because upper right lat is ''{1}''.",
product.toString(),
gp.getLat()));
this.products.add(product);
}
}
}
private void reproject() {
final Map<String, Object> params = new HashMap<String, Object>();
params.put("crs", "EPSG:4326");
for (Product belowSixtyProduct : products) {
System.out.println("Reprojecting product '" + belowSixtyProduct + "'.");
final Product reprojectedProduct = GPF.createProduct(OperatorSpi.getOperatorAlias(ReprojectionOp.class),
params, belowSixtyProduct);
reprojectedProducts.add(reprojectedProduct);
}
}
private void write() throws IOException {
for (Product reprojectedProduct : reprojectedProducts) {
System.out.println("Writing product '" + reprojectedProduct + "'.");
reprojectedProduct.removeBand(reprojectedProduct.getBand("water_mask_QA"));
ProductIO.writeProduct(reprojectedProduct, new File(args[1], getProductName(reprojectedProduct)), "BEAM-DIMAP", false);
}
}
private String getProductName(Product reprojectedProduct) {
return reprojectedProduct.getName();
}
}
| 7,577 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ShapeFileRasterizer.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/util/ShapeFileRasterizer.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.watermask.util;
import gov.nasa.gsfc.seadas.watermask.operator.WatermaskUtils;
import org.geotools.coverage.grid.GridEnvelope2D;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.MapContent;
import org.geotools.map.MapViewport;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.referencing.operation.builder.GridToEnvelopeMapper;
import org.geotools.renderer.lite.StreamingRenderer;
import org.geotools.styling.*;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.FilterFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.datum.PixelInCell;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Responsible for transferring shapefiles containing a land/water-mask into a rasterized image.
*
* @author Thomas Storm
*/
class ShapeFileRasterizer {
private final File targetDir;
private final String tempDir;
ShapeFileRasterizer(File targetDir) {
this.targetDir = targetDir;
tempDir = System.getProperty("java.io.tmpdir", ".");
}
/**
* The main method of this tool.
*
* @param args Three arguments are needed: 1) directory containing shapefiles. 2) target directory.
* 3) resolution in meters / pixel.
* @throws java.io.IOException If some IO error occurs.
*/
public static void main(String[] args) throws IOException {
final File resourceDir = new File(args[0]);
final File targetDir = new File(args[1]);
targetDir.mkdirs();
int sideLength = WatermaskUtils.computeSideLength(Integer.parseInt(args[2]));
boolean createImage = false;
if (args.length == 4) {
createImage = Boolean.parseBoolean(args[3]);
}
final ShapeFileRasterizer rasterizer = new ShapeFileRasterizer(targetDir);
rasterizer.rasterizeShapeFiles(resourceDir, sideLength, createImage);
}
void rasterizeShapeFiles(File directory, int tileSize, boolean createImage) throws IOException {
File[] shapeFiles = directory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".zip");
}
});
if (shapeFiles != null) {
rasterizeShapeFiles(shapeFiles, tileSize, createImage);
}
File[] subdirs = directory.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
if (subdirs != null) {
for (File subDir : subdirs) {
rasterizeShapeFiles(subDir, tileSize, createImage);
}
}
}
void rasterizeShapeFiles(File[] zippedShapeFiles, int tileSize, boolean createImage) {
final ExecutorService executorService = Executors.newFixedThreadPool(12);
for (int i = 0; i < zippedShapeFiles.length; i++) {
File shapeFile = zippedShapeFiles[i];
int shapeFileIndex = i + 1;
ShapeFileRunnable runnable = new ShapeFileRunnable(shapeFile, tileSize, shapeFileIndex,
zippedShapeFiles.length, createImage);
executorService.submit(runnable);
}
executorService.shutdown();
while (!executorService.isTerminated()) {
try {
executorService.awaitTermination(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
BufferedImage createImage(File shapeFile, int tileSize) throws Exception {
CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;
final String shapeFileName = shapeFile.getName();
final ReferencedEnvelope referencedEnvelope = parseEnvelopeFromShapeFileName(shapeFileName, crs);
final MapViewport viewport = new MapViewport();
viewport.setBounds(referencedEnvelope);
viewport.setCoordinateReferenceSystem(crs);
//MapContext context = new DefaultMapContext(crs);
MapContent mapContent = new MapContent();
mapContent.setViewport(viewport);
final URL shapeFileUrl = shapeFile.toURI().toURL();
final FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = getFeatureSource(shapeFileUrl);
org.geotools.map.FeatureLayer featureLayer = new org.geotools.map.FeatureLayer(featureSource, createPolygonStyle());
mapContent.addLayer(featureLayer);
BufferedImage landMaskImage = new BufferedImage(tileSize, tileSize, BufferedImage.TYPE_BYTE_BINARY);
Graphics2D graphics = landMaskImage.createGraphics();
StreamingRenderer renderer = new StreamingRenderer();
renderer.setMapContent(mapContent);
Rectangle paintArea = new Rectangle(0, 0, tileSize, tileSize);
// the transform is computed here, because it ensures that the pixel anchor is in the pixel center and
// not at the corner as the StreamingRenderer does by default
AffineTransform transform = createWorldToScreenTransform(referencedEnvelope, paintArea);
renderer.paint(graphics, paintArea, referencedEnvelope, transform);
return landMaskImage;
}
private AffineTransform createWorldToScreenTransform(ReferencedEnvelope referencedEnvelope, Rectangle paintArea) throws Exception {
GridEnvelope2D gridRange = new GridEnvelope2D(paintArea);
final GridToEnvelopeMapper mapper = new GridToEnvelopeMapper(gridRange, referencedEnvelope);
mapper.setPixelAnchor(PixelInCell.CELL_CENTER);
return mapper.createAffineTransform().createInverse();
}
private ReferencedEnvelope parseEnvelopeFromShapeFileName(String shapeFileName, CoordinateReferenceSystem crs) {
int lonMin = Integer.parseInt(shapeFileName.substring(1, 4));
int lonMax;
if (shapeFileName.startsWith("e")) {
lonMax = lonMin + 1;
} else if (shapeFileName.startsWith("w")) {
lonMin--;
lonMin = lonMin * -1;
lonMax = lonMin--;
} else {
throw new IllegalStateException("Wrong shapefile-name: '" + shapeFileName + "'.");
}
int latMin = Integer.parseInt(shapeFileName.substring(5, 7));
int latMax;
if (shapeFileName.charAt(4) == 'n') {
latMax = latMin + 1;
} else if (shapeFileName.charAt(4) == 's') {
latMin--;
latMin = latMin * -1;
latMax = latMin--;
} else {
throw new IllegalStateException("Wrong shapefile-name: '" + shapeFileName + "'.");
}
return new ReferencedEnvelope(lonMin, lonMax, latMin, latMax, crs);
}
private void writeToFile(BufferedImage image, String name, boolean createImage) throws IOException {
String fileName = getFilenameWithoutExtension(name);
fileName = fileName.substring(0, fileName.length() - 1);
String imgFileName = fileName + ".img";
File outputFile = new File(targetDir.getAbsolutePath(), imgFileName);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
try {
byte[] data = ((DataBufferByte) image.getData().getDataBuffer()).getData();
fileOutputStream.write(data);
if (createImage) {
ImageIO.write(image, "png", new File(targetDir.getAbsolutePath(), fileName + ".png"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
List<File> createTempFiles(ZipFile zipFile) {
final Enumeration<? extends ZipEntry> entries = zipFile.entries();
List<File> tempShapeFiles;
try {
tempShapeFiles = unzipTempFiles(zipFile, entries);
} catch (IOException e) {
throw new IllegalStateException(
"Error generating temp files from shapefile '" + zipFile.getName() + "'.", e);
}
return tempShapeFiles;
}
private List<File> unzipTempFiles(ZipFile zipFile, Enumeration<? extends ZipEntry> entries) throws
IOException {
List<File> files = new ArrayList<File>();
while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
File file = readIntoTempFile(zipFile, entry);
files.add(file);
}
return files;
}
private File readIntoTempFile(ZipFile zipFile, ZipEntry entry) throws IOException {
File file = new File(tempDir, entry.getName());
final InputStream reader = zipFile.getInputStream(entry);
final FileOutputStream writer = new FileOutputStream(file);
try {
byte[] buffer = new byte[1024 * 1024];
int bytesRead = reader.read(buffer);
while (bytesRead != -1) {
writer.write(buffer, 0, bytesRead);
bytesRead = reader.read(buffer);
}
} finally {
reader.close();
writer.close();
}
return file;
}
@SuppressWarnings({"ResultOfMethodCallIgnored"})
private void deleteTempFiles(List<File> tempFiles) {
for (File tempFile : tempFiles) {
tempFile.delete();
}
tempFiles.clear();
}
private static String getFilenameWithoutExtension(String fileName) {
int i = fileName.lastIndexOf('.');
if (i > 0 && i < fileName.length() - 1) {
return fileName.substring(0, i);
}
return fileName;
}
private FeatureSource<SimpleFeatureType, SimpleFeature> getFeatureSource(URL url) throws IOException {
Map<String, Object> parameterMap = new HashMap<String, Object>();
parameterMap.put(ShapefileDataStoreFactory.URLP.key, url);
parameterMap.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key, Boolean.TRUE);
DataStore shapefileStore = DataStoreFinder.getDataStore(parameterMap);
String typeName = shapefileStore.getTypeNames()[0]; // Shape files do only have one type name
FeatureSource<SimpleFeatureType, SimpleFeature> featureSource;
featureSource = shapefileStore.getFeatureSource(typeName);
return featureSource;
}
private Style createPolygonStyle() {
StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(null);
FilterFactory filterFactory = CommonFactoryFinder.getFilterFactory(null);
PolygonSymbolizer symbolizer = styleFactory.createPolygonSymbolizer();
org.geotools.styling.Stroke stroke = styleFactory.createStroke(
filterFactory.literal("#FFFFFF"),
filterFactory.literal(0.0)
);
symbolizer.setStroke(stroke);
Fill fill = styleFactory.createFill(
filterFactory.literal("#FFFFFF"),
filterFactory.literal(1.0)
);
symbolizer.setFill(fill);
Rule rule = styleFactory.createRule();
rule.symbolizers().add(symbolizer);
FeatureTypeStyle fts = styleFactory.createFeatureTypeStyle();
fts.rules().add(rule);
Style style = styleFactory.createStyle();
style.featureTypeStyles().add(fts);
return style;
}
private class ShapeFileRunnable implements Runnable {
private final File shapeFile;
private int tileSize;
private int index;
private int shapeFileCount;
private boolean createImage;
ShapeFileRunnable(File shapeFile, int tileSize, int shapeFileIndex, int shapeFileCount, boolean createImage) {
this.shapeFile = shapeFile;
this.tileSize = tileSize;
this.index = shapeFileIndex;
this.shapeFileCount = shapeFileCount;
this.createImage = createImage;
}
@Override
public void run() {
try {
List<File> tempShapeFiles;
ZipFile zipFile = new ZipFile(shapeFile);
try {
tempShapeFiles = createTempFiles(zipFile);
} finally {
zipFile.close();
}
for (File file : tempShapeFiles) {
if (file.getName().endsWith("shp")) {
final BufferedImage image = createImage(file, tileSize);
writeToFile(image, shapeFile.getName(), createImage);
}
}
deleteTempFiles(tempShapeFiles);
System.out.printf("File %d of %d%n", index, shapeFileCount);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
} | 14,347 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
LandMaskRasterCreator.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/util/LandMaskRasterCreator.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.watermask.util;
import com.bc.ceres.glevel.MultiLevelImage;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
/**
* @author Thomas Storm
*/
public class LandMaskRasterCreator {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
printUsage();
System.exit(-1);
}
final LandMaskRasterCreator landMaskRasterCreator = new LandMaskRasterCreator(args[1]);
final String sourcePath = args[0];
landMaskRasterCreator.createRasterFile(sourcePath);
}
private static void printUsage() {
System.out.println("Usage: ");
System.out.println(" LandMaskRasterCreator $sourceFile $targetPath");
System.out.println(" System will exit.");
}
private final String targetPath;
public LandMaskRasterCreator(String targetPath) {
this.targetPath = targetPath;
}
void createRasterFile(String sourcePath) throws IOException {
validateSourcePath(sourcePath);
final Product lwProduct = readLwProduct(sourcePath);
final Band band = lwProduct.getBand("lw-mask");
final MultiLevelImage sourceImage = band.getSourceImage();
final int numXTiles = sourceImage.getNumXTiles();
final int numYTiles = sourceImage.getNumYTiles();
final int tileWidth = sourceImage.getTileWidth();
final int tileHeight = sourceImage.getTileHeight();
final BufferedImage image = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_BYTE_BINARY);
int count = 0;
for (int tileX = 0; tileX < numXTiles; tileX++) {
for (int tileY = 0; tileY < numYTiles; tileY++) {
count++;
final Raster tile = sourceImage.getTile(tileX, tileY);
final int minX = tile.getMinX();
for (int x = minX; x < minX + tile.getWidth(); x++) {
final int minY = tile.getMinY();
for (int y = minY; y < minY + tile.getHeight(); y++) {
image.getRaster().setSample(x - minX, y - minY, 0, (byte) tile.getSample(x, y, 0));
}
}
image.setData(sourceImage.getTile(tileX, tileY));
System.out.println("Writing image " + count + "/" + numXTiles * numYTiles + ".");
ImageIO.write(image, "png", new File(targetPath, String.format("%d-%d.png", tileX, tileY)));
}
}
}
private Product readLwProduct(String sourcePath) {
final Product lwProduct;
try {
lwProduct = ProductIO.readProduct(sourcePath);
} catch (IOException e) {
throw new IllegalArgumentException(MessageFormat.format("Unable to read from file ''{0}''.", sourcePath), e);
}
return lwProduct;
}
void validateSourcePath(String sourcePath) {
final File path = new File(sourcePath);
if (path.isDirectory()) {
throw new IllegalArgumentException(MessageFormat.format("Source path ''''{0}'' points to a directory, but " +
"must point to a file.", sourcePath));
}
if (!path.exists()) {
throw new IllegalArgumentException(MessageFormat.format("Source path ''{0}'' does not exist.", sourcePath));
}
}
}
| 4,387 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWServicesTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/test/java/gov/nasa/gsfc/seadas/ocsswrest/OCSSWServicesTest.java | package gov.nasa.gsfc.seadas.ocsswrest;
import gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWRemoteImpl;
import org.junit.Test;
import javax.json.JsonObject;
import static org.junit.Assert.*;
/**
* Created by amhmd on 4/26/17.
*/
public class OCSSWServicesTest {
@Test
public void getOCSSWInstallDir() {
}
@Test
public void getOcsswInstallStatus() {
}
@Test
public void setOCSSWProgramName() {
}
@Test
public void getMissionDataStatus() {
}
@Test
public void getMissionSuites() {
String missionName = "MODIS Aqua";
System.out.println("missionName = " + missionName);
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
JsonObject fileContents = ocsswRemote.getSensorFileIntoArrayList(missionName);
System.out.print(fileContents.keySet());
}
} | 860 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWFileServicesTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/test/java/gov/nasa/gsfc/seadas/ocsswrest/OCSSWFileServicesTest.java | package gov.nasa.gsfc.seadas.ocsswrest;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import static org.junit.Assert.*;
/**
* Created by aabduraz on 6/12/17.
*/
public class OCSSWFileServicesTest {
@Test
public void uploadClientFile() throws Exception {
OCSSWFileServices ocsswFileServices = new OCSSWFileServices();
File file = new File("/accounts/aabduraz/Downloads/A2011199230500.L1A_LAC");
InputStream inputStream = new FileInputStream(file);
final FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file", file);
final MultiPart multiPart = new FormDataMultiPart()
//.field("ifileName", ifileName)
.bodyPart(fileDataBodyPart);
ocsswFileServices.uploadClientFile("2", inputStream, fileDataBodyPart.getFormDataContentDisposition());
}
@Before
public void setUp() {
// OCSSWConfig ocsswConfig = new OCSSWConfig();
// ocsswConfig.readProperties();
// OCSSWServerModel.initiliaze();
}
@After
public void tearDown() {
}
@Test
public void downloadFile() {
OCSSWFileServices ocsswFileServices = new OCSSWFileServices();
ocsswFileServices.downloadFile("e3111428287d67a772eeb58946ae1bee");
}
} | 1,739 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWServerPropertyValuesTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/test/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/OCSSWServerPropertyValuesTest.java | package gov.nasa.gsfc.seadas.ocsswrest.utilities;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 4/27/15
* Time: 3:03 PM
* To change this template use File | Settings | File Templates.
*/
public class OCSSWServerPropertyValuesTest {
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testGetPropValue() throws Exception {
OCSSWServerPropertyValues propertyValues = new OCSSWServerPropertyValues();
String sharedDir = propertyValues.getPropValues("serverSharedDirName");
System.out.println(sharedDir);
Assert.assertNotNull(sharedDir);
}
}
| 783 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWConfigTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/test/java/gov/nasa/gsfc/seadas/ocsswrest/ocsswmodel/OCSSWConfigTest.java | package gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by aabduraz on 8/25/17.
*/
public class OCSSWConfigTest {
@Before
public void setUp() {
}
@Test
public void readProperties() {
String configFilePath = "/accounts/aabduraz/SeaDAS/dev/seadas-7.4/seadas/seadas-ocsswrest/config/ocsswservertest.config";
OCSSWConfig ocsswConfig = new OCSSWConfig(configFilePath);
ResourceLoader rl = new FileResourceLoader(configFilePath);
ocsswConfig.readProperties(rl);
}
} | 609 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWServerModelTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/test/java/gov/nasa/gsfc/seadas/ocsswrest/ocsswmodel/OCSSWServerModelTest.java | package gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by amhmd on 4/26/17.
*/
public class OCSSWServerModelTest {
@Test
public void initiliaze() {
OCSSWServerModel ocsswServerModel = new OCSSWServerModel();
System.out.println(OCSSWServerModel.isOCSSWExist());
}
@Test
public void isOCSSWExist() {
}
@Test
public void getFileType() {
}
@Test
public void setProgramName() {
}
@Test
public void setCommandArrayPrefix() {
}
} | 599 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWRemoteTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/test/java/gov/nasa/gsfc/seadas/ocsswrest/ocsswmodel/OCSSWRemoteTest.java | package gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel;
import gov.nasa.gsfc.seadas.ocsswrest.utilities.ServerSideFileUtilities;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.json.Json;
import javax.json.JsonObject;
import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;
import static gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWRemoteImpl.MLP_PROGRAM_NAME;
/**
* Created by aabduraz on 6/2/17.
*/
public class OCSSWRemoteTest {
@Test
public void executeMLP() {
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
ocsswRemote.executeMLP("65c5712c21bb142bdeaa174920669eff", new File("/accounts/aabduraz/aynur/65c5712c21bb142bdeaa174920669eff/multilevel_processor_parFile.txt"));
}
@Test
public void execute() {
String parFileLocation = "/accounts/aabduraz/aynur/65c5712c21bb142bdeaa174920669eff/multilevel_processor_parFile.txt";
String[] commandArray = {MLP_PROGRAM_NAME, parFileLocation};
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
final long startTime = System.nanoTime();
ocsswRemote.execute(ServerSideFileUtilities.concatAll(ocsswRemote.getCommandArrayPrefix(MLP_PROGRAM_NAME), commandArray), new File(parFileLocation).getParent(), "1234");
final long duration = System.nanoTime() - startTime;
long start = System.currentTimeMillis();
System.out.println("execution time is nano seconds: " + duration);
Date myTime = new Date(duration/1000);
long end = System.currentTimeMillis();
NumberFormat formatter = new DecimalFormat("#0.00000");
System.out.println("Execution time is " + formatter.format((end - start) / 1000d) + " seconds");
System.out.println(myTime.getTime());
}
@Before
public void setUp() {
String configFilePath = "/accounts/aabduraz/TestDir/ocsswrestserver.config";
OCSSWConfig ocsswConfig = new OCSSWConfig(configFilePath);
OCSSWServerModel.initiliaze();
}
@After
public void tearDown() {
}
@Test
public void getOfileName() {
}
@Test
public void extractFileInfo() {
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
ocsswRemote.extractFileInfo("/accounts/aabduraz/Downloads/A2011199230500.L1A_LAC", "1");
}
@Test
public void executeProgram() {
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
JsonObject jsonObject = Json.createObjectBuilder().add("file_IFILE", "/accounts/aabduraz/test.dir/A2011199230500.L1A_LAC")
.add("--output_OFILE","--output=/accounts/aabduraz/test.dir/A2011199230500.GEO")
.add("--verbose_BOOLEAN","--verbose")
.build();
ocsswRemote.executeProgram("725c26a6204e8b37613d66f6ea95e4d9", jsonObject);
}
} | 2,893 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ProcessServices.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/ProcessServices.java | package gov.nasa.gsfc.seadas.ocsswrest;
import gov.nasa.gsfc.seadas.ocsswrest.database.SQLiteJDBC;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import static gov.nasa.gsfc.seadas.ocsswrest.database.SQLiteJDBC.PROCESS_TABLE_NAME;
/**
* Created by aabduraz on 3/4/16.
*/
@Path("/process")
public class ProcessServices {
private final String stdout = "stdout";
private final String stderr = "stderr";
@GET
@Path("/stdout/{jobId}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String getProcessInputStream(@PathParam("jobId") String jobId) {
//TODO: get process input stream from the running process!
System.out.println("reached to grep standard output.");
String stdoutString = SQLiteJDBC.retrieveItem(PROCESS_TABLE_NAME, jobId, stdout);
return stdoutString == null ? "done!" :stdoutString;
}
@GET
@Path("/stderr/{jobId}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String getProcessErrorStream(@PathParam("jobId") String jobId) {
//TODO: get process error stream from the running process!
//System.out.println("reached to grep standard error.");
String stderrString = SQLiteJDBC.retrieveItem(PROCESS_TABLE_NAME, jobId, stderr);
return stderrString == null ? "done!" : stderrString;
}
}
| 1,383 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWServices.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/OCSSWServices.java | package gov.nasa.gsfc.seadas.ocsswrest;
import gov.nasa.gsfc.seadas.ocsswrest.database.SQLiteJDBC;
import gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWRemoteImpl;
import gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWServerModel;
import gov.nasa.gsfc.seadas.ocsswrest.utilities.*;
import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import static gov.nasa.gsfc.seadas.ocsswrest.OCSSWRestServer.SERVER_WORKING_DIRECTORY_PROPERTY;
import static gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWRemoteImpl.*;
import static gov.nasa.gsfc.seadas.ocsswrest.process.ORSProcessObserver.PROCESS_ERROR_STREAM_FILE_NAME;
import static gov.nasa.gsfc.seadas.ocsswrest.process.ORSProcessObserver.PROCESS_INPUT_STREAM_FILE_NAME;
import static gov.nasa.gsfc.seadas.ocsswrest.utilities.ServerSideFileUtilities.debug;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 1/8/15
* Time: 12:17 PM
* To change this template use File | Settings | File Templates.
*/
@Path("/ocssw")
public class OCSSWServices {
private static final String OBPG_FILE_TYPE_PROGRAM_NAME = "obpg_file_type";
private static String NEXT_LEVEL_NAME_FINDER_PROGRAM_NAME = "get_output_name";
private static String NEXT_LEVEL_FILE_NAME_TOKEN = "Output Name:";
private static String FILE_TABLE_NAME = "FILE_TABLE";
private static String MISSION_TABLE_NAME = "MISSION_TABLE";
final static String CLIENT_SERVER_SHARED_DIR_PROPERTY = "clientServerSharedDir";
private HashMap<String, Boolean> missionDataStatus;
/**
* This service empties client working directory on the server for each new connection from seadas application, then
* returns ocssw information.
* 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;
* ocsswRunnerScriptPath = ocsswScriptsDirPath + System.getProperty("file.separator") + OCSSW_RUNNER_SCRIPT;
* ocsswBinDirPath
*
* @return
*/
@GET
@Path("/ocsswInfo/{seadasVersion}")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getOcsswInfo(@PathParam("seadasVersion") String seadasVersion) {
OCSSWServerModel.setSeadasVersion(seadasVersion);
OCSSWServerModel.initiliaze();
JsonObject ocsswInstallStatus = null;
try {
ocsswInstallStatus = Json.createObjectBuilder().add("ocsswExists", OCSSWServerModel.isOCSSWExist())
.add("ocsswRoot", OCSSWServerModel.getOcsswRoot())
.add("ocsswScriptsDirPath", OCSSWServerModel.getOcsswScriptsDirPath())
.add("ocsswDataDirPath", OCSSWServerModel.getOcsswDataDirPath())
.add("ocsswInstallerScriptPath", OCSSWServerModel.getOcsswInstallerScriptPath())
.add("ocsswRunnerScriptPath", OCSSWServerModel.getOcsswRunnerScriptPath())
.add("ocsswBinDirPath", OCSSWServerModel.getOcsswBinDirPath())
.build();
} catch (Exception e) {
e.printStackTrace();
}
return ocsswInstallStatus;
}
/**
* This service manages client working directory on server.
* If the client working directory, "System.getProperty(SERVER_WORKING_DIRECTORY_PROPERTY) + File.separator + clientId" exists on server and
* the flag "keepFilesOnServer is set to "false", the client working directory is purged ; if the flag "keepFilesOnServer is set to "true"
* the directory is left intact.
* If the client working directory doesn't exist, it will be created at this time.
*
* @return
*/
@PUT
@Path("/manageClientWorkingDirectory/{clientId}")
@Consumes(MediaType.TEXT_PLAIN)
public Response manageClientWorkingDirectory(@PathParam("clientId") String clientId, String keepFilesOnServer) {
String workingDirPath = System.getProperty(SERVER_WORKING_DIRECTORY_PROPERTY) + File.separator + clientId;
String responseMessage = ServerSideFileUtilities.manageDirectory(workingDirPath, new Boolean(keepFilesOnServer).booleanValue());
Response response = Response.status(200).type("text/plain")
.entity(responseMessage).build();
return response;
}
/**
* This method uploads client id and saves it in the file table. It also decides the working directory for the client and saves it in the table for later requests.
*
* @param jobId jobId is specific to each request from the a SeaDAS client
* @param clientId clientId identifies one SeaDAS client
* @return
*/
@PUT
@Path("/ocsswSetClientId/{jobId}")
@Consumes(MediaType.TEXT_PLAIN)
public Response setClientIdWithJobId(@PathParam("jobId") String jobId, String clientId) {
Response.Status respStatus = Response.Status.OK;
SQLiteJDBC.updateItem(FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.CLIENT_ID_NAME.getFieldName(), clientId);
String workingDirPath;
boolean isClientServerSharedDir = new Boolean(System.getProperty(CLIENT_SERVER_SHARED_DIR_PROPERTY)).booleanValue();
if (isClientServerSharedDir) {
workingDirPath = System.getProperty(SERVER_WORKING_DIRECTORY_PROPERTY);
} else {
workingDirPath = System.getProperty(SERVER_WORKING_DIRECTORY_PROPERTY) + File.separator + clientId;
//ServerSideFileUtilities.createDirectory(workingDirPath + File.separator + jobId);
}
SQLiteJDBC.updateItem(FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName(), workingDirPath);
return Response.status(respStatus).build();
}
@PUT
@Path("/ocsswSetProgramName/{jobId}/{programName}")
@Consumes(MediaType.TEXT_PLAIN)
public Response setOCSSWProgramName(@PathParam("jobId") String jobId, String programName) {
Response.Status respStatus = Response.Status.OK;
if (OCSSWServerModel.isProgramValid(programName)) {
SQLiteJDBC.updateItem(FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.PROGRAM_NAME.getFieldName(), programName);
} else {
respStatus = Response.Status.BAD_REQUEST;
}
return Response.status(respStatus).build();
}
@GET
@Path("/getOfileName/{jobId}")
@Consumes(MediaType.TEXT_XML)
public String getOfileName(@PathParam("jobId") String jobId) {
String ofileName = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.O_FILE_NAME.getFieldName());
//System.out.println("Ofile name = " + ofileName);
return ofileName;
}
@GET
@Path("/getFileInfo/{jobId}/{ifileName}")
@Consumes(MediaType.TEXT_XML)
public JsonObject getFileInfo(@PathParam("jobId") String jobId, @PathParam("ifileName") String ifileName) {
String currentWorkingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String ifileFullPathName = currentWorkingDir + File.separator + ifileName;
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
HashMap<String, String> fileInfoMap = ocsswRemote.getFileInfo(ifileFullPathName, jobId);
JsonObject fileInfo = Json.createObjectBuilder().add(MISSION_NAME_VAR_NAME, fileInfoMap.get(MISSION_NAME_VAR_NAME))
.add(FILE_TYPE_VAR_NAME, fileInfoMap.get(FILE_TYPE_VAR_NAME))
.build();
return fileInfo;
}
@GET
@Path("/getFileCharSet/{jobId}/{fileName}")
@Consumes(MediaType.TEXT_XML)
public String getFileCharSet(@PathParam("jobId") String jobId, @PathParam("fileName") String fileName) {
String currentWorkingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String ifileFullPathName = currentWorkingDir + File.separator + fileName;
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
String fileCarSet = ocsswRemote.getFileCharset(ifileFullPathName);
return fileCarSet;
}
@GET
@Path("/getOfileName/{jobId}/{ifileName}/{programName}")
@Consumes(MediaType.TEXT_XML)
public String getOfileNameWithIfileAndProgramNameParams(@PathParam("jobId") String jobId,
@PathParam("ifileName") String ifileName,
@PathParam("programName") String programName) {
String currentWorkingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String ifileFullPathName = currentWorkingDir + File.separator + ifileName;
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
String ofileName = ocsswRemote.getOfileName(jobId, ifileFullPathName, programName);
return ofileName;
}
@PUT
@Path("executeOcsswProgram/{jobId}")
@Consumes(MediaType.APPLICATION_JSON)
public Response executeOcsswProgram(@PathParam("jobId") String jobId, JsonObject jsonObject) {
Response.Status respStatus = Response.Status.OK;
Process process = null;
if (jsonObject == null) {
respStatus = Response.Status.BAD_REQUEST;
} else {
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
ocsswRemote.executeProgram(jobId, jsonObject);
}
return Response.status(respStatus).build();
}
@PUT
@Path("executeUpdateLutsProgram/{jobId}")
@Consumes(MediaType.APPLICATION_JSON)
public Response executeUpdateLutsProgram(@PathParam("jobId") String jobId, JsonObject jsonObject) {
Response.Status respStatus = Response.Status.BAD_REQUEST;
Process process = null;
if (jsonObject != null) {
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
process = ocsswRemote.executeUpdateLutsProgram(jobId, jsonObject);
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
debug("exit value = " + process.exitValue());
if (process.exitValue() == 0) {
respStatus = Response.Status.OK;
} else {
respStatus = Response.Status.INTERNAL_SERVER_ERROR;
}
}
return Response.status(respStatus).build();
}
@PUT
@Path("executeOcsswProgramOnDemand/{jobId}/{programName}")
@Consumes(MediaType.APPLICATION_JSON)
public Response executeOcsswProgramOnDemand(@PathParam("jobId") String jobId,
@PathParam("programName") String programName,
JsonObject jsonObject) {
SQLiteJDBC.updateItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName(), SQLiteJDBC.ProcessStatusFlag.NONEXIST.getValue());
Response.Status respStatus = Response.Status.OK;
if (jsonObject == null) {
respStatus = Response.Status.BAD_REQUEST;
} else {
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
ocsswRemote.executeProgramOnDemand(jobId, programName, jsonObject);
}
Response response = Response.status(respStatus).type("text/plain").entity(SQLiteJDBC.retrieveItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName())).build();
System.out.println("process status on server = " + SQLiteJDBC.retrieveItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName()));
return response;
// return Response.status(respStatus).build();
}
@PUT
@Path("executeOcsswProgramAndGetStdout/{jobId}/{programName}")
@Consumes(MediaType.APPLICATION_JSON)
public Response executeOcsswProgramAndGetStdout(@PathParam("jobId") String jobId,
@PathParam("programName") String programName,
JsonObject jsonObject) {
String serverWorkingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
if (jsonObject == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
} else {
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
InputStream processInputStream = ocsswRemote.executeProgramAndGetStdout(jobId, programName, jsonObject);
ServerSideFileUtilities.writeToFile(processInputStream, serverWorkingDir + File.separator + ANC_FILE_LIST_FILE_NAME);
return Response
.ok()
.build();
}
}
@PUT
@Path("executeOcsswProgramSimple/{jobId}/{programName}")
@Consumes(MediaType.APPLICATION_JSON)
public Response executeOcsswProgramSimple(@PathParam("jobId") String jobId,
@PathParam("programName") String programName,
JsonObject jsonObject) {
Response.Status respStatus = Response.Status.OK;
if (jsonObject == null) {
respStatus = Response.Status.BAD_REQUEST;
} else {
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
ocsswRemote.executeProgramSimple(jobId, programName, jsonObject);
}
return Response.status(respStatus).build();
}
@PUT
@Path("convertLonLat2Pixels/{jobId}/{programName}")
@Consumes(MediaType.APPLICATION_JSON)
public Response convertLonLat2Pixels(@PathParam("jobId") String jobId,
@PathParam("programName") String programName,
JsonObject jsonObject) {
Response.Status respStatus = Response.Status.OK;
HashMap<String, String> pixels = new HashMap();
JsonObject pixelsJson = null;
if (jsonObject == null) {
respStatus = Response.Status.BAD_REQUEST;
} else {
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
pixels = ocsswRemote.computePixelsFromLonLat(jobId, programName, jsonObject);
if (pixels != null) {
respStatus = Response.Status.OK;
} else {
respStatus = Response.Status.EXPECTATION_FAILED;
}
}
return Response.status(respStatus).build();
}
@GET
@Path("getConvertedPixels/{jobId}")
@Consumes(MediaType.TEXT_PLAIN)
public JsonObject getConvertedPixels(@PathParam("jobId") String jobId) {
try {
JsonObject pixelsJsonObject = Json.createObjectBuilder()
.add(SQLiteJDBC.LonLatTableFields.SLINE_FIELD_NAME.getValue(), SQLiteJDBC.retrieveItem(SQLiteJDBC.LONLAT_TABLE_NAME, jobId, SQLiteJDBC.LonLatTableFields.SLINE_FIELD_NAME.getValue()))
.add(SQLiteJDBC.LonLatTableFields.ELINE_FIELD_NAME.getValue(), SQLiteJDBC.retrieveItem(SQLiteJDBC.LONLAT_TABLE_NAME, jobId, SQLiteJDBC.LonLatTableFields.ELINE_FIELD_NAME.getValue()))
.add(SQLiteJDBC.LonLatTableFields.SPIXL_FIELD_NAME.getValue(), SQLiteJDBC.retrieveItem(SQLiteJDBC.LONLAT_TABLE_NAME, jobId, SQLiteJDBC.LonLatTableFields.SPIXL_FIELD_NAME.getValue()))
.add(SQLiteJDBC.LonLatTableFields.EPIXL_FIELD_NAME.getValue(), SQLiteJDBC.retrieveItem(SQLiteJDBC.LONLAT_TABLE_NAME, jobId, SQLiteJDBC.LonLatTableFields.EPIXL_FIELD_NAME.getValue()))
.build();
return pixelsJsonObject;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@GET
@Path("/getSensorInfoFileContent/{jobId}/{missionName}")
@Consumes(MediaType.TEXT_XML)
public JsonObject getSensorInfoFileContent(@PathParam("jobId") String jobId, @PathParam("missionName") String missionName) {
System.out.println("missionName = " + missionName);
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
JsonObject fileContents = ocsswRemote.getSensorFileIntoArrayList(missionName);
return fileContents;
}
@PUT
@Path("uploadMLPParFile/{jobId}")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response uploadMLPParFile(@PathParam("jobId") String jobId,
@PathParam("programName") String programName,
File parFile) {
Response.Status respStatus = Response.Status.OK;
///System.out.println("mlp par file path: " + parFile.getAbsolutePath());
if (parFile == null) {
respStatus = Response.Status.BAD_REQUEST;
} else {
SQLiteJDBC.updateItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName(), SQLiteJDBC.ProcessStatusFlag.NONEXIST.getValue());
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
ocsswRemote.executeMLP(jobId, parFile);
}
return Response.status(respStatus).build();
}
//todo
@PUT
@Path("executeParFile/{jobId}/{programName}")
@Consumes(MediaType.TEXT_PLAIN)
public <parFileName> Response executeParFile(@PathParam("jobId") String jobId,
@PathParam("programName") String programName,
String parFileName) {
Response.Status respStatus = Response.Status.OK;
SQLiteJDBC.updateItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName(), SQLiteJDBC.ProcessStatusFlag.NONEXIST.getValue());
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
ocsswRemote.executeWithParFile(jobId, programName, parFileName);
return Response.status(respStatus).build();
}
@GET
@Path("executeMLPParFile/{jobId}")
@Consumes(MediaType.TEXT_PLAIN)
public Response executeMLPParFile(@PathParam("jobId") String jobId) {
Response.Status respStatus = Response.Status.OK;
return Response.status(respStatus).build();
}
@GET
@Path("processExitValue")
@Produces(MediaType.TEXT_PLAIN)
public String getProcessExitValue(@PathParam("jobId") String jobId) {
return SQLiteJDBC.retrieveItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.EXIT_VALUE_NAME.getFieldName());
}
@GET
@Path("processStatus/{jobId}")
@Produces(MediaType.TEXT_PLAIN)
public String getProcessStatus(@PathParam("jobId") String jobId) {
String processStatus = SQLiteJDBC.retrieveItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName());
//System.out.println("process status: " + processStatus);
return processStatus;
}
@GET
@Path("missions")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getMissionDataStatus() {
return new MissionInfoFinder().getMissions();
}
@GET
@Path("ocsswTags")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getOCSSWTags() {
//System.out.println("request for ocssw tags!");
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
return ocsswRemote.getOCSSWTags();
}
@GET
@Path("isMissionDirExist/{missionName}")
@Produces(MediaType.TEXT_PLAIN)
public Boolean isMissionDirExist(@PathParam("missionName") String missionName) {
return OCSSWServerModel.isMissionDirExist(missionName);
}
@GET
@Path("/l2bin_suites/{missionName}")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getMissionSuites(@PathParam("missionName") String missionName) {
return new MissionInfoFinder().getL2BinSuites(missionName);
}
@GET
@Path("/missionSuites/{missionName}/{programName}")
@Produces(MediaType.APPLICATION_JSON)
public String[] getMissionSuites(@PathParam("missionName") String missionName, @PathParam("programName") String programName) {
missionName = missionName.replaceAll("_", " ");
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
return ocsswRemote.getMissionSuites(missionName, programName);
}
@GET
@Path("/srcDirInfo")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public JsonObject getOCSSWSrcDirInfo() {
JsonObject srcDirStatus = Json.createObjectBuilder().add("ocssw_src", new File(OCSSWServerModel.getOcsswSrcDirPath()).exists()).build();
return srcDirStatus;
}
@GET
@Path("/viirsDemInfo")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public JsonObject getOCSSWViirsDemInfo() {
JsonObject viirsDemStatus = Json.createObjectBuilder().add("viirs-dem", new File(OCSSWServerModel.getOcsswViirsDemPath()).exists()).build();
return viirsDemStatus;
}
@GET
@Path("/ocsswEnv")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public OCSSWInfo getOCSSWInfo() {
OCSSWInfo ocsswInfo = new OCSSWInfo();
return ocsswInfo;
}
@GET
@Path("/getSystemInfo")
@Consumes(MediaType.TEXT_XML)
public String getSystemInfo() {
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
String systemInfoString = ocsswRemote.executeGetSystemInfoProgram();
return systemInfoString;
}
@GET
@Path("/getJavaVersion")
@Consumes(MediaType.TEXT_XML)
public String getJavaVersion() {
return System.getProperty("java.version");
}
@GET
@Path("/serverSharedFileDir")
@Produces(MediaType.TEXT_PLAIN)
public String getSharedFileDirName() {
System.out.println("Shared dir name:" + OCSSWServerPropertyValues.getServerSharedDirName());
return OCSSWServerPropertyValues.getServerSharedDirName();
}
@POST
@Path("/uploadNextLevelNameParams/{jobId}")
@Consumes(MediaType.APPLICATION_JSON)
public Response uploadNextLevelNameParams(@PathParam("jobId") String jobId, JsonObject jsonObject) {
Response.Status responseStatus = Response.Status.ACCEPTED;
//System.out.println("params uploaded!");
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
String ofileName = ocsswRemote.getOfileName(jobId, jsonObject);
System.out.println("ofileName = " + ofileName);
return Response.ok(ofileName).build();
}
@GET
@Path("retrieveNextLevelFileName/{jobId}")
@Produces(MediaType.TEXT_PLAIN)
public String findNextLevelFileName(@PathParam("jobId") String jobId) {
return SQLiteJDBC.retrieveItem(FILE_TABLE_NAME, jobId, "O_FILE_NAME");
}
@GET
@Path("retrieveIFileType/{jobId}")
@Produces(MediaType.TEXT_PLAIN)
public String findIFileType(@PathParam("jobId") String jobId) {
return SQLiteJDBC.retrieveItem(FILE_TABLE_NAME, jobId, "I_FILE_TYPE");
}
@GET
@Path("retrieveMissionName/{jobId}")
@Produces(MediaType.TEXT_PLAIN)
public String findMissionName(@PathParam("jobId") String jobId) {
return SQLiteJDBC.retrieveItem(FILE_TABLE_NAME, jobId, "MISSION_NAME");
}
@GET
@Path("retrieveMissionDirName/{jobId}")
@Produces(MediaType.TEXT_PLAIN)
public String findMissionDirName(@PathParam("jobId") String jobId) {
return SQLiteJDBC.retrieveItem(FILE_TABLE_NAME, jobId, "MISSION_DIR");
}
@GET
@Path("retrieveProcessStdoutFile/{jobId}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public InputStream retrieveProcessStdoutFile(@PathParam("jobId") String jobId) {
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
InputStream inputStream1 = ocsswRemote.getProcessStdoutFile(jobId);
InputStream inputStream = SQLiteJDBC.retrieveInputStreamItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STD_OUT_NAME.getFieldName());
return inputStream;
}
@GET
@Path("retrieveProcessInputStreamLine/{jobId}")
@Produces(MediaType.TEXT_PLAIN)
public String retrieveProcessInputStreamLine(@PathParam("jobId") String jobId) {
String serverWorkingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String processInputStreamFileName = serverWorkingDir + File.separator + jobId + File.separator + PROCESS_INPUT_STREAM_FILE_NAME;
String inputStreamLine = ServerSideFileUtilities.getlastLine(processInputStreamFileName);
System.out.println("process input stream last line = " + inputStreamLine + " filename = " + processInputStreamFileName);
return inputStreamLine;
}
@GET
@Path("retrieveProcessErrorStreamLine/{jobId}")
@Produces(MediaType.TEXT_PLAIN)
public String retrieveProcessErrorStreamLine(@PathParam("jobId") String jobId) {
String serverWorkingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String processErrorStreamFileName = serverWorkingDir + File.separator + jobId + File.separator + PROCESS_ERROR_STREAM_FILE_NAME;
String errorStreamLine = ServerSideFileUtilities.getlastLine(processErrorStreamFileName);
System.out.println("process error stream last line = " + errorStreamLine + " filename = " + processErrorStreamFileName);
return errorStreamLine;
}
}
| 25,867 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWSecureRestServer.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/OCSSWSecureRestServer.java | package gov.nasa.gsfc.seadas.ocsswrest;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.ssl.SSLContextConfigurator;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import java.io.IOException;
import java.net.URI;
/**
* Main class.
*
*/
public class OCSSWSecureRestServer {
// Base URI the Grizzly HTTP server will listen on
public static final String BASE_URI = "http://0.0.0.0:6401/ocsswws/";
/**
* Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
* @return Grizzly HTTP server.
*/
public static HttpServer startServer() {
// Grizzly ssl configuration
SSLContextConfigurator sslContext = new SSLContextConfigurator();
// create a resource config that scans for JAX-RS resources and providers
// in gov.nasa.gsfc.seadas.ocsswrest package
final ResourceConfig rc = new ResourceConfig().packages("gov.nasa.gsfc.seadas.ocsswrest");
// create and start a new instance of grizzly http server
// exposing the Jersey application at BASE_URI
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
}
/**
* Main method.
* @param args
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
final HttpServer server = startServer();
System.out.println(String.format("Jersey app started with WADL available at "
+ "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
System.in.read();
server.shutdownNow();
}
}
| 1,698 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWRestServer.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/OCSSWRestServer.java | package gov.nasa.gsfc.seadas.ocsswrest;
import gov.nasa.gsfc.seadas.ocsswrest.database.SQLiteJDBC;
import gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWConfig;
import gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWServerModel;
import gov.nasa.gsfc.seadas.ocsswrest.utilities.ProcessMessageBodyWriter;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.jsonp.JsonProcessingFeature;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.server.ResourceConfig;
import javax.json.stream.JsonGenerator;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.logging.Logger;
/**
* Main class.
*/
public class OCSSWRestServer extends ResourceConfig {
final static String BASE_URI_PORT_NUMBER_PROPERTY = "baseUriPortNumber";
final static String OCSSW_ROOT_PROPERTY ="ocsswroot";
final static String OCSSW_REST_SERVICES_CONTEXT_PATH = "ocsswws";
public final static String SERVER_WORKING_DIRECTORY_PROPERTY = "serverWorkingDirectory";
final static String KEEP_INTERMEDIATE_FILES_ON_SERVER_PROPERTY ="keepIntermediateFilesOnServer";
final static String SERVER_API="0.0.0.0";
static String configFilePath="./config/ocsswservertest.config";
static String baseUriPortNumber;
static String ocsswroot;
static String serverWorkingDirectory;
static String keepIntermediateFilesOnServer;
// Base URI the Grizzly HTTP server will listen on
public static String BASE_URI = "http://0.0.0.0:6401/ocsswws/";
private static final Logger LOGGER = Logger.getLogger(OCSSWRestServer.class.getName());
public OCSSWRestServer(String ocsswroot) {
Map<String, Object> properties = new HashMap<>();
properties.put("ocsswroot", ocsswroot);
setProperties(properties);
}
/**
* Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
*
* @return Grizzly HTTP server.
*/
public static HttpServer startServer() {
final ResourceConfig resourceConfig = new ResourceConfig(MultiPartResource.class);
resourceConfig.register(MultiPartFeature.class);
resourceConfig.register(InputStream.class);
resourceConfig.register(JacksonFeature.class);
resourceConfig.register(ProcessMessageBodyWriter.class);
resourceConfig.register(JsonProcessingFeature.class).property(JsonGenerator.PRETTY_PRINTING, true);
resourceConfig.packages("gov.nasa.gsfc.seadas.ocsswrest");
// create and start a new instance of grizzly http server
// exposing the Jersey application at BASE_URI
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), resourceConfig);
}
/**
* Main method.
*
* @param args
*/
public static void main(String[] args) {
String fileName = args[0];
System.out.println("argument: " + fileName);
OCSSWConfig ocsswConfig = new OCSSWConfig(fileName);
baseUriPortNumber = System.getProperty(BASE_URI_PORT_NUMBER_PROPERTY);
BASE_URI = "http://"+ SERVER_API + ":" + baseUriPortNumber + "/" + OCSSW_REST_SERVICES_CONTEXT_PATH + "/";
SQLiteJDBC.createTables();
OCSSWServerModel.initiliaze();
System.out.println(String.format("ORS is starting at ", BASE_URI));
final HttpServer server = startServer();
System.out.println(String.format("Jersey new app started with WADL available at "
+ "%sapplication.wadl\nPress 'Ctrl' + 'C' to stop it...", BASE_URI));
// System.in.read();
//server.shutdown();
}
}
| 3,941 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWFileServices.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/OCSSWFileServices.java | package gov.nasa.gsfc.seadas.ocsswrest;
import gov.nasa.gsfc.seadas.ocsswrest.database.SQLiteJDBC;
import gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWRemoteImpl;
import gov.nasa.gsfc.seadas.ocsswrest.utilities.OCSSWServerPropertyValues;
import gov.nasa.gsfc.seadas.ocsswrest.utilities.ServerSideFileUtilities;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import static gov.nasa.gsfc.seadas.ocsswrest.OCSSWRestServer.OCSSW_ROOT_PROPERTY;
import static gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWRemoteImpl.*;
import static gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWServerModel.OCSSW_COMMON_DIR_NAME;
import static gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWServerModel.getOcsswDataDirPath;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 12/29/14
* Time: 5:23 PM
* To change this template use File | Settings | File Templates.
*/
@Path("/fileServices")
public class OCSSWFileServices {
final static String SERVER_WORKING_DIRECTORY_PROPERTY = "serverWorkingDirectory";
private static final String OCSSW_PROCESSING_DIR = "ocsswfiles";
private static final String FILE_UPLOAD_PATH = System.getProperty("user.home") + System.getProperty("file.separator") + OCSSW_PROCESSING_DIR + System.getProperty("file.separator") + "ifiles";
private static final String FILE_DOWNLOAD_PATH = System.getProperty("user.home") + System.getProperty("file.separator") + OCSSW_PROCESSING_DIR + System.getProperty("file.separator") + "ofiles";
private static final String OCSSW_SERVER_DEFAULT_WORKING_DIR = System.getProperty("user.dir") + System.getProperty("file.separator") + "ocsswIntermediateFiles";
private static final String OCSSW_OUTPUT_COMPRESSED_FILE_NAME = "ocssw_output.zip";
private static final int BUFFER_SIZE = 1024;
@GET
@Path("/serverSharedFileDir")
@Produces(MediaType.TEXT_PLAIN)
public String getSharedFileDirName() {
System.out.println("Shared dir name:" + OCSSWServerPropertyValues.getServerSharedDirName());
return OCSSWServerPropertyValues.getServerSharedDirName();
}
@GET
@Path("/fileVerification/{jobId}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response fileVerification(@PathParam("jobId") String jobId,
@QueryParam("fileName") String fileName) {
Response.Status respStatus = Response.Status.NOT_FOUND;
java.nio.file.Path path1, path2;
String fileNameWithoutPath = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
String workingFileDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String fileNameOnServer = workingFileDir + File.separator + fileNameWithoutPath;
path1 = Paths.get(fileNameOnServer);
path2 = Paths.get(fileName);
try {
//System.out.println("path1 = " + path1);
//System.out.println("path2 = " + path2);
//scenario one: file is in the client working directory
if (Files.exists(path1)) {
respStatus = Response.Status.FOUND;
return Response.status(respStatus).build();
}
//scenario two: file is in the ocssw subdirectories
//if (fileName.contains(System.getProperty(OCSSW_ROOT_PROPERTY)))
if (fileName.indexOf(File.separator) != -1 && Files.exists(path2)) {
if ((fileName.contains(System.getProperty(SERVER_WORKING_DIRECTORY_PROPERTY)) || fileName.contains(System.getProperty(OCSSW_ROOT_PROPERTY)))) {
respStatus = Response.Status.FOUND;
} else {
System.out.println("file can not be on the server");
System.out.println("fileName.indexOf(File.separator) != -1 " + (fileName.indexOf(File.separator) != -1));
System.out.println("fileName.contains(System.getProperty(SERVER_WORKING_DIRECTORY_PROPERTY)) " + (fileName.contains(System.getProperty(SERVER_WORKING_DIRECTORY_PROPERTY))));
System.out.println("fileName.contains(System.getProperty(OCSSW_ROOT_PROPERTY))" + (fileName.contains(System.getProperty(OCSSW_ROOT_PROPERTY))));
respStatus = Response.Status.NOT_FOUND;
}
}
return Response.status(respStatus).build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
/**
* Method for uploading a file.
* handling HTTP POST requests. *
*
* @return String that will be returned as a text/plain response.
*/
@POST
@Path("/uploadClientFile/{jobId}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadClientFile(
@PathParam("jobId") String jobId,
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileInfo)
throws IOException {
Response.Status respStatus = Response.Status.OK;
Response response;
String fileInfoString;
String fileName = fileInfo.getFileName();
System.out.println("file info " + " is " + fileName);
if (fileName == null) {
respStatus = Response.Status.INTERNAL_SERVER_ERROR;
} else {
String currentWorkingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
System.out.println("current working directory " + " is " + currentWorkingDir);
File newFile = new File(currentWorkingDir);
Files.createDirectories(newFile.toPath());
boolean isDirCreated = new File(currentWorkingDir).isDirectory();
String clientfileFullPathName = currentWorkingDir + File.separator + fileName;
//System.out.println(clientfileFullPathName + " is created " + isDirCreated);
//System.out.println(System.getProperty("user.home"));
//System.out.println(new File(currentWorkingDir).getAbsolutePath());
try {
ServerSideFileUtilities.writeToFile(uploadedInputStream, clientfileFullPathName);
SQLiteJDBC.updateInputFilesList(jobId, clientfileFullPathName);
} catch (Exception e) {
respStatus = Response.Status.INTERNAL_SERVER_ERROR;
e.printStackTrace();
}
}
return Response.status(respStatus).build();
}
/**
* Method for uploading a file.
* handling HTTP POST requests. *
*
* @return String that will be returned as a text/plain response.
*/
@POST
@Path("/uploadParFile/{jobId}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadParFile(
@PathParam("jobId") String jobId,
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileInfo)
throws IOException {
Response.Status respStatus = Response.Status.OK;
String fileName = fileInfo.getFileName();
//System.out.println("par file info: file name is " + fileName);
if (fileName == null) {
respStatus = Response.Status.INTERNAL_SERVER_ERROR;
} else {
String currentWorkingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
//System.out.println("current working directory " + " is " + currentWorkingDir);
File newFile = new File(currentWorkingDir);
Files.createDirectories(newFile.toPath());
boolean isDirCreated = new File(currentWorkingDir).isDirectory();
String clientfileFullPathName = currentWorkingDir + File.separator + fileName;
//System.out.println(clientfileFullPathName + " is created " + isDirCreated);
//System.out.println(System.getProperty("user.home"));
//System.out.println(new File(currentWorkingDir).getAbsolutePath());
try {
ServerSideFileUtilities.writeToFile(uploadedInputStream, clientfileFullPathName);
SQLiteJDBC.updateInputFilesList(jobId, clientfileFullPathName);
} catch (Exception e) {
respStatus = Response.Status.INTERNAL_SERVER_ERROR;
e.printStackTrace();
}
}
return Response.status(respStatus).build();
}
@GET
@Path("/downloadFile/{jobId}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile(@PathParam("jobId") String jobId) {
String ofileName = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.O_FILE_NAME.getFieldName());
StreamingOutput fileStream = new StreamingOutput() {
@Override
public void write(OutputStream outputStream) throws WebApplicationException {
try {
java.nio.file.Path path = Paths.get(ofileName);
byte[] data = Files.readAllBytes(path);
outputStream.write(data);
outputStream.flush();
} catch (Exception e) {
throw new WebApplicationException("File Not Found !!");
}
}
};
return Response
.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition", "attachment; fileName = " + ofileName)
.build();
}
@GET
@Path("downloadAncFileList/{jobId}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadAncFileList(@PathParam("jobId") String jobId) {
String serverWorkingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String fileToDownload = serverWorkingDir + File.separator + OCSSWRemoteImpl.ANC_FILE_LIST_FILE_NAME;
StreamingOutput fileStream = new StreamingOutput() {
@Override
public void write(OutputStream outputStream) throws WebApplicationException {
try {
System.out.println("anc file name = " + fileToDownload);
java.nio.file.Path path = Paths.get(fileToDownload);
byte[] data = Files.readAllBytes(path);
outputStream.write(data);
outputStream.flush();
} catch (Exception e) {
throw new WebApplicationException("File Not Found !!");
}
}
};
return Response
.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition", "attachment; fileName = " + fileToDownload)
.build();
}
@GET
@Path("getMLPOutputFilesList/{jobId}")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getMLPOutputFilesList(@PathParam("jobId") String jobId) {
OCSSWRemoteImpl ocsswRemote = new OCSSWRemoteImpl();
return ocsswRemote.getMLPOutputFilesJsonList(jobId);
}
@GET
@Path("/downloadLogFile/{jobId}/{programName}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadLogFile(@PathParam("jobId") String jobId, @PathParam("programName") String programName) {
String workingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String processStdoutFileName = workingDir + File.separator + programName + PROCESS_STDOUT_FILE_NAME_EXTENSION;
if (programName.equals(MLP_PROGRAM_NAME)) {
processStdoutFileName = ServerSideFileUtilities.getLogFileName(workingDir);
}
String finalProcessStdoutFileName = processStdoutFileName;
StreamingOutput fileStream = new StreamingOutput() {
@Override
public void write(OutputStream outputStream) throws WebApplicationException {
try {
java.nio.file.Path path = Paths.get(finalProcessStdoutFileName);
byte[] data = Files.readAllBytes(path);
outputStream.write(data);
outputStream.flush();
} catch (Exception e) {
throw new WebApplicationException("File Not Found !!");
}
}
};
return Response
.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition", "attachment; fileName = " + finalProcessStdoutFileName)
.build();
}
@GET
@Path("/downloadMLPOutputFile/{jobId}/{ofileName}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadMLPOutputFile(@PathParam("jobId") String jobId,
@PathParam("ofileName") String clientOfileName) {
String workingFileDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String mlpOutputDir = workingFileDir + File.separator + MLP_OUTPUT_DIR_NAME;
String ofileName = mlpOutputDir + File.separator + clientOfileName;
File file = new File(ofileName);
if (file.exists()) {
StreamingOutput fileStream = new StreamingOutput() {
@Override
public void write(OutputStream outputStream) throws WebApplicationException {
try {
java.nio.file.Path path = Paths.get(ofileName);
byte[] data = Files.readAllBytes(path);
outputStream.write(data);
outputStream.flush();
} catch (Exception e) {
throw new WebApplicationException("File Not Found !!");
}
}
};
System.out.println(file.getAbsolutePath());
return Response
.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition", "attachment; fileName = " + ofileName)
.build();
} else {
System.out.println(ofileName + " does not exist");
return null;
}
}
@GET
@Path("/downloadFile/{jobId}/{ofileName}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFileOnDemand(@PathParam("jobId") String jobId,
@PathParam("ofileName") String clientOfileName) {
String workingFileDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String ofileName = workingFileDir + File.separator + clientOfileName;
StreamingOutput fileStream = new StreamingOutput() {
@Override
public void write(OutputStream outputStream) throws WebApplicationException {
try {
java.nio.file.Path path = Paths.get(ofileName);
byte[] data = Files.readAllBytes(path);
outputStream.write(data);
outputStream.flush();
} catch (Exception e) {
throw new WebApplicationException("File Not Found !!");
}
}
};
return Response
.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition", "attachment; fileName = " + ofileName)
.build();
}
@GET
@Path("/downloadFile/productXmlFile")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadProductXmlFIle() {
String ofileName = getOcsswDataDirPath() + File.separator + OCSSW_COMMON_DIR_NAME + File.separator + "product.xml";
StreamingOutput fileStream = new StreamingOutput() {
@Override
public void write(OutputStream outputStream) throws WebApplicationException {
try {
java.nio.file.Path path = Paths.get(ofileName);
byte[] data = Files.readAllBytes(path);
outputStream.write(data);
outputStream.flush();
} catch (Exception e) {
throw new WebApplicationException("File Not Found !!");
}
}
};
return Response
.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition", "attachment; fileName = " + ofileName)
.build();
}
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@GET
@Path("/test")
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
//return "Got it! \n";
System.out.println("getting ocssw shared server name");
OCSSWServerPropertyValues propertyValues = new OCSSWServerPropertyValues();
return OCSSWServerPropertyValues.getServerSharedDirName();
}
@GET
@Path("/missionInfo")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getFileMissionInfo() {
JsonObject jsonObject = Json.createObjectBuilder().build();
return jsonObject;
}
}
| 18,081 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
JobServices.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/JobServices.java | package gov.nasa.gsfc.seadas.ocsswrest;
import gov.nasa.gsfc.seadas.ocsswrest.database.SQLiteJDBC;
import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 2/5/15
* Time: 4:20 PM
* To change this template use File | Settings | File Templates.
*/
@Path("/jobs")
public class JobServices {
@GET
@Path("/newJobId") ///{clientId}/{processorId}")
@Produces(MediaType.TEXT_PLAIN)
public String createNewJob() {
String newJobId = hashJobID(new Long(new Date().getTime()).toString());
//insert rows for this new job in the processor and file tables.
SQLiteJDBC.insertItem("FILE_TABLE", "JOB_ID", newJobId);
SQLiteJDBC.updateItem(SQLiteJDBC.PROCESS_TABLE_NAME, newJobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName(), SQLiteJDBC.ProcessStatusFlag.NONEXIST.getValue());
SQLiteJDBC.insertItem("PROCESS_TABLE", "JOB_ID", newJobId);
SQLiteJDBC.insertItem(SQLiteJDBC.LONLAT_TABLE_NAME, "JOB_ID", newJobId);
return newJobId;
}
@GET
@Path("/list")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getJobList() {
JsonObject jobList = Json.createObjectBuilder().build();
return jobList;
}
@DELETE
@Path("/deleteJobs")
public void deleteAllJobs() {
}
@DELETE
@Path("/deleteJobId")
@Consumes(MediaType.TEXT_PLAIN)
public void deleteAJob(String jobId) {
}
private String hashJobID(String jobID) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
md.update(jobID.getBytes());
byte byteData[] = md.digest();
//convert the byte to hex format
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
| 2,308 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ORSResource.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/ORSResource.java | package gov.nasa.gsfc.seadas.ocsswrest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
/**
* Created by aabduraz on 8/25/17.
*/
public class ORSResource {
@Context
private Application application;
@GET
@Path("")
public String getOcsswRoot() {
String ocsswRoot = String.valueOf(application.getProperties().get("ocsswroot"));
return ocsswRoot;
}
}
| 464 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MultiPartResource.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/MultiPartResource.java | package gov.nasa.gsfc.seadas.ocsswrest;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 12/29/14
* Time: 4:12 PM
* To change this template use File | Settings | File Templates.
*/
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXB;
import java.io.File;
import java.io.InputStream;
/**
* MultiPart resource
*
* @author Arul Dhesiaseelan (aruld@acm.org)
*/
@Path("multipart")
public class MultiPartResource {
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_XML)
public Response processForm(@FormDataParam("xml") InputStream is, @FormDataParam("xml") FormDataContentDisposition header) {
System.out.println("Processing file # " + header.getFileName());
File entity = JAXB.unmarshal(is, File.class);
// entity.setUid(UUID.randomUUID().toString());
return Response.ok(entity).build();
}
} | 1,192 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ProcessMessageBodyWriter.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/ProcessMessageBodyWriter.java | package gov.nasa.gsfc.seadas.ocsswrest.utilities;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
/**
* Created by aabduraz on 5/28/15.
*/
@Produces("application/octet-stream")
public class ProcessMessageBodyWriter implements MessageBodyWriter<Process> {
@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return type == Process.class;
}
@Override
public long getSize(Process process, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
// deprecated by JAX-RS 2.0 and ignored by Jersey runtime
return 0;
}
@Override
public void writeTo(Process process,
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream)
throws WebApplicationException {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Process.class);
// serialize the entity myBean to the entity output stream
jaxbContext.createMarshaller().marshal(process, entityStream);
} catch (JAXBException jaxbException) {
throw new ProcessingException(
"Error serializing a Process to the output stream", jaxbException);
}
}
}
| 1,901 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWRuntimeConfig.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/OCSSWRuntimeConfig.java | package gov.nasa.gsfc.seadas.ocsswrest.utilities;
import java.io.*;
import java.net.URL;
import java.security.CodeSource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.*;
import java.util.logging.Formatter;
/*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
public final class OCSSWRuntimeConfig {
public static final String CONFIG_KEY_CERES_CONTEXT = "ocsswws.context";
public static final String CONFIG_KEY_DEBUG = "debug";
public static final String CONFIG_KEY_MAIN_CLASS = "mainClass";
public static final String CONFIG_KEY_CLASSPATH = "classpath";
public static final String CONFIG_KEY_HOME = "home";
public static final String CONFIG_KEY_CONFIG_FILE_NAME = "config";
public static final String CONFIG_KEY_MODULES = "modules";
public static final String CONFIG_KEY_LIB_DIRS = "libDirs";
public static final String CONFIG_KEY_APP = "app";
public static final String CONFIG_KEY_CONSOLE_LOG = "consoleLog";
public static final String CONFIG_KEY_LOG_LEVEL = "logLevel";
public static final String DEFAULT_CERES_CONTEXT = "ocsswws";
public static final String DEFAULT_MAIN_CLASS_NAME = "gov.nasa.gsfc.seadas.ocsswws.Server";
public static final String DEFAULT_MODULES_DIR_NAME = "modules";
public static final String DEFAULT_CONFIG_DIR_NAME = "config";
public static final String DEFAULT_LIB_DIR_NAME = "lib";
public static final SimpleDateFormat LOG_TIME_STAMP_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
private final Properties properties;
private String contextId;
private String debugKey;
private boolean debug;
private String homeDirKey;
private String homeDirPath;
private String mainClassKey;
private String mainClassName;
private String classpathKey;
private String mainClassPath;
private String applicationIdKey;
private String applicationId;
private String configFileKey;
private String configFilePath;
private String defaultRelConfigFilePath;
private String defaultHomeConfigFilePath;
private String modulesDirKey;
private String modulesDirPath;
private String defaultHomeModulesDirPath;
private String libDirsKey;
private String[] libDirPaths;
private String defaultHomeLibDirPath;
private Logger logger;
private boolean homeDirAssumed;
private String consoleLogKey;
private String logLevelKey;
private Level logLevel;
private boolean consoleLog;
public OCSSWRuntimeConfig() throws RuntimeConfigException {
properties = System.getProperties();
initAll();
}
public String getContextId() {
return contextId;
}
public String getContextProperty(String key) {
return getContextProperty(key, null);
}
public String getContextProperty(String key, String defaultValue) {
return getProperty(contextId + '.' + key, defaultValue);
}
public boolean isDebug() {
return debug;
}
public String getMainClassName() {
return mainClassName;
}
public String getMainClassPath() {
return mainClassPath;
}
public String getHomeDirPath() {
return homeDirPath;
}
public String getConfigFilePath() {
return configFilePath;
}
public String[] getLibDirPaths() {
return libDirPaths;
}
public String getModulesDirPath() {
return modulesDirPath;
}
public boolean isUsingModuleRuntime() {
return DEFAULT_MAIN_CLASS_NAME.equals(mainClassName);
}
public String getApplicationId() {
return applicationId;
}
public Logger getLogger() {
return logger;
}
/////////////////////////////////////////////////////////////////////////
// Private
/////////////////////////////////////////////////////////////////////////
private void initAll() throws RuntimeConfigException {
initContext();
initDebug();
initHomeDirAndConfiguration();
initDebug(); // yes, again
initMainClassName();
initClasspathPaths();
initModulesDir();
initLibDirs();
if (isUsingModuleRuntime()) {
initAppId();
}
initLogLevel();
initConsoleLog();
initLogger();
setAutoDetectProperties();
}
private void initContext() {
// Initialize context identifier. Mandatory.
contextId = System.getProperty(CONFIG_KEY_CERES_CONTEXT, DEFAULT_CERES_CONTEXT);
// Initialize application specific configuration keys
homeDirKey = String.format("%s.%s", contextId, CONFIG_KEY_HOME);
debugKey = String.format("%s.%s", contextId, CONFIG_KEY_DEBUG);
configFileKey = String.format("%s.%s", contextId, CONFIG_KEY_CONFIG_FILE_NAME);
modulesDirKey = String.format("%s.%s", contextId, CONFIG_KEY_MODULES);
libDirsKey = String.format("%s.%s", contextId, CONFIG_KEY_LIB_DIRS);
mainClassKey = String.format("%s.%s", contextId, CONFIG_KEY_MAIN_CLASS);
classpathKey = String.format("%s.%s", contextId, CONFIG_KEY_CLASSPATH);
applicationIdKey = String.format("%s.%s", contextId, CONFIG_KEY_APP);
logLevelKey = String.format("%s.%s", contextId, CONFIG_KEY_LOG_LEVEL);
consoleLogKey = String.format("%s.%s", contextId, CONFIG_KEY_CONSOLE_LOG);
// Initialize default file and directory paths
char sep = File.separatorChar;
defaultRelConfigFilePath = String.format("%s/%s", DEFAULT_CONFIG_DIR_NAME, configFileKey).replace('/', sep);
defaultHomeConfigFilePath = String.format("${%s}/%s", homeDirKey, defaultRelConfigFilePath).replace('/', sep);
defaultHomeModulesDirPath = String.format("${%s}/%s", homeDirKey, DEFAULT_MODULES_DIR_NAME).replace('/', sep);
defaultHomeLibDirPath = String.format("${%s}/%s", homeDirKey, DEFAULT_LIB_DIR_NAME).replace('/', sep);
}
private void initDebug() {
debug = Boolean.valueOf(System.getProperty(debugKey, Boolean.toString(debug)));
}
private void initHomeDirAndConfiguration() throws RuntimeConfigException {
maybeInitHomeDirAndConfigFile();
if (configFilePath != null) {
loadConfiguration();
} else {
trace("A configuration file is not used.");
}
initHomeDirIfNotAlreadyDone();
}
private void maybeInitHomeDirAndConfigFile() throws RuntimeConfigException {
maybeInitHomeDir();
maybeInitConfigFile();
if (homeDirPath == null && configFilePath == null) {
// we have no home and no config file
assumeHomeDir();
}
if (configFilePath == null) {
maybeInitDefaultConfigFile();
}
}
private void maybeInitHomeDir() throws RuntimeConfigException {
String homeDirPath = getProperty(homeDirKey);
if (!isNullOrEmptyString(homeDirPath)) {
// ok set: must be an existing directory
File homeDir = new File(homeDirPath);
if (!homeDir.isDirectory()) {
throw createInvalidPropertyValueException(homeDirKey, homeDirPath);
}
try {
this.homeDirPath = homeDir.getCanonicalPath();
} catch (IOException e) {
throw new RuntimeConfigException(e.getMessage(), e);
}
}
}
private void maybeInitConfigFile() throws RuntimeConfigException {
String configFilePath = getProperty(configFileKey);
if (!isNullOrEmptyString(configFilePath)) {
File configFile = new File(configFilePath);
// ok set: must be an existing file
if (!configFile.isFile()) {
throw createInvalidPropertyValueException(configFileKey, configFile.getPath());
}
try {
this.configFilePath = configFile.getCanonicalPath();
} catch (IOException e) {
throw new RuntimeConfigException(e.getMessage(), e);
}
}
}
private void maybeInitDefaultConfigFile() {
File configFile = new File(substitute(defaultHomeConfigFilePath));
if (configFile.isFile()) {
configFilePath = configFile.getPath();
}
}
private void assumeHomeDir() {
List<File> possibleHomeDirList = createPossibleHomeDirList();
List<String> homeContentPathList = createHomeContentPathList();
// The existance of the files in homeContentPathList is optional.
// We assume that the home directory is the one in which most files of homeContentPathList are present.
trace("Auto-detecting home directory...");
File mostLikelyHomeDir = findMostLikelyHomeDir(possibleHomeDirList, homeContentPathList);
if (mostLikelyHomeDir != null) {
homeDirPath = mostLikelyHomeDir.getPath();
} else {
homeDirPath = new File(".").getAbsolutePath();
}
homeDirAssumed = true;
setProperty(homeDirKey, homeDirPath);
}
private File findMostLikelyHomeDir(List<File> possibleHomeDirList, List<String> homeContentPathList) {
int numFoundMax = 0;
File mostLikelyHomeDir = null;
for (File possibleHomeDir : possibleHomeDirList) {
trace(String.format("Is [%s] my home directory?", possibleHomeDir));
int numFound = 0;
for (String homeContentPath : homeContentPathList) {
File homeContentFile = new File(possibleHomeDir, homeContentPath);
if (homeContentFile.exists()) {
trace(String.format(" [%s] contained? Yes.", homeContentPath));
numFound++;
} else {
trace(String.format(" [%s] contained? No.", homeContentPath));
}
}
if (numFound == 0) {
trace("No.");
} else {
trace(String.format("Maybe. %d related file(s) found.", numFound));
}
if (numFound > numFoundMax) {
try {
mostLikelyHomeDir = possibleHomeDir.getCanonicalFile();
numFoundMax = numFound;
} catch (IOException e) {
// ???
}
}
}
return mostLikelyHomeDir;
}
private static List<File> createPossibleHomeDirList() {
List<File> homeDirCheckList = new ArrayList<File>(4);
// include codeSource dir in check list
CodeSource lib = OCSSWRuntimeConfig.class.getProtectionDomain().getCodeSource();
if (lib != null) {
URL libUrl = lib.getLocation();
if (libUrl.getProtocol().equals("file")) {
String libPath = libUrl.getPath();
File libParentDir = new File(libPath).getParentFile();
if (libParentDir != null) {
// include one above libParentDir
if (libParentDir.getParentFile() != null) {
homeDirCheckList.add(libParentDir.getParentFile());
}
// include libParentDir
homeDirCheckList.add(libParentDir);
}
}
}
// include CWD in check list
homeDirCheckList.add(new File(".").getAbsoluteFile());
// include one above CWD in check list
homeDirCheckList.add(new File("src/test").getAbsoluteFile());
return homeDirCheckList;
}
private List<String> createHomeContentPathList() {
List<String> homeContentPathList = new ArrayList<String>(8);
homeContentPathList.add(defaultRelConfigFilePath);
homeContentPathList.add("bin");
homeContentPathList.add(DEFAULT_LIB_DIR_NAME);
homeContentPathList.add(DEFAULT_MODULES_DIR_NAME);
return homeContentPathList;
}
private void loadConfiguration() throws RuntimeConfigException {
trace(String.format("Loading configuration from [%s]", configFilePath));
try {
InputStream stream = new FileInputStream(configFilePath);
//InputStream stream1 = new FileInputStream("config/ocsswws.config");
try {
Properties fileProperties = new Properties();
fileProperties.load(stream);
// @todo check tests - code was not backward compatible with Java 5
// so i changed it - but this is not the only place of uncompatibilty
// add default properties so that they override file properties
//Set<String> propertyNames = fileProperties.stringPropertyNames();
// for (String propertyName : propertyNames) {
// String propertyValue = fileProperties.getProperty(propertyName);
// if (!isPropertySet(propertyName)) {
// setProperty(propertyName, propertyValue);
// trace(String.format("Configuration property [%s] added", propertyName));
// } else {
// trace(String.format("Configuration property [%s] ignored", propertyName));
// }
// }
Enumeration<?> enumeration = fileProperties.propertyNames();
while (enumeration.hasMoreElements()) {
final Object key = enumeration.nextElement();
if (key instanceof String) {
final Object value = fileProperties.get(key);
if (value instanceof String) {
final String keyString = (String) key;
String propertyValue = fileProperties.getProperty(keyString);
if (!isPropertySet(keyString)) {
setProperty(keyString, propertyValue);
trace(String.format("Configuration property [%s] added", keyString));
} else {
trace(String.format("Configuration property [%s] ignored", keyString));
}
}
}
}
} finally {
stream.close();
}
} catch (IOException e) {
throw new RuntimeConfigException(String.format("Failed to load configuration [%s]", configFilePath),
e);
}
}
private void initHomeDirIfNotAlreadyDone() throws RuntimeConfigException {
if (homeDirPath == null || homeDirAssumed) {
maybeInitHomeDir();
}
if (homeDirPath == null) {
homeDirPath = new File(".").getAbsolutePath();
homeDirAssumed = true;
}
// remove redundant '.'s and '..'s.
try {
homeDirPath = new File(homeDirPath).getCanonicalPath();
} catch (IOException e) {
throw new RuntimeConfigException("Home directory is invalid.", e);
}
if (homeDirAssumed) {
trace(String.format("Home directory not set. Using assumed default."));
}
trace(String.format("Home directory is [%s]", homeDirPath));
}
private void initMainClassName() throws RuntimeConfigException {
mainClassName = getProperty(mainClassKey, DEFAULT_MAIN_CLASS_NAME);
if (isNullOrEmptyString(mainClassName)) {
throw createMissingPropertyKeyException(mainClassKey);
}
}
private void initClasspathPaths() {
mainClassPath = getProperty(classpathKey, null);
}
private void initModulesDir() throws RuntimeConfigException {
this.modulesDirPath = null;
String modulesDirPath = getProperty(modulesDirKey);
if (modulesDirPath != null) {
File modulesDir = new File(modulesDirPath);
if (!modulesDir.isDirectory()) {
throw createInvalidPropertyValueException(modulesDirKey, modulesDirPath);
}
this.modulesDirPath = modulesDir.getPath();
} else {
// try default
File modulesDir = new File(substitute(defaultHomeModulesDirPath));
if (modulesDir.isDirectory()) {
this.modulesDirPath = modulesDir.getPath();
}
}
}
private void initLibDirs() throws RuntimeConfigException {
this.libDirPaths = new String[0];
String libDirPathsString = getProperty(libDirsKey);
if (libDirPathsString != null) {
String[] libDirPaths = splitLibDirPaths(libDirPathsString);
for (String libDirPath : libDirPaths) {
File libDir = new File(libDirPath);
if (!libDir.isDirectory()) {
throw createInvalidPropertyValueException(libDirsKey, libDirPathsString);
}
}
this.libDirPaths = libDirPaths;
} else {
// try default
libDirPathsString = substitute(defaultHomeLibDirPath);
File libDir = new File(libDirPathsString);
if (libDir.isDirectory()) {
this.libDirPaths = new String[]{libDirPathsString};
}
}
}
private void initAppId() throws RuntimeConfigException {
applicationId = getProperty(applicationIdKey);
if (applicationId != null && applicationId.length() == 0) {
throw createMissingPropertyKeyException(applicationIdKey);
}
}
private void initLogLevel() {
String logLevelStr = getProperty(logLevelKey, Level.OFF.getName());
Level[] validLevels = new Level[]{
Level.SEVERE,
Level.WARNING,
Level.INFO,
Level.CONFIG,
Level.FINE,
Level.FINER,
Level.FINEST,
Level.ALL,
Level.OFF,
};
logLevel = Level.OFF;
for (Level level : validLevels) {
if (level.getName().equalsIgnoreCase(logLevelStr)) {
logLevel = level;
break;
}
}
}
private void initConsoleLog() {
String consoleLogStr = getProperty(consoleLogKey, "false");
consoleLog = Boolean.parseBoolean(consoleLogStr);
}
private void initLogger() {
ConsoleHandler consoleHandler = null;
Logger rootLogger = LogManager.getLogManager().getLogger("");
Handler[] handlers = rootLogger.getHandlers();
for (Handler handler : handlers) {
if (handler instanceof ConsoleHandler) {
consoleHandler = (ConsoleHandler) handler;
rootLogger.removeHandler(handler);
}
}
logger = Logger.getLogger(contextId);
logger.setLevel(logLevel);
if (!logLevel.equals(Level.OFF)) {
LogFormatter formatter = new LogFormatter();
if (consoleLog) {
if (consoleHandler == null) {
consoleHandler = new ConsoleHandler();
}
consoleHandler.setFormatter(formatter);
consoleHandler.setLevel(logLevel);
logger.addHandler(consoleHandler);
}
String userHomePath = getProperty("user.home", ".");
File logDir = new File(userHomePath, '.' + contextId + "/log");
logDir.mkdirs();
String logFilePattern = new File(logDir, contextId + "-%g.log").getPath();
try {
FileHandler fileHandler = new FileHandler(logFilePattern);
fileHandler.setFormatter(formatter);
fileHandler.setLevel(logLevel);
logger.addHandler(fileHandler);
} catch (IOException e) {
System.err.println("Error: Failed to create log file: " + logFilePattern);
}
}
}
private void setAutoDetectProperties() {
setPropertyIfNotSet(this.homeDirKey, getHomeDirPath());
setPropertyIfNotSet(configFileKey, getConfigFilePath());
setPropertyIfNotSet(modulesDirKey, getModulesDirPath());
String libDirPaths = assembleLibDirPaths(getLibDirPaths());
setPropertyIfNotSet(libDirsKey, libDirPaths.length() > 0 ? libDirPaths : null);
}
private void setPropertyIfNotSet(String key, String value) {
if (!isPropertySet(key)) {
setProperty(key, value);
}
}
private static boolean isNullOrEmptyString(String value) {
return value == null || value.length() == 0;
}
private static String[] splitLibDirPaths(String libDirPathsString) {
List<String> libDirPathList = new ArrayList<String>(8);
StringTokenizer stringTokenizer = new StringTokenizer(libDirPathsString, File.pathSeparator);
while (stringTokenizer.hasMoreElements()) {
String libDirPath = (String) stringTokenizer.nextElement();
libDirPathList.add(libDirPath);
}
return libDirPathList.toArray(new String[libDirPathList.size()]);
}
private static String assembleLibDirPaths(String[] libDirPaths) {
StringBuilder sb = new StringBuilder(64);
for (String libDirPath : libDirPaths) {
if (sb.length() > 0) {
sb.append(File.pathSeparator);
}
sb.append(libDirPath);
}
return sb.toString();
}
private static RuntimeConfigException createMissingPropertyKeyException(String key) {
return new RuntimeConfigException(
String.format("Property '%s' has not been set.", key));
}
private static RuntimeConfigException createInvalidPropertyValueException(String key, String value) {
return new RuntimeConfigException(String.format("Value of property '%s' is invalid: %s", key, value));
}
private void trace(String msg) {
if (debug) {
System.out.println(String.format("[DEBUG] ceres-config: %s", msg));
}
}
private boolean isPropertySet(String key) {
return properties.containsKey(key);
}
private String getProperty(String key) {
return getProperty(key, null);
}
private String getProperty(String key, String defaultValue) {
String property = properties.getProperty(key, defaultValue);
if (property != null) {
return substitute(property);
}
return property;
}
private void setProperty(String key, String value) {
if (value != null) {
properties.setProperty(key, value);
} else {
properties.remove(key);
}
}
/**
* Substitues all occurences of <code>${<i>configKey</i>}</code> in the given string
* with the value of <code><i>configKey</i></code>.
*
* @param value the string in which to perform the substitution.
* @return the resulting string.
*/
private String substitute(String value) {
if (value.indexOf('$') == -1) {
return value;
}
StringReader r = new StringReader(value);
try {
return new TemplateReader(r, properties).readAll();
} catch (IOException e) {
return value;
}
}
private static class LogFormatter extends Formatter {
@Override
public String format(LogRecord record) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.append('[');
pw.append(record.getLevel().toString());
pw.append(']');
pw.append(' ');
pw.append(LOG_TIME_STAMP_FORMAT.format(new Date(record.getMillis())));
pw.append(' ');
pw.append('-');
pw.append(' ');
pw.append(record.getMessage());
Throwable thrown = record.getThrown();
if (thrown != null) {
pw.println();
thrown.printStackTrace(pw);
}
pw.println();
return sw.toString();
}
}
}
| 24,862 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
Zip.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/Zip.java | package gov.nasa.gsfc.seadas.ocsswrest.utilities;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 8/7/12
* Time: 1:10 PM
* To change this template use File | Settings | File Templates.
*/
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Zip {
static final int BUFFER = 2048;
private static final String FILE_DOWNLOAD_PATH = System.getProperty("user.dir") + System.getProperty("file.separator") + "ofiles";
public static void main(String argv[]) {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(FILE_DOWNLOAD_PATH + File.separator + "ofiles.zip");
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
File f = new File(".");
String files[] = f.list();
for (int i = 0; i < files.length; i++) {
System.out.println("Adding: " + files[i]);
FileInputStream fi = new FileInputStream(files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(files[i]);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0,
BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} | 1,608 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
TemplateReader.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/TemplateReader.java | package gov.nasa.gsfc.seadas.ocsswrest.utilities;
import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.Map;
/**
* A template reader replaces any occurences of <code>${<i>key</i>}</code> or <code>$<i>key</i></code>
* in the underlying stream with the string representations of any non-null value returned by a given
* resolver for that key.
*
* @author Norman Fomferra
*/
public class TemplateReader extends FilterReader {
private static final char DEFAULT_KEY_INDICATOR = '$';
private static final int EOF = -1;
private Resolver resolver;
private IntBuffer buffer;
private char keyIndicator = DEFAULT_KEY_INDICATOR;
/**
* Constructs a template reader for the given reader stream and a resolver given by a {@link java.util.Map}.
*
* @param in the underlying reader
* @param map the map to serve as resolver
*/
public TemplateReader(Reader in, Map map) {
this(in, new KeyValueResolver(map));
}
/**
* Constructs a template reader for the given reader stream and the given resolver.
*
* @param in the underlying reader
* @param resolver the resolver
*/
public TemplateReader(Reader in, Resolver resolver) {
super(in);
if (resolver == null) {
throw new NullPointerException("resolver");
}
this.resolver = resolver;
}
/**
* Gets the key indicator.
*
* @return the key indicator, defaults to '$'.
*/
public char getKeyIndicator() {
return keyIndicator;
}
/**
* Sets the key indicator.
*
* @param keyIndicator the key indicator, must not be a digit, letter or whitespace.
*/
public void setKeyIndicator(char keyIndicator) {
if (Character.isWhitespace(keyIndicator) || Character.isLetterOrDigit(keyIndicator)) {
throw new IllegalArgumentException();
}
this.keyIndicator = keyIndicator;
}
/**
* Reads all content.
* @return the content
* @throws java.io.IOException if an I/O error occurs
*/
public String readAll() throws IOException {
StringBuilder sb = new StringBuilder(16 * 1024);
while (true) {
int i = read();
if (i == EOF) {
break;
}
sb.append((char) i);
}
return sb.toString();
}
/**
* Read a single character.
*
* @throws java.io.IOException If an I/O error occurs
*/
@Override
public int read() throws IOException {
synchronized (lock) {
if (buffer != null && buffer.ready()) {
return buffer.next();
}
int c = in.read();
if (c != keyIndicator) {
return c;
}
if (buffer == null) {
buffer = new IntBuffer();
}
buffer.reset();
buffer.append(keyIndicator);
c = readAndBuffer();
if (c != EOF) {
int keyType = 0;
if (c == '{') { // ${key}?
do {
c = readAndBuffer();
if (c == '}') {
keyType = 1;
break;
}
} while (c != EOF);
} else if (Character.isJavaIdentifierStart(c)) { // $key?
keyType = 2;
do {
c = readAndBuffer();
if (!(Character.isJavaIdentifierPart(c) || c == '.')) {
break;
}
} while (c != EOF);
}
if (keyType != 0) {
String key;
if (keyType == 1) { // ${key}
key = buffer.substring(2, buffer.length() - 1);
} else { // $key
key = buffer.substring(1, buffer.length() - 1);
}
Object value = resolver.resolve(key);
if (value != null) {
String s = value.toString();
int last;
if (keyType == 1) { // ${key}
last = in.read();
buffer.reset();
buffer.append(s);
} else { // $key
last = buffer.charAt(buffer.length() - 1);
buffer.reset();
buffer.append(s);
}
buffer.append(last); // last can also be EOF!
}
}
}
return buffer.next();
}
}
/**
* Read characters into an array. This method will block until some input
* is available, an I/O error occurs, or the end of the stream is reached.
*
* @param cbuf Destination buffer
* @return The number of characters read, or -1
* if the end of the stream
* has been reached
* @throws java.io.IOException If an I/O error occurs
*/
@Override
public int read(char cbuf[]) throws IOException {
return read(cbuf, 0, cbuf.length);
}
/**
* Read characters into a portion of an array.
*
* @throws java.io.IOException If an I/O error occurs
*/
@Override
public int read(char cbuf[], int off, int len) throws IOException {
synchronized (lock) {
int i;
for (i = 0; i < len; i++) {
int c = read();
if (c == EOF) {
return i == 0 ? EOF : i;
}
cbuf[off + i] = (char) c;
}
return i;
}
}
/**
* Attempts to read characters into the specified character buffer.
* The buffer is used as a repository of characters as-is: the only
* changes made are the results of a put operation. No flipping or
* rewinding of the buffer is performed.
*
* @param target the buffer to read characters into
* @return The number of characters added to the buffer, or
* -1 if this source of characters is at its end
* @throws java.io.IOException if an I/O error occurs
* @throws NullPointerException if target is null
* @throws java.nio.ReadOnlyBufferException
* if target is a read only buffer
*/
@Override
public int read(CharBuffer target) throws IOException {
synchronized (lock) {
int len = target.remaining();
char[] cbuf = new char[len];
int n = read(cbuf, 0, len);
if (n > 0) {
target.put(cbuf, 0, n);
}
return n;
}
}
/**
* Skip characters.
*
* @throws java.io.IOException If an I/O error occurs
*/
@Override
public long skip(long n) throws IOException {
synchronized (lock) {
if (n < 0L) {
throw new IllegalArgumentException("skip value is negative");
}
long i;
for (i = 0; i < n; i++) {
int c = read();
if (c == EOF) {
break;
}
}
return i;
}
}
/**
* Tell whether this stream is ready to be read.
*
* @throws java.io.IOException If an I/O error occurs
*/
@Override
public boolean ready() throws IOException {
return (buffer != null && buffer.ready()) || in.ready();
}
/**
* Tell whether this stream supports the mark() operation.
*/
@Override
public boolean markSupported() {
return false;
}
/**
* Mark the present position in the stream.
*
* @throws java.io.IOException If an I/O error occurs
*/
@Override
public void mark(int readAheadLimit) throws IOException {
throw new IOException("mark() not supported");
}
/**
* Reset the stream.
*
* @throws java.io.IOException If an I/O error occurs
*/
@Override
public void reset() throws IOException {
throw new IOException("reset() not supported");
}
/**
* Close the stream.
*
* @throws java.io.IOException If an I/O error occurs
*/
@Override
public void close() throws IOException {
super.close();
buffer = null;
}
/////////////////////////////////////////////////////////////////////////////
private int readAndBuffer() throws IOException {
int c = in.read();
buffer.append(c);
return c;
}
/////////////////////////////////////////////////////////////////////////////
public interface Resolver {
Object resolve(String reference);
}
private static class KeyValueResolver implements Resolver {
private Map map;
public KeyValueResolver(Map map) {
if (map == null) {
throw new NullPointerException("map");
}
this.map = map;
}
public Object resolve(String reference) {
return map.get(reference);
}
}
/**
* A buffer to which EOF can also be appended.
*/
private static class IntBuffer {
private final static int INC = 8192;
private int[] buffer;
private int length;
private int index;
public IntBuffer() {
this.buffer = new int[INC];
}
public void reset() {
length = 0;
index = 0;
}
public int next() {
if (!ready()) {
throw new IllegalStateException("!ready()");
}
return buffer[index++];
}
public int charAt(int pos) {
if (pos < 0) {
throw new IndexOutOfBoundsException("pos < 0");
}
if (pos >= length) {
throw new IndexOutOfBoundsException("pos >= length");
}
return buffer[pos];
}
public void append(int c) {
if (length >= buffer.length) {
int[] newBuffer = new int[buffer.length + INC];
System.arraycopy(buffer, 0, newBuffer, 0, length);
buffer = newBuffer;
}
buffer[length++] = c;
}
public void append(String s) {
for (int i = 0; i < s.length(); i++) {
append((int) s.charAt(i));
}
}
public boolean ready() {
return index < length;
}
public String substring(int start, int end) {
int n = end - start;
char[] cbuf = new char[n];
for (int i = start; i < end; i++) {
cbuf[i - start] = (char) buffer[i];
}
return new String(cbuf);
}
public int length() {
return length;
}
}
}
| 11,211 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
Job.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/Job.java | package gov.nasa.gsfc.seadas.ocsswrest.utilities;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 6/18/13
* Time: 1:17 PM
* To change this template use File | Settings | File Templates.
*/
public class Job {
private String jobID;
private boolean active;
private String jobDir;
public Job(){
jobID = generateJobID();
active = true;
jobDir = null;
}
public String generateJobID(){
return hashJobID(new Long(new Date().getTime()).toString());
}
public String getJobID() {
return jobID;
}
public void setJobID(String jobID) {
this.jobID = jobID;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getJobDir() {
return jobDir;
}
public void setJobDir(String jobDir) {
this.jobDir = jobDir;
}
private String hashJobID(String jobID) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
md.update(jobID.getBytes());
byte byteData[] = md.digest();
//convert the byte to hex format
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
| 1,728 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MissionInfoFinder.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/MissionInfoFinder.java | package gov.nasa.gsfc.seadas.ocsswrest.utilities;
import gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWServerModel;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import static gov.nasa.gsfc.seadas.ocsswrest.utilities.ServerSideFileUtilities.debug;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 1/16/15
* Time: 3:23 PM
* To change this template use File | Settings | File Templates.
*/
public class MissionInfoFinder {
public HashMap<String, Boolean> missionDataStatus;
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";
public enum MissionNames {
AQUARIUS("AQUARIUS"),
AVHRR("AVHRR"),
CZCS("CZCS"),
GOCI("GOCI"),
HAWKEYE("HAWKEYE"),
HICO("HICO"),
MERIS("MERIS"),
MODISA("MODISA"),
MODIST("MODIST"),
MOS("MOS"),
MSIS2A("MSIS2A"),
MSIS2B("MSIS2B"),
OCI("OCI"),
OCM1("OCM1"),
OCM2("OCM2"),
OCTS("OCTS"),
OLIL8("OLIL8"),
OLIL9("OLIL9"),
OLCIS3A("OLCIS3A"),
OLCIS3B("OLCIS3B"),
OSMI("OSMI"),
SEAWIFS("SEAWIFS"),
VIIRSN("VIIRSN"),
VIIRSJ1("VIIRSJ1"),
VIIRSJ2("VIIRSJ2"),
SGLI("SGLI"),
UNKNOWN("UNKNOWN");
String missionName;
MissionNames(String fieldName) {
this.missionName = fieldName;
}
public String getMissionName() {
return missionName;
}
}
public enum MissionDirs {
AQUARIUS("aquarius"),
AVHRR("avhrr"),
CZCS("czcs"),
GOCI("goci"),
HAWKEYE("hawkeye"),
HICO("hico"),
MERIS("meris"),
MODISA("modisa"),
MODIST("modist"),
MOS("mos"),
MSIS2A("msi/s2a"),
MSIS2B("msi/s2b"),
OCI("oci"),
OCM1("ocm1"),
OCM2("ocm2"),
OCTS("octs"),
OLIL8("oli/l8"),
OLIL9("oli/l9"),
OLCIS3A("olci/s3a"),
OLCIS3B("olci/s3b"),
OSMI("osmi"),
SEAWIFS("seawifs"),
VIIRSN("viirs/npp"),
VIIRSJ1("viirs/j1"),
VIIRSJ2("viirs/j2"),
SGLI("sgli"),
UNKNOWN("unknown");
String missionDir;
MissionDirs(String fieldName) {
this.missionDir = fieldName;
}
public String getMissionDir() {
return missionDir;
}
}
public MissionInfoFinder() {
initDirectoriesHashMap();
initNamesHashMap();
updateMissionStatus();
}
void updateMissionStatus() {
missionDataStatus = new HashMap<String, Boolean>();
try {
for (MissionNames missionName : MissionNames.values()) {
missionDataStatus.put(missionName.getMissionName(), new File(OCSSWServerModel.getOcsswDataDirPath() + File.separator + MissionDirs.valueOf(missionName.getMissionName()).getMissionDir()).exists());
//System.out.println(MissionDirs.valueOf(missionName.getMissionName()) + " status: " + OCSSWServerModel.getOcsswDataDirPath() + File.separator + MissionDirs.valueOf(missionName.getMissionName()).getMissionDir());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public JsonObject getMissions() {
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
for (MissionNames missionName : MissionNames.values()) {
jsonObjectBuilder.add(missionName.getMissionName(), new File(OCSSWServerModel.getOcsswDataDirPath() + File.separator + MissionDirs.valueOf(missionName.getMissionName()).getMissionDir()).exists());
//System.out.println(MissionDirs.valueOf(missionName.getMissionName()) + " status: " + new File(OCSSWServerModel.getOcsswDataDirPath() + File.separator + MissionDirs.valueOf(missionName.getMissionName()).getMissionDir()).exists());
}
return jsonObjectBuilder.build();
}
public JsonObject getL2BinSuites(String missionName) {
setName(missionName);
//File missionDir = new File(OCSSWServerModel.getOcsswDataDirPath() + File.separator + getDirectory());
String[] suites = directory.list(new FilenameFilter() {
@Override
public boolean accept(File file, String s) {
return s.contains("l2bin_defaults_");
}
});
JsonObjectBuilder job = Json.createObjectBuilder();
for (String str : suites) {
job.add(str, true);
}
JsonObject missionSuites = job.build();
return missionSuites;
}
public String[] getMissionSuiteList(String missionName, String mode) {
setName(missionName);
//File missionDir = new File(OCSSWServerModel.getOcsswDataDirPath() + File.separator + missionName);
File missionDir = directory;
System.out.println("mission directory: " + missionDir);
if (missionDir.exists()) {
ArrayList<String> suitesArrayList = new ArrayList<String>();
File missionDirectoryFiles[] = missionDir.listFiles();
for (File file : missionDirectoryFiles) {
String filename = file.getName();
debug("fileName: " + filename);
if (filename.startsWith(getDefaultsFilePrefix(mode)) && filename.endsWith(".par")) {
String filenameTrimmed = filename.replaceFirst(getDefaultsFilePrefix(mode), "");
filenameTrimmed = filenameTrimmed.replaceAll("[\\.][p][a][r]$", "");
suitesArrayList.add(filenameTrimmed);
}
}
final String[] suitesArray = new String[suitesArrayList.size()];
int i = 0;
for (String suite : suitesArrayList) {
suitesArray[i] = suite;
debug("suite " + suite);
i++;
}
java.util.Arrays.sort(suitesArray);
if(suitesArray.length > 0) {
debug("mission suite: " + suitesArray[0] + suitesArray[1] + 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;
}
public String findMissionId(String missionName) {
Id missionId = Id.UNKNOWN;
Iterator itr = names.keySet().iterator();
while (itr.hasNext()) {
Object key = itr.next();
for (String name : names.get(key)) {
if (name.toLowerCase().equals(missionName.toLowerCase())) {
setId((Id) key);
missionId = (Id) key;
}
}
}
return missionId.name();
}
public enum Id {
AQUARIUS,
CZCS,
HAWKEYE,
HICO,
GOCI,
MERIS,
MODISA,
MODIST,
MOS,
MSIS2A,
MSIS2B,
OCI,
OCTS,
OSMI,
SEAWIFS,
VIIRSN,
VIIRSJ1,
VIIRSJ2,
OCM1,
OCM2,
OLIL8,
OLIL9,
OLCIS3A,
OLCIS3B,
SGLI,
UNKNOWN
}
public final static Id[] SUPPORTED_IDS = {
Id.AQUARIUS,
Id.CZCS,
Id.HAWKEYE,
Id.HICO,
Id.GOCI,
Id.MERIS,
Id.MODISA,
Id.MODIST,
Id.MOS,
Id.MSIS2A,
Id.MSIS2B,
Id.OCI,
Id.OCTS,
Id.OSMI,
Id.SEAWIFS,
Id.VIIRSN,
Id.VIIRSJ1,
Id.VIIRSJ2,
Id.OCM1,
Id.OCM2,
Id.OLIL8,
Id.OLIL9,
Id.OLCIS3A,
Id.OLCIS3B,
Id.SGLI
};
public final static String[] SEAWIFS_NAMES = {"SeaWiFS"};
public final static String SEAWIFS_DIRECTORY = "seawifs";
public final static String[] MODISA_NAMES = { "MODISA"};
public final static String MODISA_DIRECTORY = "modisa";
public final static String[] MODIST_NAMES = {"MODIST"};
public final static String MODIST_DIRECTORY = "modist";
public final static String[] VIIRSN_NAMES = {"VIIRSN", "VIIRS"};
public final static String VIIRSN_DIRECTORY = "viirs/npp";
public final static String[] VIIRSJ1_NAMES = {"VIIRSJ1"};
public final static String VIIRSJ1_DIRECTORY = "viirs/j1";
public final static String[] VIIRSJ2_NAMES = {"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[] 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[] 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[] MSIS2A_NAMES = {"MSIS2A", "MSI 2A"};
public final static String MSIS2A_DIRECTORY = "msi/s2a";
public final static String[] MSIS2B_NAMES = {"MSIS2B", "MSI 2B"};
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[] 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;
private String[] suites;
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.CZCS, CZCS_DIRECTORY);
directories.put(Id.AQUARIUS, AQUARIUS_DIRECTORY);
directories.put(Id.OCTS, OCTS_DIRECTORY);
directories.put(Id.OSMI, OSMI_DIRECTORY);
directories.put(Id.MOS, MOS_DIRECTORY);
directories.put(Id.MSIS2A, MSIS2A_DIRECTORY);
directories.put(Id.MSIS2B, MSIS2B_DIRECTORY);
directories.put(Id.OCI, OCI_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.HAWKEYE, HAWKEYE_DIRECTORY);
directories.put(Id.SGLI, SGLI_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.CZCS, CZCS_NAMES);
names.put(Id.AQUARIUS, AQUARIUS_NAMES);
names.put(Id.OCTS, OCTS_NAMES);
names.put(Id.OSMI, OSMI_NAMES);
names.put(Id.MOS, MOS_NAMES);
names.put(Id.MSIS2A, MSIS2A_NAMES);
names.put(Id.MSIS2B, MSIS2B_NAMES);
names.put(Id.OCI, OCI_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.HAWKEYE, HAWKEYE_NAMES);
names.put(Id.SGLI, SGLI_NAMES);
}
public Id getId() {
return id;
}
public void setId(Id id) {
clear();
this.id = id;
if (isSupported()) {
setRequiresGeofile();
setMissionDirectoryName();
}
}
public boolean isId(Id id) {
return id == getId();
}
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(OCSSWServerModel.getOcsswDataDirPath(), words[0]));
setSubsensorDirectory(new File(OCSSWServerModel.getOcsswDataDirPath(), missionPiece));
return;
} else {
setDirectory(new File(OCSSWServerModel.getOcsswDataDirPath(), missionPiece));
setSubsensorDirectory(null);
return;
}
} catch (Exception e) { }
}
setDirectory(null);
setSubsensorDirectory(null);
}
// private void setMissionDirectoryName() {
// if (directories.containsKey(id)) {
// String missionPiece = directories.get(id);
// setDirectory(new File(OCSSWServerModel.getOcsswDataDirPath(), missionPiece));
// } else {
// setDirectory(null);
// }
// }
public File getDirectory() {
return directory;
}
public void setDirectory(File directory) {
this.directory = directory;
}
public boolean isSupported() {
if (id == null) {
return false;
}
for (Id supportedId : SUPPORTED_IDS) {
if (supportedId == this.id) {
return true;
}
}
return false;
}
public File getSubsensorDirectory() {
return subsensorDirectory;
}
private void setSubsensorDirectory(File directory) {
this.subsensorDirectory = directory;
}
}
| 17,969 | 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-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/MissionInfo.java | package gov.nasa.gsfc.seadas.ocsswrest.utilities;
import gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWServerModel;
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.
*/
public class MissionInfo {
public enum Id {
AQUARIUS,
AVHRR,
CZCS,
HAWKEYE,
HICO,
GOCI,
MERIS,
MODISA,
MODIST,
MOS,
MSIS2A,
MSIS2B,
OCI,
OCTS,
OSMI,
SEAWIFS,
VIIRSN,
VIIRSJ1,
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[] 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.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.HAWKEYE, HAWKEYE_DIRECTORY);
directories.put(Id.SGLI, SGLI_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.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.HAWKEYE, HAWKEYE_NAMES);
names.put(Id.SGLI, SGLI_NAMES);
}
public Id getId() {
return id;
}
public void setId(Id id) {
clear();
this.id = id;
if (isSupported()) {
setRequiresGeofile();
setMissionDirectoryName();
}
}
public boolean isId(Id id) {
return id == getId();
}
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.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(OCSSWServerModel.getOcsswDataDirPath(), words[0]));
setSubsensorDirectory(new File(OCSSWServerModel.getOcsswDataDirPath(), missionPiece));
return;
} else {
setDirectory(new File(OCSSWServerModel.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;
}
return id != Id.UNKNOWN;
}
}
| 9,932 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
RuntimeConfigException.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/RuntimeConfigException.java | package gov.nasa.gsfc.seadas.ocsswrest.utilities;
/**
* Indicates conditions that a reasonable Ceres application might want to catch.
*
* @author Norman Fomferra
* @version $Id: RuntimeConfigException.java,v 1.1 2007/03/28 11:39:11 norman Exp $
*/
public class RuntimeConfigException extends Exception {
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public RuntimeConfigException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and
* cause. <p>Note that the detail message associated with
* <code>cause</code> is <i>not</i> automatically incorporated in
* this exception's detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public RuntimeConfigException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,545 | 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-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/OCSSWInfo.java | package gov.nasa.gsfc.seadas.ocsswrest.utilities;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.File;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 1/9/15
* Time: 2:50 PM
* To change this template use File | Settings | File Templates.
* This class should always be synchronized with OCSSWInfo
*/
@XmlRootElement
public class OCSSWInfo {
public static final String _OCSSWROOT_ENVVAR = "OCSSWROOT";
public static String OCSSW_INSTALLER = "install_ocssw";
public static String OCSSW_RUNNER = "ocssw_runner";
public static final String SEADAS_OCSSW_VERSIONS_JSON_NAME = "seadasVersions.json";
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 String TMP_OCSSW_INSTALLER = (new File(System.getProperty("java.io.tmpdir"), "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_MANIFEST = (new File(System.getProperty("java.io.tmpdir"), "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 String _OCSSW_SCRIPTS_DIR_SUFFIX = System.getProperty("file.separator") + "bin";
public static String _OCSSW_DATA_DIR_SUFFIX = System.getProperty("file.separator") + "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";
private boolean installed;
private String ocsswDir;
public boolean isInstalled(){
return installed;
}
public void setInstalled(boolean installed) {
this.installed = installed;
}
public String getOcsswInstallDir(){
ocsswDir = System.getenv(_OCSSWROOT_ENVVAR);
return ocsswDir;
}
public String getOcsswDataDir(){
return ocsswDir + _OCSSW_DATA_DIR_SUFFIX;
}
public String getOcsswScriptsDir(){
return ocsswDir + _OCSSW_SCRIPTS_DIR_SUFFIX;
}
}
| 2,779 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWServerPropertyValues.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/OCSSWServerPropertyValues.java | package gov.nasa.gsfc.seadas.ocsswrest.utilities;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 4/27/15
* Time: 2:59 PM
* To change this template use File | Settings | File Templates.
*/
public class OCSSWServerPropertyValues {
static Properties properties;
final static String CONFIG_FILE_NAME = "ocsswserver.config";
final static String CLIENT_SHARED_DIR_NAME_PROPERTY = "clientSharedDirName";
final static String SERVER_SHARED_DIR_NAME_PROPERTY = "serverSharedDirName";
public OCSSWServerPropertyValues() {
properties = new Properties();
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(CONFIG_FILE_NAME);
try {
if (inputStream != null) {
properties.load(inputStream);
}
} catch (FileNotFoundException fnfe) {
System.out.println("config file not found!");
} catch (IOException ioe) {
System.out.println("IO exception!");
}
}
public String getPropValues(String propertyName) {
return properties.getProperty(propertyName);
}
public static String getClientSharedDirName(){
return properties.getProperty(CLIENT_SHARED_DIR_NAME_PROPERTY);
}
public static String getServerSharedDirName(){
System.out.println("shared dir name: " + properties.getProperty(SERVER_SHARED_DIR_NAME_PROPERTY));
return properties.getProperty(SERVER_SHARED_DIR_NAME_PROPERTY);
}
public void updateClientSharedDirName( String clientSharedDirName) {
properties.setProperty(CLIENT_SHARED_DIR_NAME_PROPERTY, clientSharedDirName);
}
private static void loadProperties(){
}
}
| 1,853 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ServerSideFileUtilities.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/ServerSideFileUtilities.java | package gov.nasa.gsfc.seadas.ocsswrest.utilities;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 5/16/13
* Time: 10:56 AM
* To change this template use File | Settings | File Templates.
*/
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 8/7/12
* Time: 2:20 PM
* To change this template use File | Settings | File Templates.
*/
public class ServerSideFileUtilities {
private static boolean debug = false;
public static final String FILE_UPLOAD_PATH = System.getProperty("user.dir") + System.getProperty("file.separator") + "ifiles";
public static final int BUFFER_SIZE = 1024;
public static void saveToDisc(final InputStream fileInputStream,
final String fileUploadPath) throws IOException
{
final OutputStream out = new FileOutputStream(new File(fileUploadPath));
int read = 0;
byte[] bytes = new byte[BUFFER_SIZE];
while ((read = fileInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
}
public static void saveStringToDisc(final String params,
final String filePath) throws IOException
{
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(new File(filePath));
fileWriter.write(params);
} finally {
if (fileWriter != null) {
fileWriter.close();
}
}
}
// save uploaded file to new location
public static void writeToFile(InputStream inputStream,
String fileLocation) {
try {
File outputFile = new File(fileLocation);
OutputStream outputStream = new FileOutputStream(outputFile);
int read = 0;
byte[] bytes = new byte[8192];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
inputStream.close();
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// save uploaded file to new location
public static void writeToFile(File inputFile,
String uploadedFileLocation) {
try {
File outputFile = new File(uploadedFileLocation);
OutputStream outputStream = new FileOutputStream(outputFile);
InputStream uploadedInputStream = new FileInputStream(inputFile);
int read = 0;
byte[] bytes = new byte[8192];
while ((read = uploadedInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
uploadedInputStream.close();
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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;
}
}
public static void debug(String message) {
if (debug) {
System.out.println("Debugging: " + message);
}
}
public static ArrayList<String> getFilesList(String dirPath) {
ArrayList<String> results = new ArrayList<String>();
File[] files = new File(dirPath).listFiles();
//If this pathname does not denote a directory, then listFiles() returns null.
for (File file : files) {
if (file.isFile()) {
results.add(file.getName());
}
}
return results;
}
public static String getLogFileName(String dirPath) {
File[] files = new File(dirPath).listFiles();
for (File file : files) {
if (file.isFile() && file.getName().indexOf("Processor") != -1 && file.getName().endsWith(".log")) {
return file.getAbsolutePath();
}
}
return null;
}
public static String manageDirectory(String filePath, boolean keepFiles) {
String message = "Client directory is left intact. All files are reusable.";
try {
File workingDir = new File(filePath);
if (workingDir.exists() && workingDir.isDirectory()) {
if (!keepFiles) {
ServerSideFileUtilities.purgeDirectory(workingDir);
message = "Client directory is emptied";
}
} else {
Files.createDirectories(new File(filePath).toPath());
message = "Client directory is created";
}
} catch (IOException e) {
e.printStackTrace();
}
return message;
}
public static void createDirectory(String dirPath) {
File newDir = new File(dirPath);
if (! (newDir.exists() && newDir.isDirectory() )) {
try {
Files.createDirectories(newDir.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void purgeDirectory(File dir) {
for (File file : dir.listFiles()) {
if (file.isDirectory()) purgeDirectory(file);
file.delete();
}
}
public static String getlastLine(String fileName) {
BufferedReader input = null;
String last = null, line;
try {
input = new BufferedReader(new FileReader(fileName));
while ((line = input.readLine()) != null) {
last = line;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return last;
}
/**
* 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;
}
}
| 7,160 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ORSProcessObserver.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/process/ORSProcessObserver.java | package gov.nasa.gsfc.seadas.ocsswrest.process;
import gov.nasa.gsfc.seadas.ocsswrest.database.SQLiteJDBC;
import gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWConfig;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by aabduraz on 3/22/16.
*/
public class ORSProcessObserver {
public static final String PROCESS_INPUT_STREAM_FILE_NAME = "processInputStream.log";
public static final String PROCESS_ERROR_STREAM_FILE_NAME = "processErrorStream.log";
private static final String STDOUT = "stdout";
private static final String STDERR = "stderr";
private final Process process;
private final String processName;
private final String jobId;
private int processInputStreamPortNumber;
private int processErrorStreamPortNumber;
/**
* Constructor.
*
* @param process The process to be observed
* @param processName A name that represents the process
*/
public ORSProcessObserver(final Process process, String processName, String jobId) {
this.process = process;
this.processName = processName;
this.jobId = jobId;
processInputStreamPortNumber = new Integer(System.getProperty(OCSSWConfig.OCSSW_PROCESS_INPUTSTREAM_SOCKET_PORT_NUMBER_PROPERTY)).intValue();
processErrorStreamPortNumber = new Integer(System.getProperty(OCSSWConfig.OCSSW_PROCESS_ERRORSTREAM_SOCKET_PORT_NUMBER_PROPERTY)).intValue();
SQLiteJDBC.updateItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName(), SQLiteJDBC.ProcessStatusFlag.STARTED.getValue());
}
/**
* Starts observing the given process. The method blocks until both {@code stdout} and {@code stderr}
* streams are no longer available. If the progress monitor is cancelled, the process will be destroyed.
*/
public final void startAndWait() {
final Thread stdoutReaderThread = new LineReaderThread(STDOUT);
final Thread stderrReaderThread = new LineReaderThread(STDERR);
stdoutReaderThread.start();
stderrReaderThread.start();
awaitTermintation(stdoutReaderThread, stderrReaderThread);
}
private void awaitTermintation(Thread stdoutReaderThread, Thread stderrReaderThread) {
while (stdoutReaderThread.isAlive() && stderrReaderThread.isAlive()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// todo - check what is best done now:
// * 1. just leave, and let the process be unattended (current impl.)
// 2. destroy the process
// 3. throw a checked ProgressObserverException
e.printStackTrace();
return;
}
}
}
private class LineReaderThread extends Thread {
private final String type;
public LineReaderThread(String type) {
super(processName + "-" + type);
this.type = type;
}
@Override
public void run() {
try {
read();
} catch (Exception e) {
e.printStackTrace();
}
}
private void read() {
InputStream inputStream = type.equals("stdout") ? process.getInputStream() : process.getErrorStream();
writeProcessStreamToSocket(inputStream, type.equals("stdout") ? processInputStreamPortNumber : processErrorStreamPortNumber);
}
private void writeProcessStreamToSocket(InputStream inputStream, int portNumber) {
System.out.println("server process observer: " + portNumber);
try (
ServerSocket serverSocket =
new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))
) {
String inputLine;
while ((inputLine = reader.readLine()) != null) {
out.println(inputLine);
}
int processStatus = process.waitFor();
System.out.println("final process status: " + processStatus);
SQLiteJDBC.updateItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName(), new Integer(process.exitValue()).toString());
serverSocket.setReuseAddress(true);
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 4,991 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWConfig.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/ocsswmodel/OCSSWConfig.java | package gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel;
/**
* Created by aabduraz on 4/19/17.
*/
import org.glassfish.grizzly.http.server.HttpServer;
import javax.ws.rs.ApplicationPath;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
@ApplicationPath("ocssw")
public class OCSSWConfig {
public final static String OCSSW_PROCESS_INPUTSTREAM_SOCKET_PORT_NUMBER_PROPERTY = "processInputStreamPortNumber";
public final static String OCSSW_PROCESS_ERRORSTREAM_SOCKET_PORT_NUMBER_PROPERTY = "processErrorStreamPortNumber";
public static Properties properties = new Properties(System.getProperties());
private ResourceLoader rl;
public OCSSWConfig(String configFilePath) {
rl = getResourceLoader(configFilePath);
readProperties(rl);
}
public Properties readProperties(ResourceLoader resourceLoader) {
InputStream inputStream = resourceLoader.getInputStream();
if (inputStream != null) {
try {
properties.load(inputStream);
String key, value;
Set<Object> keys = properties.keySet();
Iterator itr = keys.iterator();
while (itr.hasNext()) {
key = (String) itr.next();
value = properties.getProperty(key);
if (value.startsWith("$")) {
value = System.getProperty(value.substring(value.indexOf("{") + 1, value.indexOf("}"))) + value.substring(value.indexOf("}") + 1);
properties.setProperty(key, value);
}
}
// set the system properties
System.setProperties(properties);
// display new properties
System.getProperties().list(System.out);
} catch (IOException e) {
// TODO Add your custom fail-over code here
e.printStackTrace();
}
}
return properties;
}
private ResourceLoader getResourceLoader(String resourcePath) {
return new FileResourceLoader(resourcePath);
}
}
interface ResourceLoader {
InputStream getInputStream();
}
class ClassResourceLoader implements ResourceLoader {
private final String resource;
public ClassResourceLoader(String resource) {
this.resource = resource;
}
@Override
public InputStream getInputStream() {
return HttpServer.class.getResourceAsStream(resource);
}
}
class FileResourceLoader implements ResourceLoader {
private final String resource;
public FileResourceLoader(String resource) {
this.resource = resource;
}
@Override
public InputStream getInputStream() {
try {
return new FileInputStream(resource);
} catch (Exception x) {
return null;
}
}
}
| 2,983 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWServerModel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/ocsswmodel/OCSSWServerModel.java | package gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel;
import gov.nasa.gsfc.seadas.ocsswrest.utilities.MissionInfo;
import gov.nasa.gsfc.seadas.ocsswrest.utilities.ServerSideFileUtilities;
import java.io.File;
import java.nio.file.Files;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import static gov.nasa.gsfc.seadas.ocsswrest.utilities.OCSSWInfo.*;
import static java.nio.file.StandardCopyOption.*;
/**
* Created by aabduraz on 3/27/17.
*/
public class OCSSWServerModel {
public static final String OS_64BIT_ARCHITECTURE = "_64";
public static final String OS_32BIT_ARCHITECTURE = "_32";
private static String NEXT_LEVEL_NAME_FINDER_PROGRAM_NAME = "get_output_name";
private static String NEXT_LEVEL_FILE_NAME_TOKEN = "Output Name:";
public static final String OBPG_FILE_TYPE_PROGRAM_NAME = "obpg_file_type";
public static final String OCSSW_SCRIPTS_DIR_NAME = "bin";
public static final String OCSSW_DATA_DIR_NAME = "share";
public static final String OCSSW_BIN_DIR_NAME = "bin";
public static final String OCSSW_SRC_DIR_NAME = "ocssw_src";
public static final String OCSSW_COMMON_DIR_NAME = "common";
public static final String OCSSW_VIIRS_DEM_NAME = "share" + File.separator + "viirs" + File.separator + "dem";
public static String OCSSW_INSTALLER_PROGRAM = "install_ocssw";
public static String OCSSW_RUNNER_SCRIPT = "ocssw_runner";
public static String TMP_OCSSW_INSTALLER_PROGRAM_PATH = (new File(System.getProperty("java.io.tmpdir"), "install_ocssw")).getPath();
private static boolean ocsswInstalScriptDownloadSuccessful = false;
public static String getOcsswDataDirPath() {
return ocsswDataDirPath;
}
public static String getOcsswScriptsDirPath() {
return ocsswScriptsDirPath;
}
public static String getOcsswInstallerScriptPath() {
return ocsswInstallerScriptPath;
}
public static String getOcsswRunnerScriptPath() {
return ocsswRunnerScriptPath;
}
public static String getOcsswBinDirPath() {
return ocsswBinDirPath;
}
public static String getOcsswSrcDirPath() {
return ocsswSrcDirPath;
}
public static String getOcsswViirsDemPath() {
return ocsswViirsDemPath;
}
public static String getSeadasVersion() {
return seadasVersion;
}
public static void setSeadasVersion(String seadasVersion) {
OCSSWServerModel.seadasVersion = seadasVersion;
}
public enum ExtractorPrograms {
L1AEXTRACT_MODIS("l1aextract_modis"),
L1AEXTRACT_SEAWIFS("l1extract_seawifs"),
L1AEXTRACT__VIIRS("l1aextract_viirs"),
L2EXTRACT("l2extract");
String extractorProgramName;
ExtractorPrograms(String programName) {
extractorProgramName = programName;
}
public String getExtractorProgramName() {
return extractorProgramName;
}
}
final String L1AEXTRACT_MODIS = "l1aextract_modis",
L1AEXTRACT_MODIS_XML_FILE = "l1aextract_modis.xml",
L1AEXTRACT_SEAWIFS = "l1aextract_seawifs",
L1AEXTRACT_SEAWIFS_XML_FILE = "l1aextract_seawifs.xml",
L1AEXTRACT_VIIRS = "l1aextract_viirs",
L1AEXTRACT_VIIRS_XML_FILE = "l1aextract_viirs.xml",
L2EXTRACT = "l2extract",
L2EXTRACT_XML_FILE = "l2extract.xml";
private static boolean ocsswExist;
private static String ocsswRoot;
static String ocsswDataDirPath;
private static String ocsswScriptsDirPath;
private static String ocsswInstallerScriptPath;
private static String ocsswRunnerScriptPath;
private static String ocsswBinDirPath;
private static String ocsswSrcDirPath;
private static String ocsswViirsDemPath;
private static String seadasVersion;
static boolean isProgramValid;
public OCSSWServerModel() {
initiliaze();
ocsswExist = isOCSSWExist();
}
public static void initiliaze() {
String ocsswRootPath = System.getProperty("ocsswroot");
if (ocsswRootPath != null) {
final File dir = new File(ocsswRootPath + File.separator + OCSSW_SCRIPTS_DIR_NAME);
System.out.println("server ocssw root path: " + dir.getAbsoluteFile());
ocsswExist = dir.isDirectory();
ocsswRoot = ocsswRootPath;
ocsswScriptsDirPath = ocsswRoot + File.separator + OCSSW_SCRIPTS_DIR_NAME;
ocsswDataDirPath = ocsswRoot + File.separator + OCSSW_DATA_DIR_NAME;
ocsswBinDirPath = ocsswRoot + File.separator + OCSSW_BIN_DIR_NAME;
ocsswSrcDirPath = ocsswRoot + File.separator + OCSSW_SRC_DIR_NAME;
ocsswInstallerScriptPath = ocsswScriptsDirPath + File.separator + OCSSW_INSTALLER_PROGRAM;
ocsswRunnerScriptPath = ocsswScriptsDirPath + File.separator + OCSSW_RUNNER_SCRIPT;
ocsswViirsDemPath = ocsswRoot + File.separator + OCSSW_VIIRS_DEM_NAME;
copyNetrcFile();
downloadOCSSWInstaller();
}
}
public static 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;
}
public static boolean isOCSSWExist() {
return ocsswExist;
}
public static String getOcsswRoot() {
return ocsswRoot;
}
/**
* This method will validate the program name. Only programs exist in $OCSSWROOT/run/scripts and $OSSWROOT/run/bin/"os_name" can be executed on the server side.
*
* @param programName
* @return true if programName is found in the $OCSSWROOT/run/scripts or $OSSWROOT/run/bin/"os_name" directories. Otherwise return false.
*/
public static boolean isProgramValid(String programName) {
//"extractor" is special, it can't be validated using the same logic for other programs.
if (programName.equals("extractor")) {
return true;
}
isProgramValid = false;
File scriptsFolder = new File(ocsswScriptsDirPath);
File[] listOfScripts = scriptsFolder.listFiles();
File runFolder = new File(ocsswBinDirPath);
File[] listOfPrograms = runFolder.listFiles();
File[] executablePrograms = ServerSideFileUtilities.concatAll(listOfPrograms, listOfScripts);
for (File file : executablePrograms) {
if (file.isFile() && programName.equals(file.getName())) {
isProgramValid = true;
break;
}
}
return isProgramValid;
}
public static boolean isOcsswInstalScriptDownloadSuccessful() {
return ocsswInstalScriptDownloadSuccessful;
}
/**
* This method downloads the ocssw installer program ocssw_install to a tmp directory
*
* @return
*/
public static boolean downloadOCSSWInstaller() {
if (isOcsswInstalScriptDownloadSuccessful()) {
return ocsswInstalScriptDownloadSuccessful;
}
try {
//download install_ocssw
URL website = new URL(OCSSW_INSTALLER_URL);
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();
} catch (MalformedURLException malformedURLException) {
System.out.println("URL for downloading install_ocssw is not correct!");
} catch (FileNotFoundException fileNotFoundException) {
System.out.println("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) {
System.out.println("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 static void copyNetrcFile() {
File targetFile = new File(System.getProperty("user.home") + File.separator + ".netrc");
try {
targetFile.createNewFile();
Path targetPath = targetFile.toPath();
File sourceFile = new File(System.getProperty("user.home") + File.separator + "seadasClientServerShared" + File.separator + ".netrc");
Path sourcePath = sourceFile.toPath();
System.out.println(".netrc in seadasClientServer " + sourceFile.exists());
System.out.println(".netrc in home dir " + targetFile.exists());
Files.copy(sourcePath, targetPath, REPLACE_EXISTING);
} catch (java.io.IOException ioException) {
ioException.printStackTrace();
}
}
}
| 10,669 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OCSSWRemoteImpl.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/ocsswmodel/OCSSWRemoteImpl.java | package gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel;
import gov.nasa.gsfc.seadas.ocsswrest.database.SQLiteJDBC;
import gov.nasa.gsfc.seadas.ocsswrest.process.ORSProcessObserver;
import gov.nasa.gsfc.seadas.ocsswrest.utilities.MissionInfo;
import gov.nasa.gsfc.seadas.ocsswrest.utilities.ServerSideFileUtilities;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.swing.*;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import static gov.nasa.gsfc.seadas.ocsswrest.ocsswmodel.OCSSWServerModel.*;
import static gov.nasa.gsfc.seadas.ocsswrest.utilities.OCSSWInfo.*;
import static gov.nasa.gsfc.seadas.ocsswrest.utilities.ServerSideFileUtilities.debug;
/**
* Created by aabduraz on 5/15/17.
*/
public class OCSSWRemoteImpl {
final static String OCSSW_ROOT_PROPERTY = "ocsswroot";
final static String SERVER_WORKING_DIRECTORY_PROPERTY = "serverWorkingDirectory";
private static String NEXT_LEVEL_NAME_FINDER_PROGRAM_NAME = "get_output_name";
private static String NEXT_LEVEL_FILE_NAME_TOKEN = "Output Name:";
public static final String OBPG_FILE_TYPE_PROGRAM_NAME = "obpg_file_type";
public static String OCSSW_INSTALLER_PROGRAM = "install_ocssw";
public static String MLP_PROGRAM_NAME = "multilevel_processor";
public static String MLP_PAR_FILE_NAME = "multilevel_processor_parFile.par";
public static String MLP_OUTPUT_DIR_NAME = "mlpOutputDir";
public static String ANC_FILE_LIST_FILE_NAME = "anc_file_list.txt";
public static final String FILE_TYPE_VAR_NAME = "fileType";
public static final String MISSION_NAME_VAR_NAME = "missionName";
public static final String US_ASCII_CHAR_SET = "us-ascii";
public static String PROCESS_STDOUT_FILE_NAME_EXTENSION = ".log";
public static String TMP_OCSSW_INSTALLER_PROGRAM_PATH = (new File(System.getProperty("java.io.tmpdir"), "install_ocssw")).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";
String programName;
String missionName;
String fileType;
public String[] getCommandArrayPrefix(String programName) {
String[] commandArrayPrefix;
if (programName.equals(OCSSW_INSTALLER_PROGRAM)) {
commandArrayPrefix = new String[1];
if (!isOCSSWExist()) {
commandArrayPrefix[0] = TMP_OCSSW_INSTALLER_PROGRAM_PATH;
} else {
commandArrayPrefix[0] = getOcsswInstallerScriptPath();
}
} else {
commandArrayPrefix = new String[3];
commandArrayPrefix[0] = getOcsswRunnerScriptPath();
commandArrayPrefix[1] = "--ocsswroot";
commandArrayPrefix[2] = getOcsswRoot();
}
for (String item : commandArrayPrefix) {
debug("commandArrayPrefix: " + item);
}
return commandArrayPrefix;
}
//TODO this needs to be modified
public String[] getCommandArraySuffix(String programName) {
String[] commandArraySuffix = null;
// if (programName.equals(OCSSW_INSTALLER_PROGRAM)) {
// commandArraySuffix = new String[2];
// String[] parts = OCSSWServerModel.getSeadasVersion().split("\\.");
// commandArraySuffix[0] = "--tag=" + OCSSWServerModel.getOCSSWTag(); //"--git-branch=v" + parts[0] + "." + parts[1];
// commandArraySuffix[1] = "--seadas";
// }
// if (commandArraySuffix != null) {
// for (String item : commandArraySuffix) {
// debug("commandArraySuffix " + item);
// }
// }
return commandArraySuffix;
}
public void executeProgram(String jobId, JsonObject jsonObject) {
programName = SQLiteJDBC.getProgramName(jobId);
String workingFileDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String[] commandArray = transformCommandArray(jobId, jsonObject, programName);
executeProcessInWorkingDirectory(ServerSideFileUtilities.concatAll(getCommandArrayPrefix(programName), commandArray, getCommandArraySuffix(programName)), workingFileDir, jobId);
}
public void executeProgramOnDemand(String jobId, String programName, JsonObject jsonObject) {
String[] commandArray = transformCommandArray(jobId, jsonObject, programName);
String workingFileDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
executeProcessInWorkingDirectory(ServerSideFileUtilities.concatAll(getCommandArrayPrefix(programName), commandArray, getCommandArraySuffix(programName)), workingFileDir, jobId);
}
public Process executeUpdateLutsProgram(String jobId, JsonObject jsonObject) {
programName = "update_luts";
Set commandArrayKeys = jsonObject.keySet();
Object[] array = commandArrayKeys.toArray();
String commandArrayElement;
Process process = null;
for (Object element : array) {
commandArrayElement = jsonObject.getString((String) element);
debug("update_luts option: " + commandArrayElement);
process = executeSimple(ServerSideFileUtilities.concatAll(getCommandArrayPrefix(programName), new String[]{programName, commandArrayElement}, getCommandArraySuffix(programName)));
}
return process;
}
public String executeGetSystemInfoProgram() {
String[] command = {"/bin/bash", getOcsswRunnerScriptPath(), " --ocsswroot ", getOcsswRoot(), OCSSW_SEADAS_INFO_PROGRAM_NAME};
String currentInfoLine = "";
String DASHES = "-----------------------------------------------------------";
String INDENT = " ";
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 (OCSSW Docker Container): " + "\n";
currentInfoLine += DASHES + "\n";
} else {
if (line.contains("Java version")) {
line = "Java version: " + System.getProperty("java.version");
}
currentInfoLine += line + "\n";
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return currentInfoLine;
}
private String[] transformCommandArray(String jobId, JsonObject jsonObject, String programName) {
String serverWorkingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
Set commandArrayKeys = jsonObject.keySet();
debug(" programName = " + programName);
Object[] array = commandArrayKeys.toArray();
int i = 0;
String[] commandArray;
if (!programName.equals(OCSSW_INSTALLER_PROGRAM)) {
commandArray = new String[commandArrayKeys.size() + 1];
commandArray[i++] = programName;
} else {
commandArray = new String[commandArrayKeys.size()];
}
String commandArrayElement;
for (Object element : array) {
debug(" element = " + element);
String elementName = (String) element;
commandArrayElement = jsonObject.getString((String) element);
if ((elementName.contains("IFILE") && !isAncFile(commandArrayElement)) || elementName.contains("OFILE")) {
if (!(commandArrayElement.contains(System.getProperty(SERVER_WORKING_DIRECTORY_PROPERTY)) || commandArrayElement.contains(System.getProperty(OCSSW_ROOT_PROPERTY)))) {
if (commandArrayElement.indexOf("=") != -1) {
StringTokenizer st = new StringTokenizer(commandArrayElement, "=");
String paramName = st.nextToken();
String paramValue = st.nextToken();
commandArrayElement = paramName + "=" + serverWorkingDir + File.separator + paramValue.substring(paramValue.lastIndexOf(File.separator) + 1);
} else {
commandArrayElement = serverWorkingDir + File.separator + commandArrayElement.substring(commandArrayElement.lastIndexOf(File.separator) + 1);
}
}
}
debug("command array element = " + commandArrayElement);
commandArray[i++] = commandArrayElement;
}
return commandArray;
}
private boolean isAncFile(String fileName) {
boolean isAncFile = fileName.contains("/var/anc/");
return isAncFile;
}
public InputStream executeProgramAndGetStdout(String jobId, String programName, JsonObject jsonObject) {
String[] commandArray = ServerSideFileUtilities.concatAll(getCommandArrayPrefix(programName), transformCommandArray(jobId, jsonObject, programName));
debug("command array content to get stdout: ");
for (int j = 0; j < commandArray.length; j++) {
System.out.print(commandArray[j] + " ");
}
Process process = null;
InputStream processInputStream = null;
try {
ProcessBuilder processBuilder = new ProcessBuilder(commandArray);
process = processBuilder.start();
process.waitFor();
processInputStream = process.getInputStream();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (process == null) {
debug(programName + " failed to create process.");
}
return processInputStream;
}
public void executeProgramSimple(String jobId, String programName, JsonObject jsonObject) {
String[] commandArray = transformCommandArray(jobId, jsonObject, programName);
executeProcessSimple(ServerSideFileUtilities.concatAll(getCommandArrayPrefix(programName), commandArray, getCommandArraySuffix(programName)), jobId, programName);
}
public void executeMLP(String jobId, File parFile) {
try {
String workingFileDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String parFileNewLocation = workingFileDir + File.separator + MLP_PAR_FILE_NAME;
debug("mlp par file new path: " + parFileNewLocation);
String parFileContent = convertClientMLPParFilForRemoteServer(parFile, jobId);
ServerSideFileUtilities.writeStringToFile(parFileContent, parFileNewLocation);
String[] commandArray = {MLP_PROGRAM_NAME, parFileNewLocation};
execute(ServerSideFileUtilities.concatAll(getCommandArrayPrefix(MLP_PROGRAM_NAME), commandArray), new File(parFileNewLocation).getParent(), jobId);
} catch (Exception e) {
e.printStackTrace();
}
}
//todo
public void executeWithParFile(String jobId, String programName, String parFileName) {
try {
String workingFileDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String parFileNewLocation = workingFileDir + File.separator + parFileName;
debug("par file new path: " + parFileNewLocation);
String parFileContent = convertClientParFileForRemoteServer(new File(parFileNewLocation), jobId);
debug("convert successful ");
ServerSideFileUtilities.writeStringToFile(parFileContent, parFileNewLocation);
debug("write successful ");
String[] commandArray = {programName, "par=" + parFileNewLocation};
execute(ServerSideFileUtilities.concatAll(getCommandArrayPrefix(programName), commandArray), new File(parFileNewLocation).getParent(), jobId);
} catch (Exception e) {
e.printStackTrace();
}
}
public JsonObject getMLPOutputFilesList(String jobId) {
String workingFileDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String mlpDir = workingFileDir;
Collection<String> filesInMLPDir = ServerSideFileUtilities.getFilesList(mlpDir);
Collection<String> inputFiles = SQLiteJDBC.getInputFilesList(jobId);
filesInMLPDir.removeAll(inputFiles);
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
Iterator itr = filesInMLPDir.iterator();
while (itr.hasNext()) {
jsonObjectBuilder.add("OFILE", (String) itr.next());
}
return jsonObjectBuilder.build();
}
public InputStream getProcessStdoutFile(String jobId) {
String workingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String processStdoutFileName = workingDir + File.separator + programName + PROCESS_STDOUT_FILE_NAME_EXTENSION;
if (programName.equals(MLP_PROGRAM_NAME)) {
processStdoutFileName = ServerSideFileUtilities.getLogFileName(workingDir);
}
File processStdoutFile = new File(processStdoutFileName);
InputStream processStdoutStream = null;
try {
processStdoutStream = new FileInputStream(processStdoutFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return processStdoutStream;
}
public JsonObject getMLPOutputFilesJsonList(String jobId) {
String workingFileDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String mlpOutputDir = workingFileDir + File.separator + MLP_OUTPUT_DIR_NAME;
Collection<String> filesInMLPDir = ServerSideFileUtilities.getFilesList(mlpOutputDir);
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
Iterator itr = filesInMLPDir.iterator();
int i = 0;
while (itr.hasNext()) {
jsonObjectBuilder.add("OFILE" + i++, (String) itr.next());
}
return jsonObjectBuilder.build();
}
private String convertClientParFileForRemoteServer(File parFile, String jobId) {
String parString = readFile(parFile.getAbsolutePath(), StandardCharsets.UTF_8);
StringTokenizer st1 = new StringTokenizer(parString, "\n");
StringTokenizer st2;
StringBuilder stringBuilder = new StringBuilder();
String token;
String key, value;
boolean isOdirdefined = true;
String workingFileDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
debug("server side workingFileDir: " + workingFileDir);
while (st1.hasMoreTokens()) {
token = st1.nextToken();
if (token.contains("=")) {
st2 = new StringTokenizer(token, "=");
key = st2.nextToken();
value = st2.nextToken();
value = value.replace("\\", File.separator);
debug("par file tokens:" + key + " " + value);
File ofile = new File(workingFileDir + File.separator + value);
debug("Does " + ofile.getAbsolutePath() + "exists? " + new File(workingFileDir + File.separator + value).exists());
if (new File(workingFileDir + File.separator + value).exists()) {
value = workingFileDir + File.separator + value;
debug("server side file: " + value);
} else {
debug("server side file: " + value + "!!! Attention !!! value is not converted! ");
}
token = key + "=" + value;
debug("token: " + token);
stringBuilder.append(token);
stringBuilder.append("\n");
}
}
String newParString = stringBuilder.toString();
debug("new par string: " + newParString);
return newParString;
}
private String convertClientMLPParFilForRemoteServer(File parFile, String jobId) {
String parString = readFile(parFile.getAbsolutePath(), StandardCharsets.UTF_8);
StringTokenizer st1 = new StringTokenizer(parString, "\n");
StringTokenizer st2;
StringBuilder stringBuilder = new StringBuilder();
String token;
String key, value;
boolean isOdirdefined = true;
int odirStringPositioninParFile = 6;
debug("converting the string");
String workingFileDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String mlpDir = workingFileDir;
String mlpOutputDir = workingFileDir + File.separator + MLP_OUTPUT_DIR_NAME;
//delete files from the MLP_OUTPUT_DIR_NAME before executing new mlp command.
ServerSideFileUtilities.purgeDirectory(new File(mlpOutputDir));
while (st1.hasMoreTokens()) {
token = st1.nextToken();
if (token.contains("=")) {
st2 = new StringTokenizer(token, "=");
key = st2.nextToken();
value = st2.nextToken();
value = value.replace("\\", File.separator);
if (new File(mlpDir + File.separator + value).exists()) {
value = mlpDir + File.separator + value;
debug("mlp file: " + value);
isOdirdefined = false;
try {
if (isTextFile(value)) {
debug("File is a text file. Need to upload the content.");
updateFileListFileContent(value, mlpDir);
}
} catch (Exception e) {
e.printStackTrace();
}
// make sure the par file contains "odir=mlpOutputDir" element.
} else if (!isOdirdefined) {
if (key.equals("odir")) {
value = mlpOutputDir;
} else {
stringBuilder.insert(odirStringPositioninParFile, "odir=" + mlpOutputDir + "\n");
}
isOdirdefined = true;
}
token = key + "=" + value;
}
stringBuilder.append(token);
stringBuilder.append("\n");
if (token.indexOf("ifile") != -1) {
odirStringPositioninParFile = stringBuilder.indexOf(token) + token.length() + 1;
}
}
//Create the mlp output dir; Otherwise mlp will throw exception
try {
Files.createDirectories(new File(mlpOutputDir).toPath());
} catch (IOException e) {
e.printStackTrace();
}
String newParString = stringBuilder.toString();
return newParString;
}
public String readFile(String path, Charset encoding) {
String fileString = new String();
try {
byte[] encoded = Files.readAllBytes(Paths.get(path));
fileString = new String(encoded, encoding);
} catch (IOException ioe) {
ioe.printStackTrace();
}
return fileString;
}
public void updateFileListFileContent(String fileListFileName, String mlpDir) {
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) {
debug("file name in the file list: " + fileName);
fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
stringBuilder.append(mlpDir + File.separator + fileName + "\n");
}
}
String fileContent = stringBuilder.toString();
debug(fileContent);
ServerSideFileUtilities.writeStringToFile(fileContent, fileListFileName);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void executeProcessInWorkingDirectory(String[] commandArray, String workingDir, String jobId) {
debug("command array content: ");
for (int j = 0; j < commandArray.length; j++) {
System.out.print(commandArray[j] + " ");
}
debug("\n" + "command array content ended ");
SwingWorker swingWorker = new SwingWorker() {
@Override
protected Object doInBackground() throws Exception {
ProcessBuilder processBuilder = new ProcessBuilder(commandArray);
Map<String, String> env = processBuilder.environment();
env.put("PWD", workingDir);
processBuilder.directory(new File(workingDir));
Process process = null;
try {
process = processBuilder.start();
} catch (Exception e) {
e.printStackTrace();
}
if (process == null) {
throw new IOException(programName + " failed to create process.");
}
if (process.isAlive()) {
debug("process is alive: ");
final ORSProcessObserver processObserver = new ORSProcessObserver(process, programName, jobId);
processObserver.startAndWait();
} else {
if (process.exitValue() == 0) {
SQLiteJDBC.updateItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName(), SQLiteJDBC.ProcessStatusFlag.COMPLETED.getValue());
} else {
SQLiteJDBC.updateItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName(), SQLiteJDBC.ProcessStatusFlag.FAILED.getValue());
}
}
return null;
}
};
swingWorker.execute();
}
public void executeProcessSimple(String[] commandArray, String jobId, String programName) {
StringBuilder sb = new StringBuilder();
for (String item : commandArray) {
sb.append(item + " ");
}
debug("command array content: " + sb.toString());
ProcessBuilder processBuilder = new ProcessBuilder(commandArray);
Process process = null;
try {
process = processBuilder.start();
SQLiteJDBC.updateItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName(), SQLiteJDBC.ProcessStatusFlag.STARTED.getValue());
if (process == null) {
throw new IOException(programName + " failed to create process.");
}
process.waitFor();
if (process.exitValue() == 0) {
SQLiteJDBC.updateItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName(), SQLiteJDBC.ProcessStatusFlag.COMPLETED.getValue());
} else {
SQLiteJDBC.updateItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobId, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName(), SQLiteJDBC.ProcessStatusFlag.FAILED.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
debug("process exited! exit value = " + process.exitValue());
debug(process.getInputStream().toString());
}
public Process executeSimple(String[] commandArray) {
StringBuilder sb = new StringBuilder();
for (String item : commandArray) {
sb.append(item + " ");
}
debug("command array content: " + sb.toString());
ProcessBuilder processBuilder = new ProcessBuilder(commandArray);
Process process = null;
try {
process = processBuilder.start();
if (process != null) {
debug("Running the program " + sb.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return process;
}
public void execute(String[] commandArrayParam, String workingDir, String jobIdParam) {
String jobID = jobIdParam;
String[] commandArray = commandArrayParam;
SwingWorker swingWorker = new SwingWorker() {
@Override
protected Object doInBackground() {
StringBuilder sb = new StringBuilder();
for (String item : commandArray) {
sb.append(item + " ");
}
debug("command array: " + sb.toString());
ProcessBuilder processBuilder = new ProcessBuilder(commandArray);
Map<String, String> env = processBuilder.environment();
env.put("PWD", workingDir);
processBuilder.directory(new File(workingDir));
Process process = null;
try {
process = processBuilder.start();
SQLiteJDBC.updateItem(SQLiteJDBC.PROCESS_TABLE_NAME, jobID, SQLiteJDBC.ProcessTableFields.STATUS.getFieldName(), SQLiteJDBC.ProcessStatusFlag.STARTED.getValue());
} catch (Exception e) {
e.printStackTrace();
}
final ORSProcessObserver processObserver = new ORSProcessObserver(process, programName, jobIdParam);
processObserver.startAndWait();
return process;
}
};
swingWorker.execute();
}
public HashMap<String, String> computePixelsFromLonLat(String jobId, String programName, JsonObject jsonObject) {
HashMap<String, String> pixels = new HashMap();
try {
String[] commandArray = transformCommandArray(jobId, jsonObject, programName);
Process process = executeSimple(ServerSideFileUtilities.concatAll(getCommandArrayPrefix(programName), 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]);
SQLiteJDBC.updateItem(SQLiteJDBC.LONLAT_TABLE_NAME, jobId, tmp[0], tmp[1]);
debug("pixels are not null: " + tmp[0] + "=" + tmp[1]);
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return pixels;
}
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;
}
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);
debug("mission suite name: " + 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(OCSSWServerModel.getOcsswDataDirPath(), "common");
debug("mission suites dir: " + dir.getAbsolutePath());
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 getOfileName(String jobId, String ifileName, String programName) {
if (ifileName == null || programName == null) {
return null;
}
if (programName.equals("l3bindump")) {
return ifileName + ".xml";
}
String[] commandArrayParams = {NEXT_LEVEL_NAME_FINDER_PROGRAM_NAME, ifileName, programName};
return getOfileName(ServerSideFileUtilities.concatAll(getCommandArrayPrefix(NEXT_LEVEL_NAME_FINDER_PROGRAM_NAME), commandArrayParams));
}
public String getOfileName(String jobId, JsonObject jsonObject) {
debug("jobId = " + jobId);
try {
String ifileName = jsonObject.getString("ifileName");
String programName = jsonObject.getString("programName");
String additionalOptionsString = jsonObject.getString("additionalOptions");
String serverWorkingDir = SQLiteJDBC.retrieveItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.WORKING_DIR_PATH.getFieldName());
String ifileNameWithFullPath = serverWorkingDir + File.separator + ifileName;
debug("finding ofile name for " + programName + " with input file " + ifileNameWithFullPath);
if (ifileName == null || programName == null) {
return null;
}
if (programName.equals("l3bindump")) {
return ifileName + ".xml";
}
StringTokenizer st = new StringTokenizer(additionalOptionsString, ";");
int i = 0;
String[] additionalOptions = new String[st.countTokens()];
while (st.hasMoreTokens()) {
additionalOptions[i++] = st.nextToken();
}
String[] commandArrayParams = {NEXT_LEVEL_NAME_FINDER_PROGRAM_NAME, ifileNameWithFullPath, programName};
String ofileName = getOfileName(ServerSideFileUtilities.concatAll(getCommandArrayPrefix(NEXT_LEVEL_NAME_FINDER_PROGRAM_NAME), commandArrayParams, additionalOptions));
SQLiteJDBC.updateItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.OFILE_NAME_FIELD_NAME, ofileName);
return ofileName;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void extractFileInfo(String ifileName, String jobId) {
String[] fileTypeCommandArrayParams = {OBPG_FILE_TYPE_PROGRAM_NAME, ifileName};
Process process = executeSimple(ServerSideFileUtilities.concatAll(getCommandArrayPrefix(OBPG_FILE_TYPE_PROGRAM_NAME), fileTypeCommandArrayParams));
try {
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = stdInput.readLine();
debug("line : " + line);
if (line != null) {
String splitLine[] = line.split(":");
if (splitLine.length == 3) {
String missionName = splitLine[1].trim();
String fileType = splitLine[2].trim();
debug("mission name : " + missionName);
debug("file type : " + fileType);
if (fileType.length() > 0) {
SQLiteJDBC.updateItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.I_FILE_TYPE.getFieldName(), fileType);
this.fileType = fileType;
}
if (missionName.length() > 0) {
SQLiteJDBC.updateItem(SQLiteJDBC.FILE_TABLE_NAME, jobId, SQLiteJDBC.FileTableFields.MISSION_NAME.getFieldName(), missionName);
this.missionName = missionName;
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public JsonObject getSensorFileIntoArrayList(String missionName) {
MissionInfo missionInfo = new MissionInfo(missionName);
debug("mission name: " + missionName);
//missionInfo.setName(missionName);
File file = getSensorInfoFilename(missionInfo);
debug("mission sensor file path : " + file.getAbsolutePath());
String lineData;
BufferedReader moFile = null;
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
int i = 0;
try {
moFile = new BufferedReader(new FileReader(file));
while ((lineData = moFile.readLine()) != null) {
jsonObjectBuilder.add("sensorInfo" + i++, lineData);
}
} catch (IOException e) {
} finally {
try {
moFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return jsonObjectBuilder.build();
}
private File getSensorInfoFilename(MissionInfo missionInfo) {
if (missionInfo != null) {
// determine the filename which contains the wavelength information
String SENSOR_INFO_FILENAME = "msl12_sensor_info.dat";
File subSensorDir = missionInfo.getSubsensorDirectory();
if (subSensorDir != null) {
File filename = new File(subSensorDir.getAbsolutePath(), SENSOR_INFO_FILENAME);
if (filename.exists()) {
return filename;
}
}
File missionDir = missionInfo.getDirectory();
if (missionDir != null) {
File filename = new File(missionDir.getAbsolutePath(), SENSOR_INFO_FILENAME);
if (filename.exists()) {
return filename;
}
}
}
return null;
}
public HashMap<String, String> getFileInfo(String ifileName, String jobId) {
HashMap<String, String> fileInfoMap = new HashMap<>();
String[] fileTypeCommandArrayParams = {OBPG_FILE_TYPE_PROGRAM_NAME, ifileName};
Process process = executeSimple(ServerSideFileUtilities.concatAll(getCommandArrayPrefix(OBPG_FILE_TYPE_PROGRAM_NAME), fileTypeCommandArrayParams));
try {
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = stdInput.readLine();
if (line != null) {
String splitLine[] = line.split(":");
if (splitLine.length == 3) {
String missionName = splitLine[1].trim();
String fileType = splitLine[2].trim();
if (fileType.length() > 0) {
fileInfoMap.put(FILE_TYPE_VAR_NAME, fileType);
}
if (missionName.length() > 0) {
fileInfoMap.put(MISSION_NAME_VAR_NAME, missionName);
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return fileInfoMap;
}
public String getFileCharset(String fileName) {
String charset = null;
String charSetKeyword = "charset";
String[] systemFileTypeCommandArraysParams = {"file", "-i", fileName};
Process process = executeSimple(systemFileTypeCommandArraysParams);
try {
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = stdInput.readLine();
if (line != null && line.indexOf(charSetKeyword) != -1) {
charset = line.substring(line.lastIndexOf("=") + 1).trim();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
debug("system file type = " + charset);
return charset;
}
public boolean isTextFile(String fileName) {
String charSet = getFileCharset(fileName);
debug("file type is: " + charSet);
return charSet.trim().equals(US_ASCII_CHAR_SET);
}
private String getOfileName(String[] commandArray) {
Process process = executeSimple(commandArray);
if (process == null) {
return null;
}
int exitCode = 100;
try {
exitCode = process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
debug("Finding ofile name; process exit value = '" + exitCode);
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(NEXT_LEVEL_FILE_NAME_TOKEN)) {
return (line.substring(NEXT_LEVEL_FILE_NAME_TOKEN.length())).trim();
}
line = br.readLine();
}
} else {
debug("Failed exit code on program '" + NEXT_LEVEL_NAME_FINDER_PROGRAM_NAME + "'");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
public JsonObject getOCSSWTags() {
Runtime rt = Runtime.getRuntime();
String[] commands = {TMP_OCSSW_BOOTSTRAP, TMP_OCSSW_INSTALLER, "--list_tags"};
Process proc = null;
try {
proc = rt.exec(commands);
} 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;
JsonArrayBuilder array = Json.createArrayBuilder();
ArrayList<String> tagsList = new ArrayList<>();
while (true) {
try {
if (!((s = stdInput.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(s);
array.add(s);
}
return Json.createObjectBuilder().add("tags", array.build()).build();
}
}
| 38,129 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
SQLiteJDBC.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/database/SQLiteJDBC.java | package gov.nasa.gsfc.seadas.ocsswrest.database;
import java.io.File;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 2/5/15
* Time: 5:30 PM
* To change this template use File | Settings | File Templates.
*/
public class SQLiteJDBC {
public static String JOB_DB_FILENAME = "ocssw.db";
public static String PROCESS_STDOUT_DB_FILENAME = "process_stdout.db";
public static String PROCESS_STDERR_DB_FILENAME = "process_stderr.db";
public static String JOB_DB_URL = "jdbc:sqlite:" + JOB_DB_FILENAME;
public static String PROCESS_STDOUT_DB_URL = "jdbc:sqlite:" + PROCESS_STDOUT_DB_FILENAME;
public static String PROCESS_STDERR_DB_URL = "jdbc:sqlite:" + PROCESS_STDERR_DB_FILENAME;
public static String DB_CLASS_FOR_NAME = "org.sqlite.JDBC";
private static String username = "obpg";
private static String password = "obpg";
public static final String FILE_TABLE_NAME = "FILE_TABLE";
public static final String MISSION_TABLE_NAME = "MISSION_TABLE";
public static final String PROCESS_TABLE_NAME = "PROCESS_TABLE";
public static final String LONLAT_TABLE_NAME = "LONLAT_2_PIXEL_TABLE";
public static final String PROCESS_MONITOR_STDOUT_TABLE_NAME = "PROCESS_MONITOR_STDOUT_TABLE";
public static final String PROCESS_MONITOR_STDERR_TABLE_NAME = "PROCESS_MONITOR_STDERR_TABLE";
public static final String INPUT_FILES_LIST_TABLE_NAME = "INPUT_FILES_LIST_TABLE";
public static final String JOB_ID_FIELD_NAME = "JOB_ID";
public static final String IFILE_NAME_FIELD_NAME = "I_FILE_NAME";
public static final String IFILE_TYPE_FIELD_NAME = "I_FILE_TYPE";
public static final String OFILE_NAME_FIELD_NAME = "O_FILE_NAME";
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 enum FileTableFields {
JOB_ID_NAME("JOB_ID"),
CLIENT_ID_NAME("CLIENT_ID_NAME"),
WORKING_DIR_PATH("WORKING_DIR_PATH"),
I_FILE_NAME("I_FILE_NAME"),
I_FILE_TYPE("I_FILE_TYPE"),
O_FILE_NAME("O_FILE_NAME"),
PROGRAM_NAME("PROGRAM_NAME"),
MISSION_NAME("MISSION_NAME"),
MISSION_DIR("MISSION_DIR");
String fieldName;
FileTableFields(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldName() {
return fieldName;
}
}
public enum ProcessStatusFlag{
NONEXIST(PROCESS_STATUS_NONEXIST),
STARTED(PROCESS_STATUS_STARTED),
COMPLETED(PROCESS_STATUS_COMPLETED),
FAILED(PROCESS_STATUS_FAILED);
String value;
ProcessStatusFlag(String value) {
this.value = value;
}
public String getValue(){
return value;
}
}
public enum ProcessTableFields {
JOB_ID_NAME("JOB_ID"),
COMMAND_ARRAY_NAME("COMMAND_ARRAY"),
STATUS("STATUS"),
EXIT_VALUE_NAME("EXIT_VALUE"),
STD_OUT_NAME("stdout"),
STD_ERR_NAME("stderr"),
INPUTSTREAM("INPUT_STREAM"),
ERRORSTREAM("ERROR_STREAM");
String fieldName;
ProcessTableFields(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldName() {
return fieldName;
}
}
public enum LonLatTableFields{
SLINE_FIELD_NAME("sline"),
ELINE_FIELD_NAME("eline"),
SPIXL_FIELD_NAME("spixl"),
EPIXL_FIELD_NAME("epixl");
String value;
LonLatTableFields(String value) {
this.value = value;
}
public String getValue(){
return value;
}
}
public SQLiteJDBC() {
}
public static void main(String args[]) {
createTables();
//System.out.println("Opened database successfully");
}
public static void createTables() {
if (new File(JOB_DB_FILENAME).exists()) {
new File(JOB_DB_FILENAME).delete();
}
Connection connection = null;
Statement stmt = null;
PreparedStatement preparedStatement = null;
try {
Class.forName(DB_CLASS_FOR_NAME);
connection = DriverManager.getConnection(JOB_DB_URL, username, password);
stmt = connection.createStatement();
//string for creating PROCESS_TABLE
String processor_table_sql = "CREATE TABLE IF NOT EXISTS PROCESS_TABLE " +
"(JOB_ID CHAR(50) PRIMARY KEY NOT NULL, " +
" COMMAND_ARRAY CHAR(500), " +
" EXIT_VALUE CHAR(2), " +
" STATUS CHAR(50), " +
" stdout CHAR(500), " +
" stderr CHAR(500), " +
" INPUT_STREAM BLOB , " +
" OUTPUT_STREAM BLOB )";
//string for creating FILE_TABLE
String file_table_sql = "CREATE TABLE IF NOT EXISTS FILE_TABLE ( " +
"JOB_ID CHAR(50) PRIMARY KEY NOT NULL, " +
" CLIENT_ID_NAME CHAR(100) , " +
" WORKING_DIR_PATH CHAR(100) , " +
" PROGRAM_NAME CHAR(25) , " +
" I_FILE_NAME CHAR(100) , " +
"I_FILE_TYPE CHAR(50) , " +
"O_FILE_NAME CHAR(100) , " +
"MISSION_NAME CHAR(50), " +
"MISSION_DIR CHAR(50) " +
")";
//string for creating NEXT_LEVELE_FILE_NAME_TABLE
String file_info_table_sql = "CREATE TABLE IF NOT EXISTS FILE_TABLE " +
"(JOB_ID CHAR(50) NOT NULL, " +
" CLIENT_ID_NAME CHAR(100) , " +
" WORKING_DIR_PATH CHAR(100) , " +
" PROGRAM_NAME CHAR(25) , " +
" I_FILE_NAME CHAR(100) NOT NULL , " +
" I_FILE_TYPE CHAR(50) , " +
" O_FILE_NAME CHAR(100) , " +
" MISSION_NAME CHAR(50), " +
" PRIMARY KEY(JOB_ID, I_FILE_NAME)" +
" );";
//string for creating LONLAT_2_PIXEL_TABLE
String lonlat_2_pixel_table_sql = "CREATE TABLE IF NOT EXISTS LONLAT_2_PIXEL_TABLE " +
"(JOB_ID CHAR(50) PRIMARY KEY NOT NULL, " +
"SPIXL CHAR(50) , " +
"EPIXL CHAR(100) , " +
"SLINE CHAR(50), " +
"ELINE CHAR(50), " +
"PIX_SUB CHAR(100), " +
"SC_SUB CHAR(50), " +
"PRODLIST CHAR(50) )";
String input_files_list_table_sql = "CREATE TABLE IF NOT EXISTS INPUT_FILES_LIST_TABLE " +
"(FILE_ID INTEGER NOT NULL , " +
"JOB_ID CHAR(50) NOT NULL, " +
"FILENAME STRING," +
"PRIMARY KEY (FILE_ID)," +
"FOREIGN KEY (JOB_ID) REFERENCES FILE_TABLE(JOB_ID)" +
" );";
//
// String lonlat_table_sql = "CREATE TABLE IF NOT EXISTS LONLAT2PIXEL_TABLE " +
// "(LONLAT_ID INTEGER NOT NULL , " +
// "JOB_ID CHAR(50) NOT NULL, " +
// "FILENAME STRING," +
// "PRIMARY KEY (FILE_ID)," +
// "FOREIGN KEY (JOB_ID) REFERENCES FILE_TABLE(JOB_ID)" +
// " );";
//execute create_table statements
stmt.executeUpdate(processor_table_sql);
stmt.executeUpdate(file_table_sql);
stmt.executeUpdate(file_info_table_sql);
stmt.executeUpdate(lonlat_2_pixel_table_sql);
stmt.executeUpdate(input_files_list_table_sql);
//string for creating MISSION_TABLE
String mission_table_sql = "CREATE TABLE IF NOT EXISTS MISSION_TABLE " +
"(MISSION_ID CHAR(50) PRIMARY KEY NOT NULL, " +
" MISSION_NAMES CHAR(50) NOT NULL, " +
" MISSION_DIR CHAR(50) NOT NULL)";
stmt.executeUpdate(mission_table_sql);
String insertMissionTableSQL = "INSERT INTO MISSION_TABLE " + " (MISSION_ID, MISSION_NAMES, MISSION_DIR) VALUES (" + "?, ?, ?)";
preparedStatement = connection.prepareStatement(insertMissionTableSQL);
//1. insert aquarius mission info
preparedStatement.setString(1, "AQUARIUS");
preparedStatement.setString(2, "AQUARIUS");
preparedStatement.setString(3, "aquarius");
preparedStatement.executeUpdate();
//2. insert czcs mission info
preparedStatement.setString(1, "CZCS");
preparedStatement.setString(2, "CZCS");
preparedStatement.setString(3, "czcs");
preparedStatement.executeUpdate();
//3. insert hico mission info
preparedStatement.setString(1, "HICO");
preparedStatement.setString(2, "HICO");
preparedStatement.setString(3, "hico");
preparedStatement.executeUpdate();
//4. insert goci mission info
preparedStatement.setString(1, "GOCI");
preparedStatement.setString(2, "GOCI");
preparedStatement.setString(3, "goci");
preparedStatement.executeUpdate();
//5. insert meris mission info
preparedStatement.setString(1, "MERIS");
preparedStatement.setString(2, "MERIS");
preparedStatement.setString(3, "meris");
preparedStatement.executeUpdate();
//6. insert modis aqua mission info
preparedStatement.setString(1, "MODISA");
preparedStatement.setString(2, "MODIS Aqua AQUA MODISA");
preparedStatement.setString(3, "modis/aqua");
preparedStatement.executeUpdate();
//7. insert modis terra mission info
preparedStatement.setString(1, "MODIST");
preparedStatement.setString(2, "MODIS Terra TERRA MODIST");
preparedStatement.setString(3, "modis/terra");
preparedStatement.executeUpdate();
//8. insert mos mission info
preparedStatement.setString(1, "MOS");
preparedStatement.setString(2, "MOS");
preparedStatement.setString(3, "mos");
preparedStatement.executeUpdate();
//9. insert msi mission info
preparedStatement.setString(1, "MSI");
preparedStatement.setString(2, "MSI");
preparedStatement.setString(3, "msi");
preparedStatement.executeUpdate();
//10. insert octs mission info
preparedStatement.setString(1, "OCTS");
preparedStatement.setString(2, "OCTS");
preparedStatement.setString(3, "octs");
preparedStatement.executeUpdate();
//11. insert osmi mission info
preparedStatement.setString(1, "OSMI");
preparedStatement.setString(2, "OSMI");
preparedStatement.setString(3, "osmi");
preparedStatement.executeUpdate();
//12. insert seawifs mission info
preparedStatement.setString(1, "SEAWIFS");
preparedStatement.setString(2, "SEAWIFS SeaWiFS");
preparedStatement.setString(3, "seawifs");
preparedStatement.executeUpdate();
//13. insert viirs mission info
preparedStatement.setString(1, "VIIRSN");
preparedStatement.setString(2, "VIIRS VIIRSN");
preparedStatement.setString(3, "viirs/npp");
preparedStatement.executeUpdate();
//14. insert ocm1 mission info
preparedStatement.setString(1, "OCM1");
preparedStatement.setString(2, "OCM1");
preparedStatement.setString(3, "ocm1");
preparedStatement.executeUpdate();
//15. insert ocm2 mission info
preparedStatement.setString(1, "OCM2");
preparedStatement.setString(2, "OCM2");
preparedStatement.setString(3, "ocm2");
preparedStatement.executeUpdate();
//16. insert oli mission info
preparedStatement.setString(1, "OLI");
preparedStatement.setString(2, "OLI");
preparedStatement.setString(3, "oli");
preparedStatement.executeUpdate();
//16. insert olci mission info
preparedStatement.setString(1, "OLCI");
preparedStatement.setString(2, "OLCI");
preparedStatement.setString(3, "olci");
preparedStatement.executeUpdate();
//17. insert viirs mission info
preparedStatement.setString(1, "VIIRSJ1");
preparedStatement.setString(2, "VIIRSJ1");
preparedStatement.setString(3, "viirs/j1");
preparedStatement.executeUpdate();
stmt.close();
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
//System.out.println("Tables created successfully");
}
public static String retrieveMissionDir(String missionName) {
Connection connection = null;
PreparedStatement preparedStatement = null;
Statement statement = null;
String commonQueryString = "SELECT * FROM MISSION_TABLE WHERE MISSION_ID = ?";
String missionDir = null;
try {
Class.forName(DB_CLASS_FOR_NAME);
connection = DriverManager.getConnection(JOB_DB_URL);
connection.setAutoCommit(false);
//System.out.println("Opened database successfully");
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM MISSION_TABLE;");
while (rs.next()) {
String missionNames = rs.getString("MISSION_NAMES");
System.out.println("MISSION NAMES = " + missionNames);
if (missionNames.contains(missionName)) {
missionDir = rs.getString("MISSION_DIR");
System.out.println("MISSION DIR = " + missionDir);
break;
}
}
rs.close();
statement.close();
connection.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return missionDir;
}
public static void insertItem(String tableName, String itemName, String itemValue) {
Connection connection = null;
PreparedStatement preparedStatement = null;
String commonInsertString = "INSERT INTO " + tableName + " (" + itemName + ") VALUES ( ? );";
try {
Class.forName(DB_CLASS_FOR_NAME);
connection = DriverManager.getConnection(JOB_DB_URL);
connection.setAutoCommit(false);
preparedStatement = connection.prepareStatement(commonInsertString);
preparedStatement.setString(1, itemValue);
// execute insert SQL stetement
int exitCode = preparedStatement.executeUpdate();
connection.commit();
//System.out.println(itemName + " is " + (exitCode == 1 ? "" : "not") + " inserted into " + tableName + " table!");
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.err.println(" in inserting item : " + e.getClass().getName() + ": " + e.getMessage());
//System.exit(0);
}
//System.out.println("Inserted " + itemName + " successfully");
}
public static String updateItem(String tableName, String jobID, String itemName, String itemValue) {
Connection connection = null;
PreparedStatement preparedStatement = null;
String commonUpdateString = "UPDATE " + tableName + " SET " + itemName + " = ? WHERE JOB_ID = ?";
String retrievedItem = null;
try {
Class.forName(DB_CLASS_FOR_NAME);
connection = DriverManager.getConnection(JOB_DB_URL);
connection.setAutoCommit(false);
//System.out.println("Operating on table " + tableName);
preparedStatement = connection.prepareStatement(commonUpdateString);
preparedStatement.setString(1, itemValue);
preparedStatement.setString(2, jobID);
int exitCode = preparedStatement.executeUpdate();
connection.commit();
//System.out.println(itemName + " is " + (exitCode == 1 ? "" : "not") + " updated on " + tableName + " table!");
//System.out.println(itemName + " = " + itemValue);
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.err.println(" in update item : " + e.getClass().getName() + ": " + e.getMessage());
//System.exit(0);
}
//System.out.println("Operation done successfully");
return retrievedItem;
}
public static void insertItemWithDoubleKey(String tableName, String key1, String value1, String key2, String value2) {
Connection connection = null;
PreparedStatement preparedStatement = null;
String commonInsertString = "INSERT INTO " + tableName + " (" + key1 + "," + key2 + ") VALUES ( ?, ? );";
try {
Class.forName(DB_CLASS_FOR_NAME);
connection = DriverManager.getConnection(JOB_DB_URL);
connection.setAutoCommit(false);
preparedStatement = connection.prepareStatement(commonInsertString);
preparedStatement.setString(1, value1);
preparedStatement.setString(2, value2);
// execute insert SQL stetement
int exitCode = preparedStatement.executeUpdate();
connection.commit();
//System.out.println(key1 + " is " + (exitCode == 1 ? "" : "not") + " inserted into " + tableName + " table!");
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.err.println(" in inserting item : " + e.getClass().getName() + ": " + e.getMessage());
//System.exit(0);
}
//System.out.println("Inserted " + key1 + "and " + key2 + " successfully");
}
public static String updateItemWithDoubleKey(String tableName, String key1, String keyValue1, String key2, String keyValue2, String itemName, String itemValue) {
Connection connection = null;
PreparedStatement preparedStatement = null;
String commonUpdateString = "UPDATE " + tableName + " SET " + itemName + " = ? WHERE " + key1 + " = ? AND " + key2 + "=?";
String retrievedItem = null;
try {
Class.forName(DB_CLASS_FOR_NAME);
connection = DriverManager.getConnection(JOB_DB_URL);
connection.setAutoCommit(false);
//System.out.println("Operating on table " + tableName);
preparedStatement = connection.prepareStatement(commonUpdateString);
preparedStatement.setString(1, itemValue);
preparedStatement.setString(2, keyValue1);
preparedStatement.setString(3, keyValue2);
int exitCode = preparedStatement.executeUpdate();
connection.commit();
//System.out.println(itemName + " is " + (exitCode == 1 ? "" : "not") + " updated on " + tableName + " table!");
//System.out.println(itemName + " = " + itemValue);
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.err.println(" in update item : " + e.getClass().getName() + ": " + e.getMessage());
//System.exit(0);
}
//System.out.println("Operation done successfully");
return retrievedItem;
}
public static ArrayList getInputFilesList(String jobId) {
Connection connection = null;
PreparedStatement preparedStatement = null;
String commonQueryString = "SELECT * FROM " + INPUT_FILES_LIST_TABLE_NAME + " WHERE JOB_ID = ?";
ArrayList fileList = new ArrayList();
try {
Class.forName(DB_CLASS_FOR_NAME);
connection = DriverManager.getConnection(JOB_DB_URL);
connection.setAutoCommit(false);
//System.out.println("Operating on table " + INPUT_FILES_LIST_TABLE_NAME + " jobID = " + jobId + " searching for " + "fileName");
preparedStatement = connection.prepareStatement(commonQueryString);
//preparedStatement.setString(1, itemName);
preparedStatement.setString(1, jobId);
//System.out.println("sql string: " + preparedStatement);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
fileList.add(rs.getString("FILENAME"));
}
rs.close();
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.err.println(" in retrieve item : " + e.getClass().getName() + ": " + e.getMessage());
//System.exit(0);
}
//System.out.println("Operation done successfully");
return fileList;
}
public static void updateInputFilesList(String jobID, String newClientFileName) {
Connection connection = null;
PreparedStatement preparedStatement = null;
String commonUpdateString = "INSERT INTO " + INPUT_FILES_LIST_TABLE_NAME + " ( JOB_ID, FILENAME ) VALUES ( ? , ? );";
//System.out.println(commonUpdateString);
try {
Class.forName(DB_CLASS_FOR_NAME);
connection = DriverManager.getConnection(JOB_DB_URL);
connection.setAutoCommit(false);
//System.out.println("Operating on table " + INPUT_FILES_LIST_TABLE_NAME);
preparedStatement = connection.prepareStatement(commonUpdateString);
preparedStatement.setString(1, jobID);
preparedStatement.setString(2, newClientFileName);
int exitCode = preparedStatement.executeUpdate();
connection.commit();
//System.out.println(newClientFileName + " is " + (exitCode == 1 ? "" : "not") + " added in " + INPUT_FILES_LIST_TABLE_NAME + " table!");
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.err.println(" in update item : " + e.getClass().getName() + ": " + e.getMessage());
//System.exit(0);
}
}
public static String retrieveItem(String tableName, String searchKey, String itemName) {
Connection connection = null;
PreparedStatement preparedStatement = null;
String commonQueryString = "SELECT * FROM " + tableName + " WHERE JOB_ID = ?";
String retrievedItem = null;
try {
Class.forName(DB_CLASS_FOR_NAME);
connection = DriverManager.getConnection(JOB_DB_URL);
connection.setAutoCommit(false);
//System.out.println("Operating on table " + tableName + " jobID = " + searchKey + " searching for " + itemName);
preparedStatement = connection.prepareStatement(commonQueryString);
preparedStatement.setString(1, searchKey);
ResultSet rs = preparedStatement.executeQuery();
retrievedItem = rs.getString(itemName);
//System.out.println("Retrieved item name : " + retrievedItem);
rs.close();
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.err.println(" in retrieve item : " + e.getClass().getName() + ": " + e.getMessage());
//System.exit(0);
}
//System.out.println("Operation done successfully");
return retrievedItem;
}
public static InputStream retrieveInputStreamItem(String tableName, String searchKey, String itemName) {
Connection connection = null;
PreparedStatement preparedStatement = null;
String commonQueryString = "SELECT * FROM " + tableName + " WHERE JOB_ID = ?";
InputStream retrievedItem = null;
try {
Class.forName(DB_CLASS_FOR_NAME);
connection = DriverManager.getConnection(JOB_DB_URL);
connection.setAutoCommit(false);
//System.out.println("Operating on table " + tableName + " jobID = " + searchKey + " searching for " + itemName);
preparedStatement = connection.prepareStatement(commonQueryString);
preparedStatement.setString(1, searchKey);
ResultSet rs = preparedStatement.executeQuery();
int size= 0;
if (rs != null)
{
rs.beforeFirst();
rs.last();
size = rs.getRow();
}
if (rs.next()) {
retrievedItem = rs.getBinaryStream(size);
//System.out.println("Total retrieved item number : " + rs.getFetchSize());
//rs.deleteRow();
} else {
retrievedItem = null;
}
//retrievedItem = rs.getBinaryStream(itemName);
//System.out.println("Retrieved item name : " + retrievedItem.toString());
rs.close();
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.err.println(" in retrieve input stream item : " );
e.printStackTrace();
}
//System.out.println("Operation done successfully");
return retrievedItem;
}
public static String getProgramName(String jobId) {
return retrieveItem(FILE_TABLE_NAME, jobId, FileTableFields.PROGRAM_NAME.getFieldName());
}
}
| 26,413 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ContourInterval.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/data/ContourInterval.java | package gov.nasa.gsfc.seadas.contour.data;
import java.awt.*;
import java.text.DecimalFormat;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 5/27/14
* Time: 6:17 PM
* To change this template use File | Settings | File Templates.
*/
public class ContourInterval {
String contourLevelName;
Double contourLevelValue;
String contourLineStyleValue;
private Color lineColor;
private double dashLength;
private double spaceLength;
private String filterName;
private boolean initial;
//DecimalFormat decimalFormatBig = new DecimalFormat("##.###");
DecimalFormat decimalFormatSmall = new DecimalFormat("##.#######");
private double ptsToPixelsMultiplier;
public ContourInterval(String contourBaseName, Double contourLevelValue, String filterName, double ptsToPixelsMultiplier, boolean userDefinedContourName) {
this.contourLevelValue = new Double(decimalFormatSmall.format(contourLevelValue));
// if (contourLevelValue > 1) {
// this.contourLevelValue = new Double(decimalFormatBig.format(contourLevelValue));
// } else {
// this.contourLevelValue = new Double(decimalFormatSmall.format(contourLevelValue));
// }
if (userDefinedContourName) {
contourLevelName = contourBaseName;
}else {
contourLevelName = contourBaseName + this.contourLevelValue + "_" + filterName;
}
lineColor = Color.BLACK;
contourLineStyleValue = "1.0, 0";
dashLength = 1.0;
spaceLength = 0;
this.filterName = filterName;
this.ptsToPixelsMultiplier = ptsToPixelsMultiplier;
}
public ContourInterval() {
}
public void setContourLevelName(String contourLevelName) {
this.contourLevelName = contourLevelName;
}
public String getContourLevelName() {
return contourLevelName;
}
public void setContourLevelValue(Double contourLevelValue) {
this.contourLevelValue = new Double(decimalFormatSmall.format(contourLevelValue));
// if (contourLevelValue > 1) {
// this.contourLevelValue = new Double(decimalFormatBig.format(contourLevelValue));
// } else {
// this.contourLevelValue = new Double(decimalFormatSmall.format(contourLevelValue));
// }
}
public double getContourLevelValue() {
return contourLevelValue;
}
public String getContourLineStyleValue() {
return contourLineStyleValue;
}
public void setContourLineStyleValue(String contourLineStyleValue) {
this.contourLineStyleValue = contourLineStyleValue;
}
public Color getLineColor() {
return lineColor;
}
public void setLineColor(Color lineColor) {
this.lineColor = lineColor;
}
@Override
public ContourInterval clone(){
ContourInterval contourInterval = new ContourInterval();
contourInterval.setPtsToPixelsMultiplier(this.getPtsToPixelsMultiplier());
contourInterval.setLineColor(new Color(this.getLineColor().getRed(),
this.getLineColor().getGreen(),
this.getLineColor().getBlue(),
this.getLineColor().getAlpha()));
contourInterval.setContourLevelName(this.getContourLevelName());
contourInterval.setContourLevelValue(this.getContourLevelValue());
contourInterval.setContourLineStyleValue(this.getContourLineStyleValue());
contourInterval.setDashLength(this.getDashLength());
contourInterval.setSpaceLength(this.getSpaceLength());
return contourInterval;
}
public boolean isInitial() {
return initial;
}
public void setInitial(boolean initial) {
this.initial = initial;
}
public double getDashLength() {
return dashLength;
}
public void setDashLength(double dashLength) {
this.dashLength = dashLength;
setContourLineStyleValue(new Double(this.dashLength * ptsToPixelsMultiplier).toString() + ", " + new Double(this.spaceLength * ptsToPixelsMultiplier).toString());
}
public double getSpaceLength() {
return spaceLength;
}
public void setSpaceLength(double spaceLength) {
this.spaceLength = spaceLength;
setContourLineStyleValue(new Double(this.dashLength * ptsToPixelsMultiplier).toString() + ", " + new Double(this.spaceLength * ptsToPixelsMultiplier).toString());
}
public String getFilterName() {
return filterName;
}
public void setFilterName(String filterName) {
this.filterName = filterName;
}
public double getPtsToPixelsMultiplier() {
return ptsToPixelsMultiplier;
}
public void setPtsToPixelsMultiplier(double ptsToPixelsMultiplier) {
this.ptsToPixelsMultiplier = ptsToPixelsMultiplier;
}
}
| 4,957 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ContourData.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/data/ContourData.java | package gov.nasa.gsfc.seadas.contour.data;
import org.esa.snap.core.datamodel.Band;
import javax.swing.event.SwingPropertyChangeSupport;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 9/5/13
* Time: 1:03 PM
* To change this template use File | Settings | File Templates.
*/
public class ContourData {
static final String NEW_BAND_SELECTED_PROPERTY = "newBandSelected";
static final String CONTOUR_LINES_BASE_NAME = "contour_";
static final String NEW_FILTER_SELECTED_PROPERTY = "newFilterSelected";
static final String DATA_CHANGED_PROPERTY = "dataChanged";
private ArrayList<ContourInterval> contourIntervals;
Band band;
int bandIndex;
String contourBaseName;
private Double startValue;
private Double endValue;
private int numOfLevels;
private boolean log;
private boolean filtered;
private boolean contourCustomized;
private String filterName;
private String oldFilterName;
private double ptsToPixelsMultiplier;
private boolean deleted;
private boolean contourInitialized;
private boolean contourValuesChanged;
private final SwingPropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this);
public ContourData() {
this(null, null, null, 1);
}
public ContourData(Band band, String unfiltereBandName, String filterName, double ptsToPixelsMultiplier) {
contourIntervals = new ArrayList<ContourInterval>();
contourBaseName = CONTOUR_LINES_BASE_NAME;
if (band != null) {
contourBaseName = contourBaseName + unfiltereBandName + "_";
}
startValue = Double.MIN_VALUE;
endValue = Double.MAX_VALUE;
this.band = band;
log = false;
filtered = true;
contourCustomized = false;
contourInitialized = true;
contourValuesChanged = false;
deleted = false;
this.filterName = filterName;
this.ptsToPixelsMultiplier = ptsToPixelsMultiplier;
propertyChangeSupport.addPropertyChangeListener(NEW_FILTER_SELECTED_PROPERTY, getFilterButtonPropertyListener());
propertyChangeSupport.addPropertyChangeListener(NEW_FILTER_SELECTED_PROPERTY, getFilterButtonPropertyListener());
}
private PropertyChangeListener getFilterButtonPropertyListener() {
return new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
updateContourNamesForNewFilter(oldFilterName, filterName);
}
};
}
public void reset() {
contourIntervals.clear();
}
public void createContourLevels() {
createContourLevels(startValue, endValue, numOfLevels, log);
}
/**
* @param startValue start value for the contour levels; i.e., first contour line falls on this level
* @param endValue end value for the contour lines.
* @param numberOfLevels This parameter decides how many levels between start and end values
* @param log This parameter decides the distribution between two levels
*/
public void createContourLevels(Double startValue, Double endValue, int numberOfLevels, boolean log) {
Double sv;
Double ev;
Double interval;
ArrayList<Color> colors = new ArrayList<Color>();
ArrayList<String> names = new ArrayList<>();
this.startValue = startValue;
this.endValue = endValue;
this.numOfLevels = numberOfLevels;
if (contourCustomized) {
colors = getColors();
names = getNames();
}
contourIntervals.clear();
/**
* In case start value and end values are the same, there will be only one level. The log value is ignored.
* If the numberofIntervals is one (1), the contour line will be based on the start value.
*/
if (startValue == endValue || Math.abs(startValue - endValue) < 0.00001 || numberOfLevels == 1) {
contourIntervals.add(new ContourInterval(contourBaseName, startValue, filterName, ptsToPixelsMultiplier, false));
//Only update names if the user edited the contour interval values
if (contourCustomized) {
updateColors(colors);
updateNames(names);
}
return;
}
/**
* Normal case.
*/
if (log) {
if (startValue == 0) startValue = Double.MIN_VALUE;
if (endValue == 0) endValue = Double.MIN_VALUE;
sv = Math.log10(startValue);
ev = Math.log10(endValue);
interval = (ev - sv) / (numberOfLevels - 1);
System.out.println("start value: " + sv + " end value: " + ev + " interval: " + interval);
for (int i = 0; i < numberOfLevels; i++) {
double contourValue = Math.pow(10, sv + interval * i);
contourIntervals.add(new ContourInterval(contourBaseName, contourValue, filterName, ptsToPixelsMultiplier, false));
}
} else {
interval = (endValue - startValue) / (numberOfLevels - 1);
System.out.println("start value: " + startValue + " end value: " + endValue + " interval: " + interval);
for (int i = 0; i < numberOfLevels; i++) {
double contourValue = startValue + interval * i;
contourIntervals.add(new ContourInterval(contourBaseName, contourValue, filterName, ptsToPixelsMultiplier, false));
}
}
if (contourCustomized) {
updateColors(colors);
updateNames(names);
}
}
private void updateContourIntervals() {
ArrayList<Color> colors = getColors();
ArrayList<String> names = getNames();
updateColors(colors);
updateNames(names);
}
private void updateColors(ArrayList<Color> colors) {
if (colors.size() > 0) {
int i = 0;
for (ContourInterval contourInverval : contourIntervals) {
if (colors.size() > i) {
contourInverval.setLineColor(colors.get(i++));
}
}
}
}
private void updateNames(ArrayList<String> names) {
if (names.size() > 0) {
int i = 0;
for (ContourInterval contourInverval : contourIntervals) {
if (names.size() > i) {
contourInverval.setContourLevelName(names.get(i++));
}
}
}
}
public void updateContourNamesForNewFilter(String oldFilterName, String newFilterName) {
for (ContourInterval contourInverval : contourIntervals) {
String newName = contourInverval.getContourLevelName().replace(oldFilterName, newFilterName);
contourInverval.setContourLevelName(newName);
}
}
public void setBand(Band band) {
String oldBandName = this.band.getName();
this.band = band;
//contourBaseName = CONTOUR_LINES_BASE_NAME + band.getName() + "_";
propertyChangeSupport.firePropertyChange(NEW_BAND_SELECTED_PROPERTY, oldBandName, band.getName());
}
public Band getBand() {
return band;
}
public void setBandIndex(int bandIndex) {
this.bandIndex = bandIndex;
}
public int getBandIndex() {
return bandIndex;
}
public ArrayList<ContourInterval> getLevels() {
// for (double level = 1; level < 10; level += 2) {
// contourIntervals.add(level);
// }
return contourIntervals;
}
public ArrayList<ContourInterval> getContourIntervals() {
return contourIntervals;
}
public void setContourIntervals(ArrayList<ContourInterval> contourIntervals) {
this.contourIntervals = contourIntervals;
}
public Double getStartValue() {
return startValue;
}
public void setStartValue(Double startValue) {
this.startValue = startValue;
}
public Double getEndValue() {
return endValue;
}
public void setEndValue(Double endValue) {
this.endValue = endValue;
}
public void setStartEndValues(Double startValue, Double endValue) {
this.startValue = startValue;
this.endValue = endValue;
propertyChangeSupport.firePropertyChange(DATA_CHANGED_PROPERTY, startValue, endValue);
}
public int getNumOfLevels() {
return numOfLevels;
}
public void setNumOfLevels(int numOfLevels) {
this.numOfLevels = numOfLevels;
}
public ArrayList<Color> getColors() {
ArrayList<Color> colors = new ArrayList<Color>();
for (ContourInterval interval : contourIntervals) {
colors.add(interval.getLineColor());
}
return colors;
}
public ArrayList<String> getNames() {
ArrayList<String> names = new ArrayList<String>();
for (ContourInterval interval : contourIntervals) {
names.add(interval.getContourLevelName());
}
return names;
}
public ArrayList<ContourInterval> cloneContourIntervals() {
ArrayList<ContourInterval> clone = new ArrayList<ContourInterval>(contourIntervals.size());
for (ContourInterval interval : contourIntervals) {
clone.add(interval.clone());
}
return clone;
}
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() {
PropertyChangeListener[] pr = propertyChangeSupport.getPropertyChangeListeners();
for (int i = 0; i < pr.length; i++) {
this.propertyChangeSupport.removePropertyChangeListener(pr[i]);
}
}
public boolean isLog() {
return log;
}
public void setLog(boolean log) {
this.log = log;
}
public boolean isFiltered() {
return filtered;
}
public void setFiltered(boolean filtered) {
this.filtered = filtered;
}
public boolean isContourCustomized() {
return contourCustomized;
}
public void setContourCustomized(boolean contourCustomized) {
this.contourCustomized = contourCustomized;
}
public String getFilterName() {
return filterName;
}
public void setFilterName(String filterName) {
oldFilterName = this.filterName;
this.filterName = filterName;
updateContourNamesForNewFilter(oldFilterName, filterName);
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public boolean isContourValuesChanged() {
return contourValuesChanged;
}
public void setContourValuesChanged(boolean contourValuesChanged) {
this.contourValuesChanged = contourValuesChanged;
}
}
| 11,783 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ShowVectorContourOverlayAction.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/action/ShowVectorContourOverlayAction.java | package gov.nasa.gsfc.seadas.contour.action;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.PrecisionModel;
import org.locationtech.jts.geom.GeometryFactory;
import gov.nasa.gsfc.seadas.contour.data.ContourData;
import gov.nasa.gsfc.seadas.contour.data.ContourInterval;
import gov.nasa.gsfc.seadas.contour.operator.Contour1Spi;
import gov.nasa.gsfc.seadas.contour.operator.ContourDescriptor;
import gov.nasa.gsfc.seadas.contour.ui.ContourDialog;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.util.FeatureUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.product.ProductSceneView;
import org.geotools.data.collection.ListFeatureCollection;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.GeometryCoordinateSequenceTransformer;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.*;
import org.openide.util.actions.Presenter;
import javax.media.jai.JAI;
import javax.media.jai.OperationRegistry;
import javax.media.jai.ParameterBlockJAI;
import javax.media.jai.RenderedOp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author Aynur Abdurazik
*/
@ActionID(category = "View", id = "OverlayContourLayerAction")
@ActionRegistration(displayName = "#CTL_OverlayContourLayerActionName")
@ActionReferences({
@ActionReference(path = "Menu/SeaDAS-Toolbox/General Tools", position = 100),
@ActionReference(path = "Menu/Layer"),
@ActionReference(path = "Toolbars/SeaDAS Toolbox", position = 100)
})
@NbBundle.Messages({
"CTL_OverlayContourLayerActionName=Contour Overlay",
"CTL_OverlayContourLayerActionToolTip=Show/hide Contour overlay for the selected image"
})
public class ShowVectorContourOverlayAction extends AbstractSnapAction implements LookupListener, Presenter.Menu, Presenter.Toolbar {
final String DEFAULT_STYLE_FORMAT = "fill:%s; fill-opacity:0.5; stroke:%s; stroke-opacity:1.0; stroke-width:1.0; stroke-dasharray:%s; symbol:cross";
Product product;
double noDataValue;
private GeoCoding geoCoding;
// private boolean enabled = false;
public static final String SMALLICON = "gov/nasa/gsfc/seadas/contour/ui/icons/ContourOverlay.png";
public static final String LARGEICON = "gov/nasa/gsfc/seadas/contour/ui/icons/ContourOverlay24.png";
private final Lookup lookup;
private final Lookup.Result<ProductSceneView> viewResult;
// public ShowVectorContourOverlayAction() {
// this(Utilities.actionsGlobalContext());
// }
public ShowVectorContourOverlayAction() {
this(null);
}
public ShowVectorContourOverlayAction(Lookup lookup) {
putValue(ACTION_COMMAND_KEY, getClass().getName());
putValue(SELECTED_KEY, false);
putValue(NAME, Bundle.CTL_OverlayContourLayerActionName());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon(SMALLICON, false));
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon(LARGEICON, false));
putValue(SHORT_DESCRIPTION, Bundle.CTL_OverlayContourLayerActionToolTip());
this.lookup = lookup != null ? lookup : Utilities.actionsGlobalContext();
this.viewResult = this.lookup.lookupResult(ProductSceneView.class);
this.viewResult.addLookupListener(WeakListeners.create(LookupListener.class, this, viewResult));
updateEnabledState();
}
// @Override
// public Action createContextAwareInstance(Lookup actionContext) {
// return new ShowVectorContourOverlayAction(actionContext);
// }
// @Override
// protected void initActionProperties() {
// putValue(NAME, Bundle.CTL_OverlayContourLayerActionName());
// putValue(SMALL_ICON, ImageUtilities.loadImageIcon("gov/nasa/gsfc/seadas/contour/ui/icons/ContourOverlay22.png", false));
// putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon("gov/nasa/gsfc/seadas/contour/ui/icons/ContourOverlay24.gif", false));
// putValue(SHORT_DESCRIPTION, Bundle.CTL_OverlayContourLayerActionToolTip());
// }
//
@Override
public void actionPerformed(ActionEvent event) {
SnapApp snapApp = SnapApp.getDefault();
AppContext appContext = snapApp.getAppContext();
final ProductSceneView sceneView = snapApp.getSelectedProductSceneView();
product = snapApp.getSelectedProduct(SnapApp.SelectionSourceHint.VIEW);
ProductNodeGroup<Band> products = product.getBandGroup();
ContourDialog contourDialog = new ContourDialog(product, getActiveBands(products));
contourDialog.setVisible(true);
contourDialog.dispose();
if (contourDialog.getFilteredBandName() != null) {
if (product.getBand(contourDialog.getFilteredBandName()) != null)
product.getBandGroup().remove(product.getBand(contourDialog.getFilteredBandName()));
}
if (contourDialog.isContourCanceled()) {
return;
}
setGeoCoding(product.getSceneGeoCoding());
ContourData contourData = contourDialog.getContourData();
noDataValue = contourDialog.getNoDataValue();
try {
ArrayList<VectorDataNode> vectorDataNodes = createVectorDataNodesforContours(contourData);
for (VectorDataNode vectorDataNode : vectorDataNodes) {
// remove the old vector data node with the same name.
if (product.getVectorDataGroup().contains(vectorDataNode.getName())) {
product.getVectorDataGroup().remove(product.getVectorDataGroup().get(vectorDataNode.getName()));
}
product.getVectorDataGroup().add(vectorDataNode);
if (sceneView != null) {
sceneView.setLayersVisible(vectorDataNode);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private ArrayList<String> getActiveBands(ProductNodeGroup<Band> products) {
Band[] bands = new Band[products.getNodeCount()];
ArrayList<Band> activeBands = new ArrayList<>();
ArrayList<String> activeBandNames = new ArrayList<>();
products.toArray(bands);
for (Band band : bands) {
if (band.getImageInfo() != null) {
activeBands.add(band);
activeBandNames.add(band.getName());
}
}
return activeBandNames;
}
public ArrayList<VectorDataNode> createVectorDataNodesforContours(ContourData contourData) {
double scalingFactor = contourData.getBand().getScalingFactor();
double scalingOffset = contourData.getBand().getScalingOffset();
ArrayList<ContourInterval> contourIntervals = contourData.getLevels();
ArrayList<VectorDataNode> vectorDataNodes = new ArrayList<VectorDataNode>();
//Register "Contour" operator if it's not in the registry
OperationRegistry registry = JAI.getDefaultInstance().getOperationRegistry();
String modeName = "rendered";
boolean contourIsRegistered = false;
for (String name : registry.getDescriptorNames(modeName)) {
if (name.contains("Contour")) {
contourIsRegistered = true;
}
}
if (!contourIsRegistered) {
new Contour1Spi().updateRegistry(registry);
}
ParameterBlockJAI pb = new ParameterBlockJAI("Contour");
pb.setSource("source0", contourData.getBand().getSourceImage());
ArrayList<Double> noDataList = new ArrayList<>();
noDataList.add(noDataValue);
pb.setParameter("nodata", noDataList);
for (ContourInterval interval : contourIntervals) {
ArrayList<Double> contourInterval = new ArrayList<Double>();
String vectorName = interval.getContourLevelName();
if (contourData.isFiltered()) {
vectorName = vectorName + "_filtered";
}
double contourValue = (interval.getContourLevelValue() - scalingOffset) / scalingFactor;
contourInterval.add(contourValue);
pb.setParameter("levels", contourInterval);
FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = null;
try {
featureCollection = createContourFeatureCollection(pb);
} catch (Exception e) {
e.printStackTrace();
if (contourData.getLevels().size() != 0)
System.out.println(e.getMessage());
if (SnapApp.getDefault() != null) {
Dialogs.showError("failed to create contour lines");
}
continue;
}
if (featureCollection.isEmpty()) {
if (SnapApp.getDefault() != null) {
Dialogs.showError("Contour Lines", "No records found for ." + contourData.getBand().getName() + " at " + (contourValue * scalingFactor + scalingOffset));
}
continue;
}
final PlacemarkDescriptor placemarkDescriptor = PlacemarkDescriptorRegistry.getInstance().getPlacemarkDescriptor(featureCollection.getSchema());
placemarkDescriptor.setUserDataOf(featureCollection.getSchema());
VectorDataNode vectorDataNode = new VectorDataNode(vectorName, featureCollection, placemarkDescriptor);
//convert RGB color to an hexadecimal value
//String hex = "#"+Integer.toHexString(interval.getLineColor().getRGB()).substring(2);
String hex = String.format("#%02x%02x%02x", interval.getLineColor().getRed(), interval.getLineColor().getGreen(), interval.getLineColor().getBlue());
vectorDataNode.setDefaultStyleCss(String.format(DEFAULT_STYLE_FORMAT, hex, hex, interval.getContourLineStyleValue()));
vectorDataNodes.add(vectorDataNode);
}
return vectorDataNodes;
}
private FeatureCollection<SimpleFeatureType, SimpleFeature> createContourFeatureCollection(ParameterBlockJAI pb) {
RenderedOp dest = JAI.create("Contour", pb);
Collection<LineString > contours = (Collection<LineString >) dest.getProperty(ContourDescriptor.CONTOUR_PROPERTY_NAME);
SimpleFeatureType featureType = null;
FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = null;
try {
featureType = createFeatureType(geoCoding);
featureCollection = new ListFeatureCollection(featureType);
} catch (IOException ioe) {
ioe.printStackTrace();
}
LineString lineString;
Coordinate[] geomCoordinates;
PrecisionModel geomPrecisionModel;
PrecisionModel precisionModel;
for (LineString geomLineString : contours) {
geomCoordinates = geomLineString.getCoordinates();
geomPrecisionModel = geomLineString.getPrecisionModel();
precisionModel = new PrecisionModel(geomPrecisionModel.getScale(), geomPrecisionModel.getOffsetX(), geomPrecisionModel.getOffsetY());
lineString = new LineString(transformaCoordinates(geomCoordinates), precisionModel, geomLineString.getSRID());
Coordinate[] coordinates = lineString.getCoordinates();
for (int i = 0; i < coordinates.length; i++) {
coordinates[i].x = coordinates[i].x + 0.5;
coordinates[i].y = coordinates[i].y + 0.5;
}
final SimpleFeature feature = createFeature(featureType, lineString);
if (feature != null) {
((ListFeatureCollection) featureCollection).add(feature);
}
}
final CoordinateReferenceSystem mapCRS = geoCoding.getMapCRS();
//System.out.println("geo coding : " + geoCoding.getImageCRS().toString());
if (!mapCRS.equals(DefaultGeographicCRS.WGS84) || (geoCoding instanceof CrsGeoCoding)) {
try {
transformFeatureCollection(featureCollection, geoCoding.getImageCRS(), mapCRS);
} catch (TransformException e) {
Dialogs.showError("transformation failed!");
}
}
return featureCollection;
}
private Coordinate[] transformaCoordinates(Coordinate[] geomCoordinates){
Coordinate[] coordinates = new Coordinate[geomCoordinates.length];
int i = 0;
for (Coordinate coordinate:geomCoordinates) {
coordinates[i++] = new Coordinate(coordinate.x, coordinate.y, coordinate.z);
}
return coordinates;
}
private static void transformFeatureCollection(FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection, CoordinateReferenceSystem sourceCRS, CoordinateReferenceSystem targetCRS) throws TransformException {
final GeometryCoordinateSequenceTransformer transform = FeatureUtils.getTransform(sourceCRS, targetCRS);
final FeatureIterator<SimpleFeature> features = featureCollection.features();
final GeometryFactory geometryFactory = new GeometryFactory();
while (features.hasNext()) {
final SimpleFeature simpleFeature = features.next();
//System.out.println("simple feature : " + simpleFeature.toString());
final LineString sourceLine = (LineString) simpleFeature.getDefaultGeometry();
final LineString targetLine = transform.transformLineString((LineString) sourceLine, geometryFactory);
simpleFeature.setDefaultGeometry(targetLine);
}
}
private SimpleFeatureType createFeatureType(GeoCoding geoCoding) throws IOException {
SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder();
ftb.setName("gov.nasa.gsfc.contour.contourVectorData");
ftb.add("contour_lines", LineString.class, geoCoding.getImageCRS());
ftb.setDefaultGeometry("contour_lines");
final SimpleFeatureType ft = ftb.buildFeatureType();
ft.getUserData().put("contourVectorData", "true");
return ft;
}
private static SimpleFeature createFeature(SimpleFeatureType type, LineString lineString) {
SimpleFeatureBuilder fb = new SimpleFeatureBuilder(type);
/*0*/
fb.add(lineString);
return fb.buildFeature(null);
}
public GeoCoding getGeoCoding() {
return geoCoding;
}
public void setGeoCoding(GeoCoding geoCoding) {
this.geoCoding = geoCoding;
}
@Override
public JMenuItem getMenuPresenter() {
JMenuItem menuItem = new JMenuItem(this);
menuItem.setIcon(null);
return menuItem;
}
@Override
public Component getToolbarPresenter() {
JButton button = new JButton(this);
button.setText(null);
button.setIcon(ImageUtilities.loadImageIcon(LARGEICON,false));
return button;
}
@Override
public void resultChanged(LookupEvent ignored) {
updateEnabledState();
}
protected void updateEnabledState() {
final Product selectedProduct = SnapApp.getDefault().getSelectedProduct(SnapApp.SelectionSourceHint.AUTO);
boolean productSelected = selectedProduct != null;
boolean hasBands = false;
boolean hasGeoCoding = false;
if (productSelected) {
hasBands = selectedProduct.getNumBands() > 0;
hasGeoCoding = selectedProduct.getSceneGeoCoding() != null;
}
super.setEnabled(!viewResult.allInstances().isEmpty() && hasBands && hasGeoCoding);
}
}
| 16,326 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ContourIntervalDialog.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/ui/ContourIntervalDialog.java | package gov.nasa.gsfc.seadas.contour.ui;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.Binding;
import com.bc.ceres.swing.binding.BindingContext;
import gov.nasa.gsfc.seadas.contour.data.ContourData;
import gov.nasa.gsfc.seadas.contour.data.ContourInterval;
import gov.nasa.gsfc.seadas.contour.util.CommonUtilities;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.ui.color.ColorComboBox;
import org.esa.snap.ui.color.ColorComboBoxAdapter;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 6/4/14
* Time: 3:18 PM
* To change this template use File | Settings | File Templates.
*/
public class ContourIntervalDialog extends JDialog {
private static final String DELETE_BUTTON_IMAGE_FILE_NAME = "delete_button.png";
static final String CONTOUR_DATA_CHANGED_PROPERTY = "contourDataChanged";
private Double minValue;
private Double maxValue;
int numberOfLevels;
//UI components
JTextField minValueField, maxValueField, numLevelsField;
JCheckBox logCheckBox;
ContourData contourData;
ContourIntervalDialog(Band selectedBand, String unfilteredBandName, String filterName, double ptsToPixelsMultiplier) {
contourData = new ContourData(selectedBand, unfilteredBandName, filterName, ptsToPixelsMultiplier);
numberOfLevels = 1;
contourData.setNumOfLevels(numberOfLevels);
contourData.addPropertyChangeListener(ContourDialog.NEW_BAND_SELECTED_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
setBand(contourData.getBand());
propertyChangeSupport.firePropertyChange(CONTOUR_DATA_CHANGED_PROPERTY, true, false);
}
});
propertyChangeSupport.addPropertyChangeListener(CONTOUR_DATA_CHANGED_PROPERTY, getDataChangedPropertyListener());
setMaxValue(new Double(CommonUtilities.round(selectedBand.getStx().getMaximum(), 7)));
setMinValue(new Double(CommonUtilities.round(selectedBand.getStx().getMinimum(), 7)));
contourData.createContourLevels();
}
SwingPropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this);
public void setBand(Band newBand) {
numberOfLevels = 1;
numLevelsField.setText("1");
setMaxValue(new Double(CommonUtilities.round(newBand.getStx().getMaximum(), 7)));
setMinValue(new Double(CommonUtilities.round(newBand.getStx().getMinimum(), 7)));
minValueField.setText(new Double(getMinValue()).toString());
maxValueField.setText(new Double(getMaxValue()).toString());
contourData.setBand(newBand);
}
private PropertyChangeListener getDataChangedPropertyListener() {
return new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
contourData.createContourLevels();
}
};
}
protected JPanel getBasicPanel() {
final int rightInset = 5;
final JPanel contourPanel = new JPanel(new GridBagLayout());
contourPanel.setBorder(BorderFactory.createTitledBorder(""));
//final DecimalFormat decimalFormatBig = new DecimalFormat("##.###");
final DecimalFormat decimalFormatSmall = new DecimalFormat("##.#######");
minValueField = new JFormattedTextField(decimalFormatSmall);
// if (getMinValue() > 1) {
// minValueField = new JFormattedTextField(decimalFormatBig);
// } else {
// minValueField = new JFormattedTextField(decimalFormatSmall);
// }
minValueField.setColumns(10);
JLabel minValueLabel = new JLabel("Start Value:");
maxValueField = new JFormattedTextField(decimalFormatSmall);
// if (getMaxValue() > 1 ) {
// maxValueField = new JFormattedTextField(decimalFormatBig);
// } else {
// maxValueField = new JFormattedTextField(decimalFormatSmall);
// }
maxValueField.setColumns(10);
JLabel maxValueLabel = new JLabel("End Value:");
numLevelsField = new JFormattedTextField(new DecimalFormat("##"));
numLevelsField.setColumns(2);
PropertyContainer propertyContainer = new PropertyContainer();
propertyContainer.addProperty(Property.create("minValueField", minValue));
propertyContainer.addProperty(Property.create("maxValueField", maxValue));
propertyContainer.addProperty(Property.create("numLevelsField", numberOfLevels));
final BindingContext bindingContext = new BindingContext(propertyContainer);
final PropertyChangeListener pcl_min = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
Double originalMinValue = minValue;
minValue = (Double) bindingContext.getBinding("minValueField").getPropertyValue();
if (minValue == null) {
if (maxValue != null) {
minValue = maxValue;
} else {
minValue = originalMinValue;
}
}
contourData.setStartValue(minValue);
contourData.setContourValuesChanged(true);
contourData.setLog(logCheckBox.isSelected() && minValue > 0 && maxValue > 0);
propertyChangeSupport.firePropertyChange(CONTOUR_DATA_CHANGED_PROPERTY, true, false);
logCheckBox.setSelected(logCheckBox.isSelected() && minValue > 0 && maxValue > 0);
}
};
final PropertyChangeListener pcl_max = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
Double originalMaxValue = maxValue;
maxValue = (Double) bindingContext.getBinding("maxValueField").getPropertyValue();
if (maxValue == null) {
if (minValue != null) {
maxValue = minValue;
} else {
maxValue = originalMaxValue;
}
}
contourData.setEndValue(maxValue);
contourData.setContourValuesChanged(true);
contourData.setLog(logCheckBox.isSelected() && minValue > 0 && maxValue > 0);
propertyChangeSupport.firePropertyChange(CONTOUR_DATA_CHANGED_PROPERTY, true, false);
logCheckBox.setSelected(logCheckBox.isSelected() && minValue > 0 && maxValue > 0);
}
};
final PropertyChangeListener pcl_num = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
numberOfLevels = (Integer) bindingContext.getBinding("numLevelsField").getPropertyValue();
contourData.setNumOfLevels(numberOfLevels);
contourData.setContourValuesChanged(true);
propertyChangeSupport.firePropertyChange(CONTOUR_DATA_CHANGED_PROPERTY, true, false);
}
};
JLabel numLevelsLabel = new JLabel("# of Levels:");
Binding minValueBinding = bindingContext.bind("minValueField", minValueField);
minValueBinding.addComponent(minValueLabel);
bindingContext.addPropertyChangeListener("minValueField", pcl_min);
Binding maxValueBinding = bindingContext.bind("maxValueField", maxValueField);
maxValueBinding.addComponent(maxValueLabel);
bindingContext.addPropertyChangeListener("maxValueField", pcl_max);
Binding numLevelsBinding = bindingContext.bind("numLevelsField", numLevelsField);
numLevelsBinding.addComponent(numLevelsLabel);
bindingContext.addPropertyChangeListener("numLevelsField", pcl_num);
logCheckBox = new JCheckBox();
logCheckBox.setName("log checkbox");
logCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
// if (getNumberOfLevels() == contourData.getNumOfLevels()) {
// contourData.setKeepColors(true);
// } else {
// contourData.setKeepColors(false);
// }
contourData.setLog(logCheckBox.isSelected() && minValue > 0 && maxValue > 0);
propertyChangeSupport.firePropertyChange(CONTOUR_DATA_CHANGED_PROPERTY, true, false);
//contourData.createContourLevels(getMinValue(), getMaxValue(), getNumberOfLevels(), logCheckBox.isSelected());
logCheckBox.setSelected(logCheckBox.isSelected() && minValue > 0 && maxValue > 0);
}
});
JLabel filler = new JLabel(" ");
contourPanel.add(minValueLabel,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
contourPanel.add(minValueField,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
contourPanel.add(filler,
new ExGridBagConstraints(2, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
contourPanel.add(maxValueLabel,
new ExGridBagConstraints(3, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
contourPanel.add(maxValueField,
new ExGridBagConstraints(4, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
contourPanel.add(filler,
new ExGridBagConstraints(5, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
contourPanel.add(numLevelsLabel,
new ExGridBagConstraints(6, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
contourPanel.add(numLevelsField,
new ExGridBagConstraints(7, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
contourPanel.add(filler,
new ExGridBagConstraints(8, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
contourPanel.add(new JLabel("Log"),
new ExGridBagConstraints(9, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
contourPanel.add(logCheckBox,
new ExGridBagConstraints(10, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
JButton customize = new JButton("Preview/Edit");
customize.setPreferredSize(customize.getPreferredSize());
customize.setMinimumSize(customize.getPreferredSize());
customize.setMaximumSize(customize.getPreferredSize());
customize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (contourData.getLevels().size() == 0 ||
minValue != contourData.getStartValue() ||
maxValue != contourData.getEndValue() ||
numberOfLevels != contourData.getNumOfLevels()) {
System.out.print("---change!---");
contourData.createContourLevels(getMinValue(), getMaxValue(), getNumberOfLevels(), logCheckBox.isSelected());
}
//System.out.print("--- no change!---");
customizeContourLevels(contourData);
// disable min, max, level, log fields of a single contour panel
if (contourData.isContourCustomized()) {
contourPanel.getComponent(0).setEnabled(false);
contourPanel.getComponent(1).setEnabled(false);
contourPanel.getComponent(2).setEnabled(false);
contourPanel.getComponent(3).setEnabled(false);
contourPanel.getComponent(4).setEnabled(false);
contourPanel.getComponent(5).setEnabled(false);
contourPanel.getComponent(6).setEnabled(false);
contourPanel.getComponent(7).setEnabled(false);
}
}
});
contourPanel.add(filler,
new ExGridBagConstraints(11, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
contourPanel.add(customize,
new ExGridBagConstraints(12, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
contourPanel.add(filler,
new ExGridBagConstraints(13, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
JButton deleteButton = new JButton();
ImageIcon imageIcon = new ImageIcon();
java.net.URL imgURL = getClass().getResource(DELETE_BUTTON_IMAGE_FILE_NAME);
if (imgURL != null) {
imageIcon = new ImageIcon(imgURL, "Delete current row");
} else {
System.err.println("Couldn't find file: " + DELETE_BUTTON_IMAGE_FILE_NAME);
}
deleteButton.setIcon(imageIcon);
deleteButton.setToolTipText("Delete current row");
deleteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
contourPanel.removeAll();
contourPanel.validate();
contourPanel.repaint();
contourData.setDeleted(true);
propertyChangeSupport.firePropertyChange("deleteButtonPressed", true, false);
//propertyChangeSupport.firePropertyChange("deleteButtonPressed", true, false);
}
});
contourPanel.add(deleteButton,
new ExGridBagConstraints(14, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
return contourPanel;
}
protected void setMinValue(Double minValue) {
this.minValue = minValue;
contourData.setStartValue(minValue);
}
private Double getMinValue() {
return minValue;
}
protected void setMaxValue(Double maxValue) {
this.maxValue = maxValue;
contourData.setEndValue(maxValue);
}
private Double getMaxValue() {
return maxValue;
}
private void setNumberOfLevels(int numberOfLevels) {
this.numberOfLevels = numberOfLevels;
contourData.setNumOfLevels(numberOfLevels);
}
private int getNumberOfLevels() {
return numberOfLevels;
}
private void customizeContourLevels(ContourData contourData) {
final String contourNamePropertyName = "contourName";
final String contourValuePropertyName = "contourValue";
final String contourColorPropertyName = "contourColor";
final String contourLineStylePropertyName = "contourLineStyle";
final String contourLineDashLengthPropertyName = "contourLineDashLength";
final String contourLineSpaceLengthPropertyName = "contourLineSpaceLength";
ArrayList<ContourInterval> contourIntervalsClone = contourData.cloneContourIntervals();
JPanel customPanel = new JPanel();
customPanel.setLayout(new BoxLayout(customPanel, BoxLayout.Y_AXIS));
for (final ContourInterval interval : contourIntervalsClone) {
JPanel contourLevelPanel = new JPanel(new TableLayout(12));
JLabel contourNameLabel = new JLabel("Name: ");
JLabel contourValueLabel = new JLabel("Value: ");
JLabel contourColorLabel = new JLabel("Color: ");
JLabel contourLineStyleLabel = new JLabel("Line Style: ");
JLabel contourLineDashLengthLabel = new JLabel("Line Dash Length: ");
JLabel contourLineSpaceLengthLabel = new JLabel("Line Space Length: ");
JPanel contourLineStylePanel = new JPanel();
contourLineStylePanel.setLayout(new TableLayout(2));
JTextField contourLevelName = new JTextField();
contourLevelName.setColumns(25);
contourLevelName.setText(interval.getContourLevelName());
JTextField contourLevelValue = new JTextField();
contourLevelValue.setColumns(10);
contourLevelValue.setText(new Double(interval.getContourLevelValue()).toString());
JTextField contourLineStyleValue = new JTextField();
contourLineStyleValue.setColumns(10);
contourLineStyleValue.setText(interval.getContourLineStyleValue());
contourLineStyleValue.setToolTipText("Enter two numeric values. First number defines the dash length, the second number defines the space the length for dashed lines.");
JTextField dashLengthValue = new JTextField();
dashLengthValue.setColumns(4);
dashLengthValue.setText(new Double(interval.getDashLength()).toString());
dashLengthValue.setToolTipText("Enter a value greater than 0.");
JTextField spaceLengthValue = new JTextField();
spaceLengthValue.setColumns(4);
spaceLengthValue.setText(new Double(interval.getSpaceLength()).toString());
spaceLengthValue.setToolTipText("Enter 0 for solid lines. Enter a value greater than 0 for dashed lines.");
PropertyContainer propertyContainer = new PropertyContainer();
propertyContainer.addProperty(Property.create(contourNamePropertyName, interval.getContourLevelName()));
propertyContainer.addProperty(Property.create(contourValuePropertyName, interval.getContourLevelValue()));
propertyContainer.addProperty(Property.create(contourColorPropertyName, interval.getLineColor()));
propertyContainer.addProperty(Property.create(contourLineStylePropertyName, interval.getContourLineStyleValue()));
propertyContainer.addProperty(Property.create(contourLineDashLengthPropertyName, interval.getDashLength()));
propertyContainer.addProperty(Property.create(contourLineSpaceLengthPropertyName, interval.getSpaceLength()));
final BindingContext bindingContext = new BindingContext(propertyContainer);
final PropertyChangeListener pcl_name = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
interval.setContourLevelName((String) bindingContext.getBinding(contourNamePropertyName).getPropertyValue());
}
};
final PropertyChangeListener pcl_value = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
interval.setContourLevelValue((Double) bindingContext.getBinding(contourValuePropertyName).getPropertyValue());
}
};
final PropertyChangeListener pcl_color = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
interval.setLineColor((Color) bindingContext.getBinding(contourColorPropertyName).getPropertyValue());
}
};
final PropertyChangeListener pcl_lineStyle = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
interval.setContourLineStyleValue((String) bindingContext.getBinding(contourLineStylePropertyName).getPropertyValue());
}
};
final PropertyChangeListener pcl_lineDashLength = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
interval.setDashLength((Double) bindingContext.getBinding(contourLineDashLengthPropertyName).getPropertyValue());
}
};
final PropertyChangeListener pcl_lineSpaceLength = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
interval.setSpaceLength((Double) bindingContext.getBinding(contourLineSpaceLengthPropertyName).getPropertyValue());
}
};
ColorComboBox contourLineColorComboBox = new ColorComboBox();
// contourLineColorComboBox.setColorValueVisible(false);
// contourLineColorComboBox.setAllowDefaultColor(true);
contourLineColorComboBox.setSelectedColor(interval.getLineColor());
Binding contourLineColorBinding = bindingContext.bind(contourColorPropertyName, new ColorComboBoxAdapter(contourLineColorComboBox));
contourLineColorBinding.addComponent(contourColorLabel);
bindingContext.addPropertyChangeListener(contourColorPropertyName, pcl_color);
Binding contourNameBinding = bindingContext.bind(contourNamePropertyName, contourLevelName);
contourNameBinding.addComponent(contourNameLabel);
bindingContext.addPropertyChangeListener(contourNamePropertyName, pcl_name);
Binding contourValueBinding = bindingContext.bind(contourValuePropertyName, contourLevelValue);
contourValueBinding.addComponent(contourValueLabel);
bindingContext.addPropertyChangeListener(contourValuePropertyName, pcl_value);
Binding contourLineBinding = bindingContext.bind(contourLineStylePropertyName, contourLineStyleValue);
contourLineBinding.addComponent(contourLineStyleLabel);
bindingContext.addPropertyChangeListener(contourLineStylePropertyName, pcl_lineStyle);
Binding contourLineDashLengthBinding = bindingContext.bind(contourLineDashLengthPropertyName, dashLengthValue);
contourLineDashLengthBinding.addComponent(contourLineDashLengthLabel);
bindingContext.addPropertyChangeListener(contourLineDashLengthPropertyName, pcl_lineDashLength);
Binding contourLineSpaceLengthBinding = bindingContext.bind(contourLineSpaceLengthPropertyName, spaceLengthValue);
contourLineSpaceLengthBinding.addComponent(contourLineSpaceLengthLabel);
bindingContext.addPropertyChangeListener(contourLineSpaceLengthPropertyName, pcl_lineSpaceLength);
contourLevelPanel.add(contourNameLabel);
contourLevelPanel.add(contourLevelName);
contourLevelPanel.add(contourValueLabel);
contourLevelPanel.add(contourLevelValue);
contourLevelPanel.add(contourColorLabel);
contourLevelPanel.add(contourLineColorComboBox);
customPanel.add(contourLevelPanel);
}
Object[] options = {"Save",
"Cancel"};
final JOptionPane optionPane = new JOptionPane(customPanel,
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
javax.swing.UIManager.getIcon("OptionPane.informationIcon"), //do not use a custom Icon
options, //the titles of buttons
options[0]); //default button title
final JDialog dialog = optionPane.createDialog(this, "Group Contour Levels");
dialog.setDefaultCloseOperation(
JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
//setLabel("Thwarted user attempt to close window.");
}
});
optionPane.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (dialog.isVisible()
&& (e.getSource() == optionPane)
&& (prop.equals(JOptionPane.VALUE_PROPERTY))) {
//If you were going to check something
//before closing the window, you'd do
//it here.
dialog.setVisible(false);
}
}
});
Point dialogLoc = dialog.getLocation();
Point parentLoc = this.getLocation();
dialog.setLocation(parentLoc.x + dialogLoc.x, dialogLoc.y);
dialog.pack();
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
if (optionPane.getValue().equals(options[0])) {
contourData.setContourIntervals(contourIntervalsClone);
minValueField.setText(new Double(contourIntervalsClone.get(0).getContourLevelValue()).toString());
maxValueField.setText(new Double(contourIntervalsClone.get(contourIntervalsClone.size() - 1).getContourLevelValue()).toString());
minValue = contourIntervalsClone.get(0).getContourLevelValue();
maxValue = contourIntervalsClone.get(contourIntervalsClone.size() - 1).getContourLevelValue();
contourData.setStartValue(minValue);
contourData.setEndValue(maxValue);
contourData.setContourCustomized(true);
}
}
public ContourData getContourData() {
return contourData;
}
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() {
PropertyChangeListener[] pr = propertyChangeSupport.getPropertyChangeListeners();
for (int i = 0; i < pr.length; i++) {
this.propertyChangeSupport.removePropertyChangeListener(pr[i]);
}
}
}
| 26,809 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ContourLineFigureStyle.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/ui/ContourLineFigureStyle.java | package gov.nasa.gsfc.seadas.contour.ui;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.swing.figure.FigureStyle;
import com.bc.ceres.swing.figure.support.DefaultFigureStyle;
import org.esa.snap.core.datamodel.VectorDataNode;
import java.awt.*;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 7/11/14
* Time: 2:10 PM
* To change this template use File | Settings | File Templates.
*/
public class ContourLineFigureStyle extends DefaultFigureStyle {
public static final PropertyDescriptor STROKE_STYLE = createStrokeStyleDescriptor();
private VectorDataNode vectorDataNode;
public ContourLineFigureStyle(VectorDataNode vectorDataNode) {
this.vectorDataNode = vectorDataNode;
}
private static PropertyDescriptor createStrokeColorDescriptor() {
return createPropertyDescriptor("stroke-color", Color.class, null, false);
}
private static PropertyDescriptor createStrokeStyleDescriptor() {
return createPropertyDescriptor("stroke", BasicStroke.class, null, false);
}
private static PropertyDescriptor createPropertyDescriptor(String propertyName, Class type, Object defaultValue, boolean notNull) {
PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, type);
descriptor.setDefaultValue(defaultValue);
descriptor.setNotNull(notNull);
return descriptor;
}
public static FigureStyle createContourLineStyle(VectorDataNode vectorDataNode){
Stroke dashedStroke = new BasicStroke((float) getGridLineWidthPixels(vectorDataNode), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{(float) getDashLengthPixels(vectorDataNode)}, 0);
FigureStyle lineStyle = ContourLineFigureStyle.createLineStyle(new Color(255, 255, 255, 200),
dashedStroke);
lineStyle.setValue(STROKE_STYLE.getName(), dashedStroke);
return lineStyle;
}
private static double getOpacity(Color strokeColor) {
return Math.round(100.0 / 255.0 * strokeColor.getAlpha()) / 100.0;
}
private static double getGridLineWidthPixels(VectorDataNode vectorDataNode) {
double gridLineWidthPts = 0.8;
return getPtsToPixelsMultiplier(vectorDataNode) * gridLineWidthPts;
}
private static double getDashLengthPixels(VectorDataNode vectorDataNode) {
double dashLengthPts = 3;
return getPtsToPixelsMultiplier(vectorDataNode) * dashLengthPts;
}
private static double getPtsToPixelsMultiplier(VectorDataNode vectorDataNode) {
double ptsToPixelsMultiplier = -1.0;
if (ptsToPixelsMultiplier == -1.0) {
final double PTS_PER_INCH = 72.0;
final double PAPER_HEIGHT = 11.0;
final double PAPER_WIDTH = 8.5;
double heightToWidthRatioPaper = (PAPER_HEIGHT) / (PAPER_WIDTH);
double rasterHeight = vectorDataNode.getProduct().getSceneRasterHeight();
double rasterWidth = vectorDataNode.getProduct().getSceneRasterWidth();
double heightToWidthRatioRaster = rasterHeight / rasterWidth;
if (heightToWidthRatioRaster > heightToWidthRatioPaper) {
// use height
ptsToPixelsMultiplier = (1 / PTS_PER_INCH) * (rasterHeight / (PAPER_HEIGHT));
} else {
// use width
ptsToPixelsMultiplier = (1 / PTS_PER_INCH) * (rasterWidth / (PAPER_WIDTH));
}
}
return ptsToPixelsMultiplier;
}
}
| 3,585 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ContourFilteredBandAction.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/ui/ContourFilteredBandAction.java | package gov.nasa.gsfc.seadas.contour.ui;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.util.ProductUtils;
import org.esa.snap.rcp.imgfilter.FilteredBandAction;
import org.esa.snap.rcp.imgfilter.model.Filter;
public class ContourFilteredBandAction extends FilteredBandAction {
static GeneralFilterBand.OpType getOpType(Filter.Operation operation) {
if (operation == Filter.Operation.OPEN) {
return GeneralFilterBand.OpType.OPENING;
} else if (operation == Filter.Operation.CLOSE) {
return GeneralFilterBand.OpType.CLOSING;
} else if (operation == Filter.Operation.ERODE) {
return GeneralFilterBand.OpType.EROSION;
} else if (operation == Filter.Operation.DILATE) {
return GeneralFilterBand.OpType.DILATION;
} else if (operation == Filter.Operation.MIN) {
return GeneralFilterBand.OpType.MIN;
} else if (operation == Filter.Operation.MAX) {
return GeneralFilterBand.OpType.MAX;
} else if (operation == Filter.Operation.MEAN) {
return GeneralFilterBand.OpType.MEAN;
} else if (operation == Filter.Operation.MEDIAN) {
return GeneralFilterBand.OpType.MEDIAN;
} else if (operation == Filter.Operation.STDDEV) {
return GeneralFilterBand.OpType.STDDEV;
} else {
throw new IllegalArgumentException("illegal operation: " + operation);
}
}
private static Kernel getKernel(Filter filter) {
return new Kernel(filter.getKernelWidth(),
filter.getKernelHeight(),
filter.getKernelOffsetX(),
filter.getKernelOffsetY(),
1.0 / filter.getKernelQuotient(),
filter.getKernelElements());
}
static FilterBand getFilterBand(RasterDataNode sourceRaster, String bandName, Filter filter, int iterationCount) {
FilterBand targetBand;
Product targetProduct = sourceRaster.getProduct();
if (filter.getOperation() == Filter.Operation.CONVOLVE) {
targetBand = new ConvolutionFilterBand(bandName, sourceRaster, getKernel(filter), iterationCount);
if (sourceRaster instanceof Band) {
ProductUtils.copySpectralBandProperties((Band) sourceRaster, targetBand);
}
} else {
GeneralFilterBand.OpType opType = getOpType(filter.getOperation());
targetBand = new GeneralFilterBand(bandName, sourceRaster, opType, getKernel(filter), iterationCount);
if (sourceRaster instanceof Band) {
ProductUtils.copySpectralBandProperties((Band) sourceRaster, targetBand);
}
}
targetBand.setDescription(String.format("Filter '%s' (=%s) applied to '%s'", filter.getName(), filter.getOperation(), sourceRaster.getName()));
if (sourceRaster instanceof Band) {
ProductUtils.copySpectralBandProperties((Band) sourceRaster, targetBand);
}
targetProduct.addBand(targetBand);
ProductUtils.copyImageGeometry(sourceRaster, targetBand, false);
targetBand.fireProductNodeDataChanged();
return targetBand;
}
public FilterBand createdFilterBand(Filter filter, String bandName, int iterationCount){
return null;
}
}
| 3,328 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ExGridBagConstraints.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/ui/ExGridBagConstraints.java | package gov.nasa.gsfc.seadas.contour.ui;
import java.awt.*;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 1:57 PM
* To change this template use File | Settings | File Templates.
*/
public class ExGridBagConstraints extends GridBagConstraints {
public ExGridBagConstraints(int gridx, int gridy) {
this.gridx = gridx;
this.gridy = gridy;
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, int pad) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
this.insets = new Insets(pad, pad, pad, pad);
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, Insets insets) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
this.insets = insets;
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, int pad, int gridwidth) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
this.insets = new Insets(pad, pad, pad, pad);
this.gridwidth = gridwidth;
}
} | 1,795 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ContourDialog.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/ui/ContourDialog.java | package gov.nasa.gsfc.seadas.contour.ui;
import gov.nasa.gsfc.seadas.contour.data.ContourData;
import gov.nasa.gsfc.seadas.contour.data.ContourInterval;
import gov.nasa.gsfc.seadas.contour.util.CommonUtilities;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.imgfilter.FilteredBandAction;
import org.esa.snap.rcp.imgfilter.model.Filter;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.product.ProductSceneView;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.openide.util.HelpCtx;
import javax.help.HelpBroker;
import javax.swing.*;
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.Collections;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 9/9/13
* Time: 12:24 PM
* To change this template use File | Settings | File Templates.
*/
public class ContourDialog extends JDialog {
static final String PREF_KEY_AUTO_SHOW_NEW_BANDS = "ContourLines.autoShowNewBands";
public static final String TITLE = "Create Contour Lines"; /*I18N*/
static final String NEW_BAND_SELECTED_PROPERTY = "newBandSelected";
static final String DELETE_BUTTON_PRESSED_PROPERTY = "deleteButtonPressed";
static final String NEW_FILTER_SELECTED_PROPERTY = "newFilterSelected";
static final String FILTER_STATUS_CHANGED_PROPERTY = "filterStatusChanged";
private ContourData contourData;
private Component helpButton = null;
private HelpBroker helpBroker = null;
private final static String helpId = "contourLinesHelp";
private final static String HELP_ICON = "icons/Help24.gif";
private Product product;
Band selectedBand;
Band selectedFilteredBand;
Band selectedUnfilteredBand;
int numberOfLevels;
JComboBox bandComboBox;
ArrayList<ContourData> contours;
ArrayList<String> activeBands;
private SwingPropertyChangeSupport propertyChangeSupport;
JPanel contourPanel;
private boolean contourCanceled;
private String filteredBandName;
boolean filterBand;
private double noDataValue;
RasterDataNode raster;
private double NULL_DOUBLE = -1.0;
private double ptsToPixelsMultiplier = NULL_DOUBLE;
JCheckBox filtered = new JCheckBox("", true);
ContourIntervalDialog contourIntervalDialog;
public ContourDialog(Product product, ArrayList<String> activeBands) {
super(SnapApp.getDefault().getMainFrame(), TITLE, JDialog.DEFAULT_MODALITY_TYPE);
this.product = product;
propertyChangeSupport = new SwingPropertyChangeSupport(this);
helpButton = getHelpButton();
// todo This is old block of broken code which can probably be deleted once well tested
// ProductNode productNode = SnapApp.getDefault().getSelectedProductNode(SnapApp.SelectionSourceHint.VIEW);
//
// if (productNode != null && activeBands.contains(productNode.getName())) {
// selectedUnfilteredBand = product.getBand(productNode.getName());
// //selectedBand = product.getBand(VisatApp.getApp().getSelectedProductNode().getName());
// selectedBand = getDefaultFilterBand(selectedUnfilteredBand);
// raster = product.getRasterDataNode(selectedUnfilteredBand.getName());
// } else {
// selectedUnfilteredBand = product.getBand(activeBands.get(0));
// //selectedBand = product.getBand(activeBands.get(0)); //todo - match this with the selected productNode
// selectedBand = getDefaultFilterBand(selectedUnfilteredBand);
// raster = product.getRasterDataNode(selectedUnfilteredBand.getName());
//
// }
// todo This is new block which fixes above commented out broken code
ProductSceneView productSceneView = SnapApp.getDefault().getSelectedProductSceneView();
ProductNodeGroup<Band> bandGroup = product.getBandGroup();
if (productSceneView != null) {
ImageInfo selectedImageInfo = productSceneView.getImageInfo();
Band[] bands = new Band[bandGroup.getNodeCount()];
bandGroup.toArray(bands);
for (Band band : bands) {
if (band.getImageInfo() != null) {
if (band.getImageInfo() == selectedImageInfo) {
selectedUnfilteredBand = band;
}
}
}
selectedBand = getDefaultFilterBand(selectedUnfilteredBand);
raster = product.getRasterDataNode(selectedUnfilteredBand.getName());
this.activeBands = activeBands;
ptsToPixelsMultiplier = getPtsToPixelsMultiplier();
contourData = new ContourData(selectedBand, selectedUnfilteredBand.getName(), getFilterShortHandName(), ptsToPixelsMultiplier);
numberOfLevels = 1;
contours = new ArrayList<ContourData>();
propertyChangeSupport.addPropertyChangeListener(NEW_BAND_SELECTED_PROPERTY, getBandPropertyListener());
propertyChangeSupport.addPropertyChangeListener(DELETE_BUTTON_PRESSED_PROPERTY, getDeleteButtonPropertyListener());
propertyChangeSupport.addPropertyChangeListener(NEW_FILTER_SELECTED_PROPERTY, getFilterButtonPropertyListener());
propertyChangeSupport.addPropertyChangeListener(FILTER_STATUS_CHANGED_PROPERTY, getFilterCheckboxPropertyListener());
noDataValue = selectedBand.getNoDataValue();
createContourUI();
}
contourCanceled = true;
}
private PropertyChangeListener getBandPropertyListener() {
return new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
for (ContourData contourData1 : contours) {
contourData1.setBand(selectedBand);
}
}
};
}
private PropertyChangeListener getFilterButtonPropertyListener() {
return new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
for (ContourData contourData : contours) {
contourData.setFilterName(getFilterShortHandName());
}
if (!contourIntervalDialog.getContourData().isContourCustomized() && ! contourIntervalDialog.getContourData().isContourValuesChanged())
contourIntervalDialog.setBand(selectedBand);
}
};
}
private PropertyChangeListener getFilterCheckboxPropertyListener() {
return new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
for (ContourData contourData : contours) {
if (!contourData.isContourCustomized()) {
contourData.setStartValue(CommonUtilities.round(selectedBand.getStx().getMinimum(), 3));
contourData.setEndValue(CommonUtilities.round(selectedBand.getStx().getMaximum(), 3));
}
contourData.setFilterName(getFilterShortHandName());
}
if (!contourIntervalDialog.getContourData().isContourCustomized() && ! contourIntervalDialog.getContourData().isContourValuesChanged())
contourIntervalDialog.setBand(selectedBand);
}
};
}
private PropertyChangeListener getDeleteButtonPropertyListener() {
return new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
Component[] components = contourPanel.getComponents();
for (Component component : components) {
if (component instanceof JPanel) {
Component[] jPanelComponents = ((JPanel) component).getComponents();
for (Component jPanelComponent : jPanelComponents) {
if (component instanceof JPanel && ((JPanel) jPanelComponent).getComponents().length == 0) {
((JPanel) component).remove(jPanelComponent);
}
}
}
contourPanel.validate();
contourPanel.repaint();
}
//delete vectors from the memory also
for (ContourData contourData1 : contours) {
if (contourData1.isDeleted()) {
contours.remove(contourData1);
}
}
}
};
}
@Override
public void addPropertyChangeListener(String name, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(name, listener);
}
@Override
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() {
PropertyChangeListener[] pr = propertyChangeSupport.getPropertyChangeListeners();
for (int i = 0; i < pr.length; i++) {
this.propertyChangeSupport.removePropertyChangeListener(pr[i]);
}
}
protected AbstractButton getHelpButton() {
if (helpId != null) {
final AbstractButton helpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon(HELP_ICON),
false);
helpButton.setToolTipText("Help.");
helpButton.setName("helpButton");
helpButton.addActionListener(e ->getHelpCtx().display());
return helpButton;
}
return null;
}
public HelpCtx getHelpCtx() {
return new HelpCtx(helpId);
}
public final JPanel createContourUI() {
final int rightInset = 5;
contourPanel = new JPanel(new GridBagLayout());
contourPanel.setBorder(BorderFactory.createTitledBorder(""));
final JPanel contourContainerPanel = new JPanel(new GridBagLayout());
final JPanel basicPanel = getContourPanel();
contourContainerPanel.add(basicPanel,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
JButton addButton = new JButton("+");
addButton.setPreferredSize(addButton.getPreferredSize());
addButton.setMinimumSize(addButton.getPreferredSize());
addButton.setMaximumSize(addButton.getPreferredSize());
addButton.setName("addButton");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JPanel addedPanel = getContourPanel();
((JButton) event.getSource()).getParent().add(addedPanel);
JPanel c = (JPanel) ((JButton) event.getSource()).getParent();
JPanel jPanel = (JPanel) c.getComponents()[0];
int numPanels = jPanel.getComponents().length;
jPanel.add(addedPanel,
new ExGridBagConstraints(0, numPanels, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
repaint();
pack();
}
});
contourContainerPanel.addPropertyChangeListener(DELETE_BUTTON_PRESSED_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
Component[] components = contourContainerPanel.getComponents();
for (Component component : components) {
if (((JPanel) component).getComponents().length == 0) {
contourContainerPanel.remove(component);
}
}
contourContainerPanel.validate();
contourContainerPanel.repaint();
}
});
JPanel mainPanel = new JPanel(new GridBagLayout());
contourPanel.add(contourContainerPanel,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
contourPanel.add(addButton,
new ExGridBagConstraints(0, 2, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
mainPanel.add(getBandPanel(),
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
mainPanel.add(contourPanel,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
mainPanel.add(getControllerPanel(),
new ExGridBagConstraints(0, 2, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
add(mainPanel);
//this will set the "Create Contour Lines" button as a default button that listens to the Enter key
mainPanel.getRootPane().setDefaultButton((JButton) ((JPanel) mainPanel.getComponent(2)).getComponent(2));
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("Create Contour Lines");
//setTitle("Contour Lines for " + selectedBand.getName() );
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
pack();
return mainPanel;
}
/**
* By default a band should be filtered before running the contour algorithm on it.
*
* @return
*/
private JPanel getBandPanel() {
final int rightInset = 5;
final JPanel bandPanel = new JPanel(new GridBagLayout());
JLabel bandLabel = new JLabel("Product: ");
final JTextArea filterMessage = new JTextArea("Using filter " + getFilterShortHandName());
Collections.swap(activeBands, 0, activeBands.indexOf(selectedUnfilteredBand.getName()));
//bandComboBox = new JComboBox(activeBands.toArray());
bandComboBox = new JComboBox(new String[]{selectedUnfilteredBand.getName()});
bandComboBox.setSelectedItem(selectedBand.getName());
//bandComboBox.setEnabled(false);
bandComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
String oldBandName = selectedBand.getName();
if (filterBand) {
product.getBandGroup().remove(product.getBand(selectedBand.getName()));
}
selectedUnfilteredBand = product.getBand((String) bandComboBox.getSelectedItem());
//selectedBand = selectedUnfilteredBand;
product.getRasterDataNode(oldBandName);
selectedBand = getDefaultFilterBand(product.getRasterDataNode(oldBandName));
filtered.setSelected(true);
filterBand = true;
filterMessage.setText("Using filter " + getFilterShortHandName());
//raster = product.getRasterDataNode(selectedUnfilteredBand.getName());
propertyChangeSupport.firePropertyChange(NEW_BAND_SELECTED_PROPERTY, oldBandName, selectedBand.getName());
noDataValue = selectedBand.getGeophysicalNoDataValue();
}
});
final JButton filterButton = new JButton("Choose Filter");
final JCheckBox filtered = new JCheckBox("", true);
filterMessage.setBackground(Color.lightGray);
filterMessage.setEditable(false);
filterButton.addActionListener(new ActionListener() {
SnapApp snapApp = SnapApp.getDefault();
@Override
public void actionPerformed(ActionEvent e) {
Band currentFilteredBand = selectedFilteredBand;
SnapApp.getDefault().getPreferences().put(PREF_KEY_AUTO_SHOW_NEW_BANDS, "false");
FilteredBandAction filteredBandAction = new FilteredBandAction();
//VisatApp.getApp().setSelectedProductNode(selectedUnfilteredBand);
if (selectedFilteredBand != null) {
product.getBandGroup().remove(product.getBand(selectedFilteredBand.getName()));
}
filteredBandAction.actionPerformed(e);
updateActiveBandList();
SnapApp.getDefault().getPreferences().put(PREF_KEY_AUTO_SHOW_NEW_BANDS, "true");
if (filterBand) {
filterMessage.setText("Using filter " + getFilterShortHandName());
filtered.setSelected(true);
} else {
if (currentFilteredBand != null) {
product.getBandGroup().add(currentFilteredBand);
}
}
propertyChangeSupport.firePropertyChange(NEW_FILTER_SELECTED_PROPERTY, true, false);
}
});
filtered.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (filtered.isSelected()) {
//SnapApp.getDefault().setSelectedProductNode(selectedUnfilteredBand);
selectedBand = getDefaultFilterBand(selectedBand);
selectedFilteredBand = selectedBand;
filterMessage.setText("Using filter " + getFilterShortHandName());
filterBand = true;
} else {
//VisatApp.getApp().setSelectedProductNode(selectedUnfilteredBand);
selectedBand = selectedUnfilteredBand;
filterMessage.setText("Not filtered");
if (selectedFilteredBand != null) {
product.getBandGroup().remove(product.getBand(selectedFilteredBand.getName()));
}
selectedFilteredBand = null;
filterBand = false;
}
propertyChangeSupport.firePropertyChange(FILTER_STATUS_CHANGED_PROPERTY, true, false);
}
});
JLabel filler = new JLabel(" ");
JTextArea productTextArea = new JTextArea(bandComboBox.getSelectedItem().toString());
productTextArea.setBackground(Color.lightGray);
productTextArea.setEditable(false);
bandPanel.add(filler,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
bandPanel.add(bandLabel,
new ExGridBagConstraints(1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
bandPanel.add(productTextArea,
new ExGridBagConstraints(2, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
bandPanel.add(filterButton,
new ExGridBagConstraints(3, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
bandPanel.add(filtered,
new ExGridBagConstraints(4, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
bandPanel.add(filterMessage,
new ExGridBagConstraints(5, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
return bandPanel;
}
private void updateActiveBandList() {
Band[] bands = product.getBands();
filterBand = false;
for (Band band : bands) {
//the image info of the filteredBand of the current band is null; this is to avoid selecting other filter bands and setting them to null
if (band.getName().contains(selectedUnfilteredBand.getName()) && band.getName().length() > selectedUnfilteredBand.getName().length() && band.equals(bands[bands.length - 1])) {
selectedBand = band;
selectedFilteredBand = band;
filteredBandName = band.getName();
filterBand = true;
noDataValue = selectedBand.getNoDataValue();
}
}
}
private JPanel getControllerPanel() {
JPanel controllerPanel = new JPanel(new GridBagLayout());
JButton createContourLines = new JButton("Create Contour Lines");
createContourLines.setPreferredSize(createContourLines.getPreferredSize());
createContourLines.setMinimumSize(createContourLines.getPreferredSize());
createContourLines.setMaximumSize(createContourLines.getPreferredSize());
createContourLines.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// if (contourData.getContourIntervals().size() == 0) {
// contourData.createContourLevels(getMinValue(), getMaxValue(), getNumberOfLevels(), logCheckBox.isSelected());
// }
contourCanceled = false;
dispose();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.setPreferredSize(cancelButton.getPreferredSize());
cancelButton.setMinimumSize(cancelButton.getPreferredSize());
cancelButton.setMaximumSize(cancelButton.getPreferredSize());
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
contourCanceled = true;
dispose();
}
});
JLabel filler = new JLabel(" ");
controllerPanel.add(filler,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
controllerPanel.add(cancelButton,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
controllerPanel.add(createContourLines,
new ExGridBagConstraints(3, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
controllerPanel.add(helpButton,
new ExGridBagConstraints(5, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
return controllerPanel;
}
private JPanel getContourPanel() {
contourIntervalDialog = new ContourIntervalDialog(selectedBand, selectedUnfilteredBand.getName(), getFilterShortHandName(), ptsToPixelsMultiplier);
contourIntervalDialog.addPropertyChangeListener(DELETE_BUTTON_PRESSED_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
propertyChangeSupport.firePropertyChange(DELETE_BUTTON_PRESSED_PROPERTY, true, false);
}
});
contourIntervalDialog.addPropertyChangeListener(ContourIntervalDialog.CONTOUR_DATA_CHANGED_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
for (ContourData contourData : contours) {
contourData.createContourLevels();
}
}
});
contourIntervalDialog.addPropertyChangeListener(FILTER_STATUS_CHANGED_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
contourIntervalDialog.setBand(selectedBand);
System.out.println("would this line be executed?");
}
});
contours.add(contourIntervalDialog.getContourData());
return contourIntervalDialog.getBasicPanel();
}
public ContourData getContourData() {
return getContourData(contours);
}
public ContourData getContourData(ArrayList<ContourData> contours) {
ContourData mergedContourData = new ContourData(selectedBand, selectedUnfilteredBand.getName(), getFilterShortHandName(), ptsToPixelsMultiplier);
ArrayList<ContourInterval> contourIntervals = new ArrayList<ContourInterval>();
for (ContourData contourData : contours) {
if (contourData != null)
contourIntervals.addAll(contourData.getContourIntervals());
}
mergedContourData.setContourIntervals(contourIntervals);
mergedContourData.setFiltered(filterBand);
return mergedContourData;
}
public boolean isContourCanceled() {
return contourCanceled;
}
public void setContourCanceled(boolean contourCanceled) {
this.contourCanceled = contourCanceled;
}
public String getFilteredBandName() {
return filteredBandName;
}
private ActionEvent getFilterActionEvent(FilteredBandAction filteredBandAction, ActionEvent actionEvent) {
ActionEvent filterCommandEvent = new ActionEvent(filteredBandAction, 1,null, 0);
return filterCommandEvent;
}
private FilterBand getDefaultFilterBand(RasterDataNode rasterDataNode) {
// Filter defaultFilter = new Filter("Mean 2.5 Pixel Radius", "amc_2.5px", 5, 5, new double[]{
// 0.172, 0.764, 1, 0.764, 0.172,
// 0.764, 1, 1, 1, 0.764,
// 1, 1, 1, 1, 1,
// 0.764, 1, 1, 1, 0.764,
// 0.172, 0.764, 1, 0.764, 0.172,
// }, 19.8);
Filter defaultFilter =new Filter("Arithmetic Mean 5x5", "am5", 5, 5, new double[]{
+1, +1, +1, +1, +1,
+1, +1, +1, +1, +1,
+1, +1, +1, +1, +1,
+1, +1, +1, +1, +1,
+1, +1, +1, +1, +1,
}, 25.0);
ContourFilteredBandAction contourFilteredBandAction = new ContourFilteredBandAction();
final FilterBand filteredBand = contourFilteredBandAction.getFilterBand(rasterDataNode, selectedUnfilteredBand.getName() + "_am5", defaultFilter,1);
filterBand = true;
selectedFilteredBand = filteredBand;
filteredBandName = filteredBand.getName();
return filteredBand;
}
public double getNoDataValue() {
return noDataValue;
}
public void setNoDataValue(double noDataValue) {
this.noDataValue = noDataValue;
}
private double getPtsToPixelsMultiplier() {
if (ptsToPixelsMultiplier == NULL_DOUBLE) {
final double PTS_PER_INCH = 72.0;
final double PAPER_HEIGHT = 11.0;
final double PAPER_WIDTH = 8.5;
double heightToWidthRatioPaper = (PAPER_HEIGHT) / (PAPER_WIDTH);
double heightToWidthRatioRaster = raster.getRasterHeight() / raster.getRasterWidth();
if (heightToWidthRatioRaster > heightToWidthRatioPaper) {
// use height
ptsToPixelsMultiplier = (1 / PTS_PER_INCH) * (raster.getRasterHeight() / (PAPER_HEIGHT));
} else {
// use width
ptsToPixelsMultiplier = (1 / PTS_PER_INCH) * (raster.getRasterWidth() / (PAPER_WIDTH));
}
}
return ptsToPixelsMultiplier;
}
private String getFilterShortHandName() {
if (selectedFilteredBand == null) {
return "not_filtered";
}
String selectedUnfilteredBandName = selectedUnfilteredBand.getName();
String selectedFilteredBandName = selectedFilteredBand.getName();
return selectedFilteredBandName.substring(selectedUnfilteredBandName.length() + 1);
}
}
| 28,007 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
Contour1Spi.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/operator/Contour1Spi.java | /*
* Copyright (c) 2010, Michael Bedward. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.nasa.gsfc.seadas.contour.operator;
import javax.media.jai.OperationDescriptor;
import javax.media.jai.OperationRegistry;
import javax.media.jai.OperationRegistrySpi;
import javax.media.jai.registry.RenderedRegistryMode;
import java.awt.image.renderable.RenderedImageFactory;
/**
* OperationRegistrySpi implementation to register the "Contour"
* operation and its associated image factories.
*
*/
public class Contour1Spi implements OperationRegistrySpi {
/** The name of the product to which these operations belong. */
private String productName = "gov.nasa.gsfc.seadas.contour";
/** Default constructor. */
public Contour1Spi() {}
/**
* Registers the Contour operation and its
* associated image factories across all supported operation modes.
*
* @param registry The registry with which to register the operations
* and their factories.
*/
public void updateRegistry(OperationRegistry registry) {
OperationDescriptor op = new ContourDescriptor();
registry.registerDescriptor(op);
String descName = op.getName();
RenderedImageFactory rif = new ContourRIF();
registry.registerFactory(RenderedRegistryMode.MODE_NAME,
descName,
productName,
rif);
}
}
| 2,803 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ContourOpImage.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/operator/ContourOpImage.java | /*
* Copyright (c) 2010-2011, Michael Bedward. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.nasa.gsfc.seadas.contour.operator;
import org.jaitools.CollectionFactory;
import org.jaitools.jts.LineSmoother;
import org.jaitools.jts.SmootherControl;
import org.jaitools.jts.Utils;
import org.jaitools.media.jai.AttributeOpImage;
import org.jaitools.numeric.CompareOp;
import org.jaitools.numeric.Range;
import org.locationtech.jts.geom.LineString;
import javax.media.jai.PlanarImage;
import javax.media.jai.ROI;
import javax.media.jai.iterator.RectIter;
import javax.media.jai.iterator.RectIterFactory;
import java.awt.image.RenderedImage;
import java.lang.ref.SoftReference;
import java.util.*;
/**
* Generates contours for user-specified levels of values in the source image.
* The contours are returned as a {@code Collection} of
* {@link com.vividsolutions.jts.geom.LineString}s.
* <p>
* The interpolation algorithm used is that of Paul Bourke: originally published
* in Byte magazine (1987) as the CONREC contouring subroutine written in
* FORTRAN. The implementation here was adapted from Paul Bourke's C code for the
* algorithm available at:
* <a href="http://local.wasp.uwa.edu.au/~pbourke/papers/conrec/">
* http://local.wasp.uwa.edu.au/~pbourke/papers/conrec/</a>
* <p>
*
* @author Michael Bedward
* @since 1.1
* @version $Id$
*/
public class ContourOpImage extends AttributeOpImage {
/*
* Constants to identify vertices for each group of
* data points being processed, as per the diagram
* in the javadoc for getContourSegments method.
*/
private static final int BL_VERTEX1 = 0;
private static final int BR_VERTEX2 = 1;
private static final int TR_VERTEX3 = 2;
private static final int TL_VERTEX4 = 3;
/** The source image band to process */
private int band;
/** Values at which to generate contour intervals */
private List<Double> contourLevels;
/**
* Interval between contours. This is used if specific contour
* levels are not requested. Contours will be generated such that
* the value of each is an integer multiple of this value.
*/
private Double contourInterval;
/** List of Numbers to treat as NO_DATA */
private List<Double> noDataNumbers;
/** List of Ranges to treat as NO_DATA */
private List<Range<Double>> noDataRanges;
/** Whether to use strict NODATA exclusion */
private final boolean strictNodata;
/** Output contour lines */
private SoftReference<List<LineString>> cachedContours;
/** Whether to simplify contour lines by removing coincident vertices */
private final boolean simplify;
/** Whether to apply Bezier smoothing to the contour lines */
private final boolean smooth;
/**
* Alpha parameter controlling Bezier smoothing
* (see {@link LineSmoother})
*/
private double smoothAlpha = 0.0;
/**
* Control object for Bezier smoothing. Note that length units here
* are pixels.
*/
private final SmootherControl smootherControl = new SmootherControl() {
public double getMinLength() {
return 0.1;
}
public int getNumVertices(double length) {
return (int) Math.max(5, length * 10);
}
};
/**
* Constructor. Note that one of {@code levels} or {@code interval} must
* be supplied. If both are supplied {@code interval} is ignored.
*
* @param source the source image
*
* @param roi an optional {@code ROI} to constrain the areas for which
* contours are generated
*
* @param band the band of the source image to process
*
* @param levels values for which to generate contours
*
* @param interval interval between contour levels (ignored if {@code levels}
* is supplied)
*
* @param noDataValues an optional {@code Collection} of values and/or {@code Ranges}
* to treat as NO_DATA
*
* @param simplify whether to simplify contour lines by removing
* colinear vertices
*
* @param strictNodata if {@code true} any NO_DATA values in a 2x2 data window will
* cause that window to be skipped; if {@code false} a single NO_DATA value
* is permitted
*
* @param smooth whether contour lines should be smoothed using
* Bezier interpolation
*/
public ContourOpImage(RenderedImage source,
ROI roi,
int band,
Collection<? extends Number> levels,
Double interval,
Collection<Object> noDataValues,
boolean strictNodata,
boolean simplify,
boolean smooth) {
super(source, roi);
this.band = band;
if (levels != null) {
this.contourLevels = new ArrayList<Double>();
// Use specific levels
for (Number z : levels) {
this.contourLevels.add(z.doubleValue());
}
Collections.sort(contourLevels);
} else if (interval != null && !interval.isNaN()) {
// Use requested interval with levels 'discovered' as the
// image is scanned
this.contourInterval = interval;
} else {
throw new IllegalArgumentException("At least one of levels or interval must be supplied");
}
this.noDataNumbers = CollectionFactory.list();
this.noDataRanges = CollectionFactory.list();
if (noDataValues != null) {
// Only add values that are not in the default set:
// NaN, +ve and -ve Inf, MaxValue
for (Object oelem : noDataValues) {
if (oelem instanceof Number) {
double dz = ((Number)oelem).doubleValue();
if (!(Double.isNaN(dz) ||
Double.isInfinite(dz) ||
Double.compare(dz, Double.MAX_VALUE) == 0)) {
this.noDataNumbers.add(dz);
}
} else if (oelem instanceof Range) {
Range r = (Range) oelem;
Double min = r.getMin().doubleValue();
Double max = r.getMax().doubleValue();
Range<Double> rd = new Range<Double>(
min, r.isMinIncluded(), max, r.isMaxIncluded());
this.noDataRanges.add(rd);
} else {
// This should have been picked up by validateParameters
// method in ContourDescriptor, but just in case...
throw new IllegalArgumentException(
"only Number and Range elements are permitted in the "
+ "noDataValues Collection");
}
}
}
this.strictNodata = strictNodata;
this.simplify = simplify;
this.smooth = smooth;
// Set the precision to use for Geometry operations
Utils.setPrecision(100.0);
}
/**
* {@inheritDoc }
*/
@Override
protected Object getAttribute(String name) {
if (cachedContours == null || cachedContours.get() == null) {
synchronized(this) {
cachedContours = new SoftReference<List<LineString>>(createContours());
}
}
return cachedContours.get();
}
/**
* {@inheritDoc }
*/
@Override
protected String[] getAttributeNames() {
return new String[]{ContourDescriptor.CONTOUR_PROPERTY_NAME};
}
/**
* Returns the class of the specified attribute. For
* {@link ContourDescriptor#CONTOUR_PROPERTY_NAME} this will be {@code List}.
*/
@Override
protected Class<?> getAttributeClass(String name) {
if (ContourDescriptor.CONTOUR_PROPERTY_NAME.equalsIgnoreCase(name)) {
return List.class;
}
return super.getAttributeClass(name);
}
/**
* Controls contour generation.
*
* @return generated contours
*/
private List<LineString> createContours() {
// build the contour levels if necessary
if(contourLevels == null) {
contourLevels = buildContourLevels();
}
// aggregate all the segments
Map<Integer, Segments> segments = getContourSegments();
/*
* Assemble contours into a simple list and assign values
*/
List<LineString> mergedContourLines = new ArrayList<LineString>();
int levelIndex = 0;
for (Double levelValue : contourLevels) {
Segments levelSegments = segments.remove(levelIndex);
if (levelSegments != null) {
List<LineString> levelContours = levelSegments.getMergedSegments();
for (LineString line : levelContours) {
line.setUserData(levelValue);
}
mergedContourLines.addAll(levelContours);
}
levelIndex++;
}
/*
* Bezier smoothing of contours
*/
if (smooth) {
LineSmoother smoother = new LineSmoother(Utils.getGeometryFactory());
smoother.setControl(smootherControl);
final int N = mergedContourLines.size();
for (int i = N - 1; i >= 0; i--) {
LineString contour = mergedContourLines.remove(i);
LineString smoothed = smoother.smooth(contour, smoothAlpha);
mergedContourLines.add(smoothed);
}
}
return mergedContourLines;
}
/**
* Creates contour segments.
* The algorithm used is CONREC, devised by Paul Bourke (see class notes).
* <p>
* The source image is scanned with a 2x2 sample window. The algorithm
* then treats these values as corner vertex values for a square that is
* sub-divided into four triangles. This results in an additional centre
* vertex.
* <p>
* The following diagram, taken from the C implementation of CONREC,
* shows how vertices and triangles are indexed:
* <pre>
* vertex 4 +-------------------+ vertex 3
* | \ / |
* | \ m=3 / |
* | \ / |
* | \ / |
* | m=4 X m=2 | centre vertex is 0
* | / \ |
* | / \ |
* | / m=1 \ |
* | / \ |
* vertex 1 +-------------------+ vertex 2
*
* </pre>
* Each triangle is then categorized on which of its vertices are below,
* at or above the contour level being considered. Triangle vertices
* (m1, m2, m3) are indexed such that:
* <ul>
* <li> m1 is the square vertex with index == triangle index
* <li> m2 is square vertex 0
* <li> m3 is square vertex m+1 (or 1 when m == 4)
* </ul>
* The original CONREC algorithm produces some duplicate line segments
* which is not a problem when only plotting contours. However, here we
* try to avoid any duplication because this can confuse the merging of
* line segments into JTS LineStrings later.
* <p>
* NODATA values are handled by ignoring all triangles that have any
* NODATA vertices.
*
* @return the generated contour segments
*/
private Map<Integer, Segments> getContourSegments() {
Map<Integer, Segments> segments = new HashMap<Integer, Segments>();
double[] sample = new double[4];
boolean[] nodata = new boolean[4];
double[] h = new double[5];
double[] xh = new double[5];
double[] yh = new double[5];
int[] sh = new int[5];
double temp1, temp2, temp3, temp4;
int[][][] configLookup = {
{{0, 0, 8}, {0, 2, 5}, {7, 6, 9}},
{{0, 3, 4}, {1, 3, 1}, {4, 3, 0}},
{{9, 6, 7}, {5, 2, 0}, {8, 0, 0}}
};
final PlanarImage src = getSourceImage(0);
RectIter iter1 = RectIterFactory.create(src, src.getBounds());
RectIter iter2 = RectIterFactory.create(src, src.getBounds());
moveIterToBand(iter1, this.band);
moveIterToBand(iter2, this.band);
iter1.startLines();
iter2.startLines();
iter2.nextLine();
int y = (int) src.getBounds().getMinY();
while(!iter2.finishedLines() && !iter1.finishedLines()) {
iter1.startPixels();
iter2.startPixels();
sample[BR_VERTEX2] = iter1.getSampleDouble();
nodata[BR_VERTEX2] = isNoData(sample[BR_VERTEX2]);
sample[TR_VERTEX3] = iter2.getSampleDouble();
nodata[TR_VERTEX3] = isNoData(sample[TR_VERTEX3]);
iter1.nextPixel();
iter2.nextPixel();
int x = (int) src.getBounds().getMinX() + 1;
while (!iter1.finishedPixels() && !iter2.finishedPixels()) {
sample[BL_VERTEX1] = sample[BR_VERTEX2];
nodata[BL_VERTEX1] = nodata[BR_VERTEX2];
sample[BR_VERTEX2] = iter1.getSampleDouble();
nodata[BR_VERTEX2] = isNoData(sample[BR_VERTEX2]);
sample[TL_VERTEX4] = sample[TR_VERTEX3];
nodata[TL_VERTEX4] = nodata[TR_VERTEX3];
sample[TR_VERTEX3] = iter2.getSampleDouble();
nodata[TR_VERTEX3] = isNoData(sample[TR_VERTEX3]);
boolean processSquare = true;
boolean hasSingleNoData = false;
for (int i = 0; i < 4 && processSquare; i++) {
if (nodata[i]) {
if (strictNodata || hasSingleNoData) {
processSquare = false;
break;
} else {
hasSingleNoData = true;
}
}
}
if (processSquare) {
if (nodata[BL_VERTEX1]) {
temp1 = temp3 = sample[TL_VERTEX4];
} else if (nodata[TL_VERTEX4]) {
temp1 = temp3 = sample[BL_VERTEX1];
} else {
temp1 = Math.min(sample[BL_VERTEX1], sample[TL_VERTEX4]);
temp3 = Math.max(sample[BL_VERTEX1], sample[TL_VERTEX4]);
}
if (nodata[BR_VERTEX2]) {
temp2 = temp4 = sample[TR_VERTEX3];
} else if (nodata[TR_VERTEX3]) {
temp2 = temp4 = sample[BR_VERTEX2];
} else {
temp2 = Math.min(sample[BR_VERTEX2], sample[TR_VERTEX3]);
temp4 = Math.max(sample[BR_VERTEX2], sample[TR_VERTEX3]);
}
double dmin = Math.min(temp1, temp2);
double dmax = Math.max(temp3, temp4);
final int size=contourLevels.size();
for (int levelIndex = 0; levelIndex < size; levelIndex++) {
double levelValue = contourLevels.get(levelIndex);
if (levelValue < dmin || levelValue > dmax) {
continue;
}
Segments zlist = segments.get(levelIndex);
if (zlist == null) {
zlist = new Segments(simplify);
segments.put(levelIndex, zlist);
}
if (!nodata[TL_VERTEX4]) {
h[4] = sample[TL_VERTEX4] - levelValue;
xh[4] = x - 1;
yh[4] = y + 1;
sh[4] = Double.compare(h[4], 0.0);
}
if (!nodata[TR_VERTEX3]) {
h[3] = sample[TR_VERTEX3] - levelValue;
xh[3] = x;
yh[3] = y + 1;
sh[3] = Double.compare(h[3], 0.0);
}
if (!nodata[BR_VERTEX2]) {
h[2] = sample[BR_VERTEX2] - levelValue;
xh[2] = x;
yh[2] = y;
sh[2] = Double.compare(h[2], 0.0);
}
if (!nodata[BL_VERTEX1]) {
h[1] = sample[BL_VERTEX1] - levelValue;
xh[1] = x - 1;
yh[1] = y;
sh[1] = Double.compare(h[1], 0.0);
}
h[0] = 0.0;
int nh = 0;
for (int i = 0; i < 4; i++) {
if (!nodata[i]) {
h[0] += h[i+1];
nh++ ;
}
}
// Just in case
if (nh < 3) {
throw new IllegalStateException(
"Internal error: number data vertices = " + nh);
}
h[0] /= nh;
xh[0] = x - 0.5;
yh[0] = y + 0.5;
sh[0] = Double.compare(h[0], 0.0);
/* Scan each triangle in the box */
int m1, m2, m3;
for (int m = 1; m <= 4; m++) {
m1 = m;
m2 = 0;
m3 = m == 4 ? 1 : m + 1;
if (nodata[m1 - 1] || nodata[m3 - 1]) {
// skip this triangle with a NODATA vertex
continue;
}
int config = configLookup[sh[m1] + 1][sh[m2] + 1][sh[m3] + 1];
if (config == 0) {
continue;
}
double x0 = 0.0, y0 = 0.0, x1 = 0.0, y1 = 0.0;
boolean addSegment = true;
switch (config) {
/* Line between vertices 1 and 2 */
case 1:
x0 = xh[m1];
y0 = yh[m1];
x1 = xh[m2];
y1 = yh[m2];
break;
/* Line between vertices 2 and 3 */
case 2:
x0 = xh[m2];
y0 = yh[m2];
x1 = xh[m3];
y1 = yh[m3];
break;
/*
* Line between vertices 3 and 1.
* We only want to generate this segment
* for triangles m=2 and m=3, otherwise
* we will end up with duplicate segments.
*/
case 3:
if (m == 2 || m == 3) {
x0 = xh[m3];
y0 = yh[m3];
x1 = xh[m1];
y1 = yh[m1];
} else {
addSegment = false;
}
break;
/* Line between vertex 1 and side 2-3 */
case 4:
x0 = xh[m1];
y0 = yh[m1];
x1 = sect(m2, m3, h, xh);
y1 = sect(m2, m3, h, yh);
break;
/* Line between vertex 2 and side 3-1 */
case 5:
x0 = xh[m2];
y0 = yh[m2];
x1 = sect(m3, m1, h, xh);
y1 = sect(m3, m1, h, yh);
break;
/* Line between vertex 3 and side 1-2 */
case 6:
x0 = xh[m3];
y0 = yh[m3];
x1 = sect(m1, m2, h, xh);
y1 = sect(m1, m2, h, yh);
break;
/* Line between sides 1-2 and 2-3 */
case 7:
x0 = sect(m1, m2, h, xh);
y0 = sect(m1, m2, h, yh);
x1 = sect(m2, m3, h, xh);
y1 = sect(m2, m3, h, yh);
break;
/* Line between sides 2-3 and 3-1 */
case 8:
x0 = sect(m2, m3, h, xh);
y0 = sect(m2, m3, h, yh);
x1 = sect(m3, m1, h, xh);
y1 = sect(m3, m1, h, yh);
break;
/* Line between sides 3-1 and 1-2 */
case 9:
x0 = sect(m3, m1, h, xh);
y0 = sect(m3, m1, h, yh);
x1 = sect(m1, m2, h, xh);
y1 = sect(m1, m2, h, yh);
break;
}
if (addSegment) {
zlist.add(x0, y0, x1, y1);
}
}
}
}
iter1.nextPixel();
iter2.nextPixel();
x++;
}
iter1.nextLine();
iter2.nextLine();
y++;
}
return segments;
}
/**
* Calculate an X or Y ordinate for a contour segment end-point
* relative to the difference in value between two sampling positions.
*
* @param p1 index of the first sampling position
* @param p2 index of the second sampling position
* @param h source image values at sampling positions
* @param coord X or Y ordinates of the 4 corner sampling positions
*
* @return the calculated X or Y ordinate
*/
private static double sect(int p1, int p2, double[] h, double[] coord) {
return (h[p2] * coord[p1] - h[p1] * coord[p2]) / (h[p2] - h[p1]);
}
/**
* Scans the image and builds the required contour values.
* <p>
* Note: this method is only called when contour levels are being set
* according to a specified interval rather than user-supplied levels.
*
* @return the contour levels
*/
private List<Double> buildContourLevels() {
double minVal = 0, maxVal = 0;
boolean first = true;
RectIter iter = RectIterFactory.create(getSourceImage(0), getBounds());
boolean hasNonNan = false;
moveIterToBand(iter, this.band);
// scan all the pixels
iter.startLines();
while (!iter.finishedLines()) {
iter.startPixels();
while (!iter.finishedPixels()) {
double val = iter.getSampleDouble();
if (!Double.isNaN(val)) {
hasNonNan = true;
if (first) {
minVal = maxVal = val;
first = false;
} else if (val < minVal) {
minVal = val;
} else if (val > maxVal) {
maxVal = val;
}
}
iter.nextPixel();
}
iter.nextLine();
}
if (!hasNonNan) return Collections.emptyList();
double z = Math.floor(minVal / contourInterval) * contourInterval;
if (CompareOp.acompare(z, minVal) < 0) z += contourInterval;
List<Double> result = new ArrayList<Double>();
while (CompareOp.acompare(z, maxVal) <= 0) {
result.add(z);
z += contourInterval;
}
return result;
}
/**
* Positions an image iterator at the specified band.
*
* @param iter the iterator
* @param targetBand the band
*/
private void moveIterToBand(RectIter iter, int targetBand) {
int iband = 0;
iter.startBands();
while(iband < targetBand && !iter.nextBandDone()) {
iband++;
}
if(iband != targetBand) {
throw new IllegalArgumentException("Band " + targetBand + " not found, max band is " + iband);
}
}
/**
* Tests if a value should be treated as NODATA.
* Values that are NaN, infinite or equal to Double.MAX_VALUE
* are always treated as NODATA.
*
* @param value the value to test
*
* @return {@code true} if a NODATA value; {@code false} otherwise
*/
private boolean isNoData(double value) {
if (Double.isNaN(value) || Double.isInfinite(value) ||
Double.compare(value, Double.MAX_VALUE) == 0) {
return true;
}
for (Double d : noDataNumbers) {
if (CompareOp.aequal(value, d)) {
return true;
}
}
for (Range r : noDataRanges) {
if (r.contains(value)) {
return true;
}
}
return false;
}
}
| 28,193 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ContourDescriptor.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/operator/ContourDescriptor.java | /*
* Copyright (c) 2010, Michael Bedward. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.nasa.gsfc.seadas.contour.operator;
import javax.media.jai.OperationDescriptorImpl;
import javax.media.jai.ROI;
import javax.media.jai.registry.RenderedRegistryMode;
import javax.media.jai.util.Range;
import java.awt.image.renderable.ParameterBlock;
import java.util.Arrays;
import java.util.Collection;
/**
* Describes the "Contour" operation in which contour lines are interpolated
* from values in a source image band. The desired contour values can be
* specified either by supplying a {@code Collection} of values via the
* "levels" parameter, or a single value via the "interval" parameter. In the
* interval case, the resulting contour values will be integer multiples of
* the interval. If both parameters are supplied the "levels" parameter takes
* preference.
* <p>
* Contours are returned as a destination image property in the form of
* a {@code Collection} of {@link com.vividsolutions.jts.geom.LineString} objects.
* The source image value associated with each contour can be retrieved
* with the {@link com.vividsolutions.jts.geom.LineString#getUserData()} method.
* <p>
* Source image pixels are passed through to the destination image unchanged.
* <p>
* Three boolean parameters control the form of the generated contours:
* <ol type="1">
* <li>
* <b>simplify</b>: if {@code true} (the default) colinear vertices are removed
* to reduce contour memory requirements.
* <li>
* <b>mergeTiles</b>: if {@code true} (the default) contour lines are merged into
* {@code LineStrings} across image tile boundaries; if {@code false} mergine
* is skipped for faster processing.
* </li>
* <li>
* <b>smooth</b>: if {@code true} contours are smoothed using Bezier interpolation
* before being returned; if {@code false} (the default) no smoothing is done.
* This option will probably have little effect on the form of contours unless
* the source image resolution is coarse.
* </li>
* </ol>
* Example of use:
* <pre><code>
* RenderedImage src = ...
* ParameterBlockJAI pb = new ParameterBlockJAI("Contour");
* pb.setSource("source0", src);
*
* // For contours at specific levels set the levels parameter
* List<Double> levels = Arrays.asList(new double[]{1.0, 5.0, 10.0, 20.0, 50.0, 100.0});
* pb.setParameter("levels", levels);
*
* // Alternatively, set a constant interval between contours
* pb.setParameter("interval", 10.0);
*
* RenderedOp dest = JAI.create("Contour", pb);
* Collection<LineString> contours = (Collection<LineString>)
* dest.getProperty(ContourDescriptor.CONTOUR_PROPERTY_NAME);
*
* for (LineString contour : contours) {
* // get this contour's value
* Double contourValue = (Double) contour.getUserData();
* ...
* }
* </code></pre>
*
* The interpolation algorithm used is that of Paul Bourke: originally published
* in Byte magazine (1987) as the CONREC contouring subroutine written in
* FORTRAN. The implementation here was adapted from Paul Bourke's C code for the
* algorithm available at:
* <a href="http://local.wasp.uwa.edu.au/~pbourke/papers/conrec/">
* http://local.wasp.uwa.edu.au/~pbourke/papers/conrec/</a>
*
* <p>
* <b>Summary of parameters:</b>
* <table border="1", cellpadding="3">
* <tr>
* <th>Name</th>
* <th>Class</th>
* <th>Default</th>
* <th>Description</th>
* </tr>
*
* <tr>
* <td>roi</td>
* <td>ROI</td>
* <td>null</td>
* <td>An optional ROI defining the area to contour.</td>
* </tr>
*
* <tr>
* <td>band</td>
* <td>Integer</td>
* <td>0</td>
* <td>Source image band to process.</td>
* </tr>
*
* <tr>
* <td>levels</td>
* <td>Collection</td>
* <td>null</td>
* <td>The values for which to generate contours.</td>
* </tr>
*
* <tr>
* <td>interval</td>
* <td>Number</td>
* <td>null</td>
* <td>
* The interval between contour values. This parameter is ignored if the
* levels parameter has been supplied. With interval contouring the minimum
* and maximum contour values will be integer multiples of the interval
* parameter value.
* </td>
* </tr>
*
* <tr>
* <td>nodata</td>
* <td>Collection</td>
* <td>
* The set: {Double.NaN, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, Double.MAX_VALUE}
* </td>
* <td>
* Values to be treated as NO_DATA. A value can be either a Number or a
* {@link javax.media.jai.util.Range} (mixtures of both are permitted).
* </td>
* </tr>
*
* <tr>
* <td>strictNodata</td>
* <td>Boolean</td>
* <td>Boolean.TRUE</td>
* <td>
* If true, any NODATA values in the 2x2 cell moving window used by the
* contouring algorithm will cause that part of the image to be skipped.
* If false, a single NODATA value will be permitted in the window. This
* probably only makes a noticeable difference with small images.
* </td>
* </tr>
*
* <tr>
* <td>simplify</td>
* <td>Boolean</td>
* <td>Boolean.TRUE</td>
* <td>Whether to simplify contour lines by removing collinear vertices.</td>
* </tr>
*
* <tr>
* <td>smooth</td>
* <td>Boolean</td>
* <td>Boolean.FALSE</td>
* <td>
* Whether to smooth contour lines using Bezier interpolation. This probably
* only makes a noticeable difference with small images.
* </td>
* </tr>
* </table>
*
* @author Michael Bedward
* @since 1.1
* @version $Id$
*/
public class ContourDescriptor extends OperationDescriptorImpl {
/**
* Constant identifying the image property that will hold the generated contours.
*/
public final static String CONTOUR_PROPERTY_NAME = "contours";
static final int ROI_ARG = 0;
static final int BAND_ARG = 1;
static final int LEVELS_ARG = 2;
static final int INTERVAL_ARG = 3;
static final int NO_DATA_ARG = 4;
static final int STRICT_NO_DATA_ARG = 5;
static final int SIMPLIFY_ARG = 6;
static final int SMOOTH_ARG = 7;
private static final String[] paramNames = {
"roi",
"band",
"levels",
"interval",
"nodata",
"strictNodata",
"simplify",
"smooth"
};
private static final Class[] paramClasses = {
javax.media.jai.ROI.class,
Integer.class,
Collection.class,
Number.class,
Collection.class,
Boolean.class,
Boolean.class,
Boolean.class
};
// package access for use by ContourOpImage
static final Object[] paramDefaults = {
(ROI) null,
Integer.valueOf(0),
(Collection) null,
(Number) null,
Arrays.asList(Double.NaN, Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY, Double.MAX_VALUE),
Boolean.TRUE,
Boolean.TRUE,
Boolean.FALSE,
};
/**
* Creates a new instance.
*/
public ContourDescriptor() {
super(new String[][]{
{"GlobalName", "Contour"},
{"LocalName", "Contour"},
{"Vendor", "org.jaitools.media.jai"},
{"Description", "Traces contours based on source image values"},
{"DocURL", "http://code.google.com/p/jaitools/"},
{"Version", "1.1.0"},
{"arg0Desc", paramNames[0] + " an optional ROI"},
{"arg1Desc", paramNames[1] + " (Integer, default=0) " +
"the source image band to process"},
{"arg2Desc", paramNames[2] + " (Collection<? extends Number>) " +
"values for which to generate contours"},
{"arg3Desc", paramNames[3] + " (Number) " +
"interval between contour values (ignored if levels arg is supplied)"},
{"arg4Desc", paramNames[4] + " (Collection) " +
"values to be treated as NO_DATA; elements can be Number and/or Range"},
{"arg5Desc", paramNames[5] + " (Boolean, default=true) " +
"if true, use strict NODATA exclusion; if false use accept some NODATA"},
{"arg6Desc", paramNames[6] + " (Boolean, default=true) " +
"whether to simplify contour lines by removing colinear vertices"},
{"arg7Desc", paramNames[7] + " (Boolean, default=false) " +
"whether to smooth contour lines using Bezier interpolation"}
},
new String[]{RenderedRegistryMode.MODE_NAME}, // supported modes
1, // number of sources
paramNames,
paramClasses,
paramDefaults,
null // valid values (none defined)
);
}
/**
* Validates supplied parameters.
*
* @param modeName the rendering mode
* @param pb the parameter block
* @param msg a {@code StringBuffer} to receive error messages
*
* @return {@code true} if parameters are valid; {@code false} otherwise
*/
@Override
protected boolean validateParameters(String modeName, ParameterBlock pb, StringBuffer msg) {
final String nodataErrorMsg =
"nodata parameter must be a Collection of Numbers and/or Ranges";
boolean ok = super.validateParameters(modeName, pb, msg);
if (ok) {
Collection levels = (Collection) pb.getObjectParameter(LEVELS_ARG);
Object objInterval = pb.getObjectParameter(INTERVAL_ARG);
if (levels == null || levels.isEmpty()) {
// No levels: check for a valid contour interval
if (objInterval == null) {
ok = false;
msg.append("One of levels or interval parameters must be supplied");
} else {
Double interval = ((Number) objInterval).doubleValue();
if (interval.isNaN() || interval.isInfinite()) {
ok = false;
msg.append("interval parameter must not be NaN or infinite");
}
}
} else {
// Levels parameter supplied
if (levels.isEmpty()) {
ok = false;
msg.append("levels parameter must be a Collection of one or more numbers");
}
}
Object objc = pb.getObjectParameter(NO_DATA_ARG);
if (objc != null) {
if (!(objc instanceof Collection)) {
msg.append(nodataErrorMsg);
ok = false;
} else {
Collection col = (Collection) objc;
for (Object oelem : col) {
if (!(oelem instanceof Number || oelem instanceof Range)) {
msg.append(nodataErrorMsg);
ok = false;
break;
}
}
}
}
}
return ok;
}
}
| 12,748 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ContourRIF.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/operator/ContourRIF.java | /*
* Copyright (c) 2010, Michael Bedward. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.nasa.gsfc.seadas.contour.operator;
import javax.media.jai.ROI;
import java.awt.*;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.awt.image.renderable.RenderedImageFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* The image factory for the Contour operator.
*
* @author Michael Bedward
* @since 1.1
* @version $Id$
*/
public class ContourRIF implements RenderedImageFactory {
/**
* Creates a new instance of ContourOpImage in the rendered layer.
*
* @param paramBlock specifies the source image and the parameters
* "roi", "band", "outsideValues" and "insideEdges"
*
* @param renderHints rendering hints (ignored)
*/
public RenderedImage create(ParameterBlock paramBlock,
RenderingHints renderHints) {
Object obj = null;
ROI roi = (ROI) paramBlock.getObjectParameter(ContourDescriptor.ROI_ARG);
int band = paramBlock.getIntParameter(ContourDescriptor.BAND_ARG);
List<Double> contourLevels = null;
Double interval = null;
Collection levels = (Collection) paramBlock.getObjectParameter(ContourDescriptor.LEVELS_ARG);
if (levels != null && !levels.isEmpty()) {
contourLevels = new ArrayList<Double>();
for (Object val : levels) {
contourLevels.add(((Number)val).doubleValue());
}
} else {
// No contour levels - use interval parameter
obj = paramBlock.getObjectParameter(ContourDescriptor.INTERVAL_ARG);
interval = ((Number)obj).doubleValue();
}
Collection noDataValues = (Collection) paramBlock.getObjectParameter(ContourDescriptor.NO_DATA_ARG);
Boolean strictNodata = (Boolean) paramBlock.getObjectParameter(ContourDescriptor.STRICT_NO_DATA_ARG);
Boolean simplify = (Boolean) paramBlock.getObjectParameter(ContourDescriptor.SIMPLIFY_ARG);
Boolean smooth = (Boolean) paramBlock.getObjectParameter(ContourDescriptor.SMOOTH_ARG);
return new ContourOpImage(paramBlock.getRenderedSource(0),
roi, band, contourLevels, interval, noDataValues,
strictNodata, simplify, smooth);
}
}
| 3,758 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
Segments.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/operator/Segments.java | /*
* Copyright (c) 2010, Michael Bedward. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.nasa.gsfc.seadas.contour.operator;
import org.jaitools.jts.Utils;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.operation.linemerge.LineMerger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* A container for the segments collected by ContourOpImage.
* It will return them as merged lines eventually applying simplification procedures
*
* @author Andrea Aime - GeoSolutions
* @since 1.1
* @version $Id$
*/
class Segments {
static final int MAX_SIZE = 16348; // this amounts to 130KB storage
boolean simplify;
double[] ordinates;
int idx = 0;
List<LineString> result = new ArrayList<LineString>();
public Segments(boolean simplify) {
this.simplify = simplify;
}
/**
* Adds a segment to the mix
* @param x1
* @param y1
* @param x2
* @param y2
*/
public void add(double x1, double y1, double x2, double y2) {
if(ordinates == null) {
ordinates = new double[512];
} else if((idx + 4) > ordinates.length) {
// reallocate
double[] temp = new double[ordinates.length * 2];
System.arraycopy(ordinates, 0, temp, 0, ordinates.length);
ordinates = temp;
}
ordinates[idx++] = x1;
ordinates[idx++] = y1;
ordinates[idx++] = x2;
ordinates[idx++] = y2;
if(idx >= MAX_SIZE) {
merge();
}
}
/**
* Returns the merged and eventually simplified segments
* @return
*/
public List<LineString> getMergedSegments() {
if(idx > 0) {
merge();
// release the part of the storage we don't need anymore
ordinates = null;
}
return result;
}
/**
* Merges and eventually simplifies all of the segments collected so far with the
* linestring collected so far
*/
void merge() {
// merge all the segments
LineMerger merger = new LineMerger();
for (int i = 0; i < idx;) {
Coordinate p1 = new Coordinate(ordinates[i++], ordinates[i++]);
Coordinate p2 = new Coordinate(ordinates[i++], ordinates[i++]);
if(!p1.equals2D(p2)) {
merger.add(Utils.getGeometryFactory().createLineString(new Coordinate[] {p1, p2}));
}
}
// reset the counter, we offloaded all segments
idx = 0;
// add to the mix all lines that have not been merged so far
// (we know linear rings are already complete so we skip them)
for (LineString ls : result) {
merger.add(ls);
}
// eventually simplify and add back the merged line strings
Collection<LineString> mergedLines = merger.getMergedLineStrings();
result.clear();
if(simplify) {
for (LineString merged : mergedLines) {
if(simplify) {
merged = Utils.removeCollinearVertices(merged);
}
result.add(merged);
}
} else {
result.addAll(mergedLines);
}
}
}
| 4,660 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ResourceInstallationUtils.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/util/ResourceInstallationUtils.java | package gov.nasa.gsfc.seadas.contour.util;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 9/5/13
* Time: 12:59 PM
* To change this template use File | Settings | File Templates.
*/
import org.esa.snap.core.util.ResourceInstaller;
import org.esa.snap.core.util.SystemUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Path;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 1/17/13
* Time: 2:56 PM
* To change this template use File | Settings | File Templates.
*/
public class ResourceInstallationUtils {
public static String CONTOUR_MODULE_NAME = "seadas-contour-operator";
public static String AUXDIR = "auxdata";
public static String CONTOUR_PATH = "gov/nasa/gsfc/seadas/contour/";
public static String AUXPATH = CONTOUR_PATH + "operator/" + AUXDIR + "/";
public static String ICON_PATH = CONTOUR_PATH + "ui/action/";
public static String getIconFilename(String icon, Class sourceClass) {
Path sourceUrl = ResourceInstaller.findModuleCodeBasePath(sourceClass);
String iconFilename = sourceUrl.toString() + ICON_PATH + icon;
return iconFilename;
}
public static void writeFileFromUrlOld(URL sourceUrl, File targetFile) throws IOException {
try {
InputStreamReader inputStreamReader = new InputStreamReader(sourceUrl.openStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
boolean exist = targetFile.createNewFile();
if (!exist) {
// file already exists
} else {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(targetFile));
String line;
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
}
bufferedWriter.close();
}
bufferedReader.close();
} catch (Exception e) {
throw new IOException("failed to write file from url: " + e.getMessage());
}
}
public static void writeFileFromUrl(URL sourceUrl, File targetFile) throws IOException {
HttpURLConnection connection = (HttpURLConnection) sourceUrl.openConnection();
connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream(targetFile);
FileCopy(in, out, 1024);
out.close();
}
public static void FileCopy(InputStream input, OutputStream output, int bufferSize) throws IOException {
byte[] buf = new byte[bufferSize];
int n = input.read(buf);
while (n >= 0) {
output.write(buf, 0, n);
n = input.read(buf);
}
output.flush();
}
public static File getTargetDir() {
File targetModuleDir = new File(SystemUtils.getApplicationDataDir(), CONTOUR_MODULE_NAME);
File targetDir = new File(targetModuleDir, AUXDIR);
return targetDir;
}
public static File getModuleDir(String moduleName) {
if (moduleName == null) {
return null;
}
return new File(SystemUtils.getApplicationDataDir(), moduleName);
}
public static File getTargetFile(String filename) {
File targetModuleDir = new File(SystemUtils.getApplicationDataDir(), CONTOUR_MODULE_NAME);
File targetDir = new File(targetModuleDir, AUXDIR);
File targetFile = new File(targetDir, filename);
return targetFile;
}
public static void installAuxdata(URL sourceUrl, String filename) throws IOException {
File targetFile = getTargetFile(filename);
try {
writeFileFromUrl(sourceUrl, targetFile);
} catch (IOException e) {
targetFile.delete();
throw new IOException();
}
}
// public static File installAuxdata(Class sourceClass, String filename) throws IOException {
// File targetFile = getTargetFile(filename);
//
// if (!targetFile.canRead()) {
// Path sourceUrl = ResourceInstaller.findModuleCodeBasePath(sourceClass);
// ResourceInstaller resourceInstaller = new ResourceInstaller(sourceUrl, AUXPATH, targetFile.getParentFile());
// try {
// resourceInstaller.install(filename, ProgressMonitor.NULL);
// } catch (Exception e) {
// throw new IOException("file failed: " + e.getMessage());
// }
// }
// return targetFile;
// }
}
| 4,622 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
CommonUtilities.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/util/CommonUtilities.java | package gov.nasa.gsfc.seadas.contour.util;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 5/30/14
* Time: 3:06 PM
* To change this template use File | Settings | File Templates.
*/
public class CommonUtilities {
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
}
| 575 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
Java2DConverter.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-contour-operator/src/main/java/gov/nasa/gsfc/seadas/contour/util/Java2DConverter.java | package gov.nasa.gsfc.seadas.contour.util;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 4/11/14
* Time: 6:14 PM
* To change this template use File | Settings | File Templates.
*/
import org.locationtech.jts.awt.GeometryCollectionShape;
import org.locationtech.jts.awt.PolygonShape;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import java.awt.*;
import java.awt.geom.*;
import java.util.ArrayList;
/**
* Converts JTS Geometry objects into Java 2D Shape objects
*/
public class Java2DConverter {
private static double POINT_MARKER_SIZE = 0.0;
private final AffineTransform pointConverter;
public Java2DConverter(AffineTransform pointConverter) {
this.pointConverter = pointConverter;
}
private Shape toShape(Polygon p) {
ArrayList holeVertexCollection = new ArrayList();
for (int j = 0; j < p.getNumInteriorRing(); j++) {
holeVertexCollection.add(toViewCoordinates(p.getInteriorRingN(j)
.getCoordinates()));
}
return new PolygonShape(toViewCoordinates(p.getExteriorRing()
.getCoordinates()), holeVertexCollection);
}
private Coordinate[] toViewCoordinates(Coordinate[] modelCoordinates) {
Coordinate[] viewCoordinates = new Coordinate[modelCoordinates.length];
for (int i = 0; i < modelCoordinates.length; i++) {
Point2D point2D = toViewPoint(modelCoordinates[i]);
viewCoordinates[i] = new Coordinate(point2D.getX(), point2D.getY());
}
return viewCoordinates;
}
private Shape toShape(GeometryCollection gc)
throws NoninvertibleTransformException {
GeometryCollectionShape shape = new GeometryCollectionShape();
for (int i = 0; i < gc.getNumGeometries(); i++) {
Geometry g = gc.getGeometryN(i);
shape.add(toShape(g));
}
return shape;
}
private GeneralPath toShape(MultiLineString mls)
throws NoninvertibleTransformException {
GeneralPath path = new GeneralPath();
for (int i = 0; i < mls.getNumGeometries(); i++) {
LineString lineString = (LineString) mls.getGeometryN(i);
path.append(toShape(lineString), false);
}
// BasicFeatureRenderer expects LineStrings and MultiLineStrings to be
// converted to GeneralPaths. [Jon Aquino]
return path;
}
private GeneralPath toShape(LineString lineString)
throws NoninvertibleTransformException {
GeneralPath shape = new GeneralPath();
Point2D viewPoint = toViewPoint(lineString.getCoordinateN(0));
shape.moveTo((double) viewPoint.getX(), (double) viewPoint.getY());
for (int i = 1; i < lineString.getNumPoints(); i++) {
viewPoint = toViewPoint(lineString.getCoordinateN(i));
shape.lineTo((double) viewPoint.getX(), (double) viewPoint.getY());
}
//BasicFeatureRenderer expects LineStrings and MultiLineStrings to be
//converted to GeneralPaths. [Jon Aquino]
return shape;
}
private Shape toShape(Point point) {
Rectangle2D.Double pointMarker = new Rectangle2D.Double(0.0, 0.0,
POINT_MARKER_SIZE, POINT_MARKER_SIZE);
Point2D viewPoint = toViewPoint(point.getCoordinate());
pointMarker.x = (viewPoint.getX() - (POINT_MARKER_SIZE / 2));
pointMarker.y = (viewPoint.getY() - (POINT_MARKER_SIZE / 2));
return pointMarker;
// GeneralPath path = new GeneralPath();
// return viewPoint;
}
private Point2D toViewPoint(Coordinate modelCoordinate) {
// Do the rounding now; don't rely on Java 2D rounding, because it
// seems to do it differently for drawing and filling, resulting in the
// draw
// being a pixel off from the fill sometimes. [Jon Aquino]
double x = modelCoordinate.x;
double y = modelCoordinate.y;
// x = Math.round(x);
// y = Math.round(y);
Point2D modelPoint = new Point2D.Double(x, y);
Point2D viewPoint = modelPoint;
if (pointConverter != null) {
viewPoint = pointConverter.transform(modelPoint, null);
}
return viewPoint;
}
/**
* If you pass in a common GeometryCollection, note that a Shape cannot
* preserve information gov.nasa.gsfc.seadas.about which elements are 1D and which are 2D. For
* example, if you pass in a GeometryCollection containing a ring and a
* disk, you cannot render them as such: if you use Graphics.fill, you'll
* get two disks, and if you use Graphics.draw, you'll get two rings.
* Solution: create Shapes for each element.
*/
public Shape toShape(Geometry geometry)
throws NoninvertibleTransformException {
if (geometry.isEmpty()) {
return new GeneralPath();
}
if (geometry instanceof Polygon) {
return toShape((Polygon) geometry);
}
if (geometry instanceof MultiPolygon) {
return toShape((MultiPolygon) geometry);
}
if (geometry instanceof LineString) {
return toShape((LineString)geometry);
}
if (geometry instanceof MultiLineString) {
return toShape((MultiLineString) geometry);
}
if (geometry instanceof Point) {
return toShape((Point) geometry);
}
// as of JTS 1.8, the only thing that this might be is a
// jts.geom.MultiPoint, because
// MultiPolygon and MultiLineString are caught above. [Frank Hardisty]
if (geometry instanceof GeometryCollection) {
return toShape((GeometryCollection) geometry);
}
throw new IllegalArgumentException("Unrecognized Geometry class: "
+ geometry.getClass());
}
public static Geometry toMultiGon(GeneralPath path) {
// TODO Auto-generated method stub
return null;
}
}
| 6,108 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
BathymetryOpTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/test/java/gov/nasa/gsfc/seadas/bathymetry/operator/BathymetryOpTest.java | package gov.nasa.gsfc.seadas.bathymetry.operator;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.dataop.maptransf.Datum;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.graph.GraphException;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import static org.esa.snap.core.util.Debug.assertNotNull;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
/**
* Created by knowles on 5/31/17.
*/
public class BathymetryOpTest {
@Test
public void testInstantiationWithGPF() throws GraphException {
GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis();
HashMap<String, Object> parameters = new HashMap<>();
final Product sp = createTestProduct(100, 100);
assertNotNull(sp.getSceneGeoCoding());
parameters.put("resolution", "1855");
parameters.put("filename", "ETOPO1_ocssw.nc");
Product tp = GPF.createProduct("BathymetryOp", parameters, sp);
assertNotNull(tp);
assertEquals(100, tp.getSceneRasterWidth());
assertEquals(50, tp.getSceneRasterHeight());
}
private Product createTestProduct(int w, int h) {
Product product = new Product("p", "t", w, h);
Placemark[] gcps = {
Placemark.createPointPlacemark(GcpDescriptor.getInstance(), "p1", "p1", "", new PixelPos(0.5f, 0.5f), new GeoPos(10, -10),
null),
Placemark.createPointPlacemark(GcpDescriptor.getInstance(), "p2", "p2", "", new PixelPos(w - 0.5f, 0.5f), new GeoPos(10, 10),
null),
Placemark.createPointPlacemark(GcpDescriptor.getInstance(), "p3", "p3", "", new PixelPos(w - 0.5f, h - 0.5f), new GeoPos(-10, 10),
null),
Placemark.createPointPlacemark(GcpDescriptor.getInstance(), "p4", "p4", "", new PixelPos(0.5f, h - 0.5f), new GeoPos(-10, -10),
null),
};
product.setSceneGeoCoding(new GcpGeoCoding(GcpGeoCoding.Method.POLYNOMIAL1, gcps, w, h, Datum.WGS_84));
Band band1 = product.addBand("radiance_1", ProductData.TYPE_INT32);
int[] intValues = new int[w * h];
Arrays.fill(intValues, 1);
band1.setData(ProductData.createInstance(intValues));
Band band2 = product.addBand("radiance_2", ProductData.TYPE_FLOAT32);
float[] floatValues = new float[w * h];
Arrays.fill(floatValues, 2.5f);
band2.setData(ProductData.createInstance(floatValues));
Band band3 = product.addBand("radiance_3", ProductData.TYPE_INT16);
band3.setScalingFactor(0.5);
short[] shortValues = new short[w * h];
Arrays.fill(shortValues, (short) 6);
band3.setData(ProductData.createInstance(shortValues));
return product;
}
} | 2,860 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ShapeFileRasterizerTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/test/java/gov/nasa/gsfc/seadas/bathymetry/util/ShapeFileRasterizerTest.java | package gov.nasa.gsfc.seadas.bathymetry.util;
import gov.nasa.gsfc.seadas.bathymetry.operator.BathymetryUtils;
import junit.framework.TestCase;
import org.junit.Test;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipFile;
import static org.esa.snap.core.util.Debug.assertNotNull;
public class ShapeFileRasterizerTest extends TestCase {
@Test
public void testImageCreation() throws Exception {
final File targetDir = new File("");
final ShapeFileRasterizer rasterizer = new ShapeFileRasterizer(targetDir);
final URL shapeUrl = getClass().getResource("e000n05f.shp");
final File shapeFile = new File(shapeUrl.getFile());
final int resolution = BathymetryUtils.computeSideLength(150);
final BufferedImage image = rasterizer.createImage(shapeFile, resolution);
// test some known values
final Raster imageData = image.getData();
assertEquals(1, imageData.getSample(526, 92, 0));
assertEquals(0, imageData.getSample(312, 115, 0));
assertEquals(1, imageData.getSample(141, 187, 0));
assertEquals(0, imageData.getSample(197, 27, 0));
assertEquals(1, imageData.getSample(308, 701, 0));
}
@Test
public void testFromZip() throws Exception {
final File targetDir = new File("");
final ShapeFileRasterizer rasterizer = new ShapeFileRasterizer(targetDir);
final URL shapeUrl = getClass().getResource("e000n05f.zip");
final int tileSize = BathymetryUtils.computeSideLength(150);
final List<File> tempFiles;
final ZipFile zipFile = new ZipFile(shapeUrl.getFile());
try {
tempFiles = rasterizer.createTempFiles(zipFile);
} finally {
zipFile.close();
}
BufferedImage image = null;
for (File file : tempFiles) {
if (file.getName().endsWith("shp")) {
image = rasterizer.createImage(file, tileSize);
}
}
assertNotNull(image);
// // test some known values
final Raster imageData = image.getData();
assertEquals(1, imageData.getSample(526, 92, 0));
assertEquals(0, imageData.getSample(312, 115, 0));
assertEquals(1, imageData.getSample(141, 187, 0));
assertEquals(0, imageData.getSample(197, 27, 0));
assertEquals(1, imageData.getSample(308, 701, 0));
}
}
| 2,547 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
LandMaskRasterCreatorTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/test/java/gov/nasa/gsfc/seadas/bathymetry/util/LandMaskRasterCreatorTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.bathymetry.util;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import static org.junit.Assert.assertEquals;
/**
* @author Thomas Storm
*/
@SuppressWarnings({"ReuseOfLocalVariable"})
public class LandMaskRasterCreatorTest {
@Test
public void testMixedFile() throws Exception {
final BufferedImage image = ImageIO.read(getClass().getResource("156-12.png"));
int sample = image.getData().getSample(220, 40, 0);
assertEquals(0, sample);
sample = image.getData().getSample(220, 41, 0);
assertEquals(1, sample);
sample = image.getData().getSample(187, 89, 0);
assertEquals(0, sample);
sample = image.getData().getSample(186, 89, 0);
assertEquals(1, sample);
sample = image.getData().getSample(188, 89, 0);
assertEquals(1, sample);
}
@Test
public void testAllWaterFile() throws Exception {
final BufferedImage image = ImageIO.read(getClass().getResource("195-10.png"));
Raster imageData = image.getData();
for (int x = 0; x < imageData.getWidth(); x++) {
for (int y = 0; y < imageData.getHeight(); y++) {
assertEquals(0, imageData.getSample(x, y, 0));
}
}
}
@Test
public void testAllLandFile() throws Exception {
final BufferedImage image = ImageIO.read(getClass().getResource("92-10.png"));
Raster imageData = image.getData();
for (int x = 0; x < imageData.getWidth(); x++) {
for (int y = 0; y < imageData.getHeight(); y++) {
assertEquals(1, imageData.getSample(x, y, 0));
}
}
}
}
| 2,482 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
BathymetryAction.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/BathymetryAction.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import com.bc.ceres.glevel.MultiLevelImage;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import gov.nasa.gsfc.seadas.bathymetry.operator.BathymetryOp;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.*;
import org.openide.util.actions.Presenter;
import javax.media.jai.ImageLayout;
import javax.media.jai.JAI;
import javax.media.jai.operator.FormatDescriptor;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.util.HashMap;
import java.util.Map;
/**
* This registers an action which calls the "bathymetry" Operator
*
* @author Danny Knowles
* @author Aynur Abdurazik
* @author Bing Yang
*/
@ActionID(category = "Processing", id = "gov.nasa.gsfc.seadas.bathymetry.ui.BathymetryAction" )
@ActionRegistration(displayName = "#CTL_BathymetryAction_Text", lazy = false)
// iconBase = "gov/nasa/gsfc/seadas/bathymetry/ui/icons/bathymetry.png")
@ActionReferences({
@ActionReference(path = "Menu/SeaDAS-Toolbox/General Tools", position = 300),
@ActionReference(path = "Menu/Raster/Masks"),
@ActionReference(path = "Toolbars/SeaDAS Toolbox", position = 20)
})
@NbBundle.Messages({
"CTL_BathymetryAction_Text=Bathymetry",
"CTL_BathymetryAction_Description=Add bathymetry-elevation band and mask."
})
public final class BathymetryAction extends AbstractSnapAction
implements LookupListener, Presenter.Menu, Presenter.Toolbar {
public static final String COMMAND_ID = "Bathymetry & Elevation";
public static final String TOOL_TIP = "Add bathymetry-elevation band and mask";
public static final String SMALLICON = "gov/nasa/gsfc/seadas/bathymetry/ui/icons/bathymetry.png";
public static final String LARGEICON = "gov/nasa/gsfc/seadas/bathymetry/ui/icons/bathymetry24.png";
public static final String TARGET_TOOL_BAR_NAME = "layersToolBar";
public static final String BATHYMETRY_PRODUCT_NAME = "BathymetryOp";
private final Lookup lookup;
private final Lookup.Result<ProductNode> viewResult;
public BathymetryAction() {
this(null);
}
public BathymetryAction(Lookup lookup) {
putValue(ACTION_COMMAND_KEY, getClass().getName());
putValue(SELECTED_KEY, false);
putValue(NAME, Bundle.CTL_BathymetryAction_Text());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon(SMALLICON, false));
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon(LARGEICON, false));
putValue(SHORT_DESCRIPTION, Bundle.CTL_BathymetryAction_Description());
this.lookup = lookup != null ? lookup : Utilities.actionsGlobalContext();
this.viewResult = this.lookup.lookupResult(ProductNode.class);
this.viewResult.addLookupListener(WeakListeners.create(LookupListener.class, this, viewResult));
updateEnabledState();
}
// @Override
// public void start(final SnapApp snapApp) {
// final ExecCommand action = snapApp.getCommandManager().createExecCommand(COMMAND_ID,
// new ToolbarCommand(visatApp));
//
// String iconFilename = ResourceInstallationUtils.getIconFilename(ICON, BathymetryVPI.class);
//
// try {
// URL iconUrl = new URL(iconFilename);
// ImageIcon imageIcon = new ImageIcon(iconUrl);
// action.setLargeIcon(imageIcon);
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
//
//
// final AbstractButton lwcButton = visatApp.createToolButton(COMMAND_ID);
// lwcButton.setToolTipText(TOOL_TIP);
//
// visatApp.getMainFrame().addWindowListener(new WindowAdapter() {
// @Override
// public void windowOpened(WindowEvent e) {
// CommandBar layersBar = visatApp.getToolBar(TARGET_TOOL_BAR_NAME);
// layersBar.add(lwcButton);
// }
// });
//
// final AbstractButton lwcButton = visatApp.createToolButton(COMMAND_ID);
// lwcButton.setToolTipText(TOOL_TIP);
//
// final AbstractButton lwcButton2 = visatApp.createToolButton(COMMAND_ID);
// lwcButton2.setToolTipText(TOOL_TIP);
//
// visatApp.getMainFrame().addWindowListener(new WindowAdapter() {
// @Override
// public void windowOpened(WindowEvent e) {
// CommandBar layersBar = visatApp.getToolBar(TARGET_TOOL_BAR_NAME);
// if (layersBar != null) {
// layersBar.add(lwcButton);
// }
//
//
// CommandBar seadasDefaultBar = visatApp.getToolBar("seadasDeluxeToolsToolBar");
// if (seadasDefaultBar != null) {
// seadasDefaultBar.add(lwcButton2);
// }
// }
//
// });
//
//
// }
private void showBathymetry(final SnapApp snapApp) {
final Product product = snapApp.getSelectedProduct(SnapApp.SelectionSourceHint.AUTO);
if (product != null) {
final ProductNodeGroup<Mask> maskGroup = product.getMaskGroup();
final ProductNodeGroup<Band> bandGroup = product.getBandGroup();
/*
A simple boolean switch to enable this to run with or without the intermediate user dialogs
*/
boolean useDialogs = true;
final BathymetryData bathymetryData = new BathymetryData();
if (!useDialogs) {
bathymetryData.setCreateMasks(true);
}
/*
Determine whether these auxilliary masks and associated products have already be created.
This would be the case when run a second time on the same product.
*/
final boolean[] masksCreated = {false};
final boolean[] bandCreated = {false};
for (String name : maskGroup.getNodeNames()) {
if (name.equals(bathymetryData.getMaskName())) {
masksCreated[0] = true;
}
}
for (String name : bandGroup.getNodeNames()) {
if (name.equals(BathymetryOp.BATHYMETRY_BAND_NAME)) {
bandCreated[0] = true;
}
}
/*
For the case where this is being run a second time, prompt the user to determine whether to delete
and re-create the products and masks.
*/
if (masksCreated[0]) {
bandCreated[0] = true;
if (useDialogs) {
bathymetryData.setDeleteMasks(false);
BathymetryDialog bathymetryDialog = new BathymetryDialog(bathymetryData, masksCreated[0], bandCreated[0]);
bathymetryDialog.setVisible(true);
bathymetryDialog.dispose();
}
if (bathymetryData.isDeleteMasks() || !useDialogs) {
masksCreated[0] = false;
// for (String name : bandGroup.getNodeNames()) {
// if (
// name.equals(bathymetryData.getBathymetryBandName())) {
// // Band bathymetryBand = bandGroup.get(name);
//
//// product.getBand(name).dispose();
//
// bandGroup.remove(bandGroup.get(name));
//// product.removeBand(bathymetryBand);
//
// }
// }
for (String name : maskGroup.getNodeNames()) {
if (name.equals(bathymetryData.getMaskName())) {
// maskGroup.get(name).dispose();
maskGroup.remove(maskGroup.get(name));
}
}
}
}
if (!masksCreated[0]) {
if (useDialogs) {
bathymetryData.setCreateMasks(false);
BathymetryDialog bathymetryDialog = new BathymetryDialog(bathymetryData, masksCreated[0], bandCreated[0]);
bathymetryDialog.setVisible(true);
}
if (bathymetryData.isCreateMasks()) {
final SourceFileInfo sourceFileInfo = bathymetryData.getSourceFileInfo();
if (sourceFileInfo.isEnabled() && sourceFileInfo.getExistingFile() != null) {
final String[] msg = {"Creating bathymetry band and mask"};
if (bandCreated[0] == true) {
msg[0] = "recreating bathymetry mask";
}
ProgressMonitorSwingWorker pmSwingWorker = new ProgressMonitorSwingWorker(snapApp.getMainFrame(),
msg[0]) {
@Override
protected Void doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception {
pm.beginTask(msg[0], 2);
try {
if (bandCreated[0] != true) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("resolution", sourceFileInfo.getResolution(SourceFileInfo.Unit.METER));
parameters.put("filename", sourceFileInfo.getExistingFile().getName());
/*
Create a new product, which will contain the bathymetry band, then add this band to current product.
*/
Product bathymetryProduct = GPF.createProduct(BATHYMETRY_PRODUCT_NAME, parameters, product);
if (bathymetryData.isCreateTopographyBand()) {
Band topographyBand = bathymetryProduct.getBand(BathymetryOp.TOPOGRAPHY_BAND_NAME);
reformatSourceImage(topographyBand, new ImageLayout(product.getBandAt(0).getSourceImage()));
topographyBand.setName(BathymetryOp.TOPOGRAPHY_BAND_NAME);
product.addBand(topographyBand);
}
if (bathymetryData.isCreateElevationBand()) {
Band elevationBand = bathymetryProduct.getBand(BathymetryOp.ELEVATION_BAND_NAME);
reformatSourceImage(elevationBand, new ImageLayout(product.getBandAt(0).getSourceImage()));
elevationBand.setName(BathymetryOp.ELEVATION_BAND_NAME);
product.addBand(elevationBand);
}
Band bathymetryBand = bathymetryProduct.getBand(BathymetryOp.BATHYMETRY_BAND_NAME);
reformatSourceImage(bathymetryBand, new ImageLayout(product.getBandAt(0).getSourceImage()));
bathymetryBand.setName(BathymetryOp.BATHYMETRY_BAND_NAME);
product.addBand(bathymetryBand);
}
pm.worked(1);
Mask bathymetryMask = Mask.BandMathsType.create(
bathymetryData.getMaskName(),
bathymetryData.getMaskDescription(),
product.getSceneRasterWidth(),
product.getSceneRasterHeight(),
bathymetryData.getMaskMath(),
bathymetryData.getMaskColor(),
bathymetryData.getMaskTransparency());
maskGroup.add(bathymetryMask);
pm.worked(1);
String[] bandNames = product.getBandNames();
for (String bandName : bandNames) {
RasterDataNode raster = product.getRasterDataNode(bandName);
if (bathymetryData.isShowMaskAllBands()) {
raster.getOverlayMaskGroup().add(bathymetryMask);
}
}
} finally {
pm.done();
}
return null;
}
};
pmSwingWorker.executeWithBlocking();
} else {
SimpleDialogMessage dialog = new SimpleDialogMessage(null, "Cannot Create Masks: Resolution File Doesn't Exist");
dialog.setVisible(true);
dialog.setEnabled(true);
}
}
}
}
}
private void reformatSourceImage(Band band, ImageLayout imageLayout) {
RenderingHints renderingHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, imageLayout);
MultiLevelImage sourceImage = band.getSourceImage();
Raster r = sourceImage.getData();
DataBuffer db = r.getDataBuffer();
int t = db.getDataType();
int dataType = sourceImage.getData().getDataBuffer().getDataType();
RenderedImage newImage = FormatDescriptor.create(sourceImage, dataType, renderingHints);
band.setSourceImage(newImage);
}
// private class ToolbarCommand extends CommandAdapter {
// private final VisatApp visatApp;
// public ToolbarCommand(VisatApp visatApp) {
// this.visatApp = visatApp;
// }
@Override
public void actionPerformed(ActionEvent e) {
showBathymetry(SnapApp.getDefault());
}
@Override
public JMenuItem getMenuPresenter() {
JMenuItem menuItem = new JMenuItem(this);
menuItem.setIcon(null);
return menuItem;
}
@Override
public Component getToolbarPresenter() {
JButton button = new JButton(this);
button.setText(null);
button.setIcon(ImageUtilities.loadImageIcon(LARGEICON,false));
return button;
}
@Override
public void resultChanged(LookupEvent ignored) {
updateEnabledState();
}
protected void updateEnabledState() {
final Product selectedProduct = SnapApp.getDefault().getSelectedProduct(SnapApp.SelectionSourceHint.AUTO);
boolean productSelected = selectedProduct != null;
boolean hasBands = false;
boolean hasGeoCoding = false;
if (productSelected) {
hasBands = selectedProduct.getNumBands() > 0;
hasGeoCoding = selectedProduct.getSceneGeoCoding() != null;
}
super.setEnabled(!viewResult.allInstances().isEmpty() && hasBands && hasGeoCoding);
}
}
// @Override
// public void updateState(CommandEvent event) {
// Product selectedProduct = visatApp.getSelectedProduct();
// boolean productSelected = selectedProduct != null;
// boolean hasBands = false;
// boolean hasGeoCoding = false;
// if (productSelected) {
// hasBands = selectedProduct.getNumBands() > 0;
// hasGeoCoding = selectedProduct.getGeoCoding() != null;
// }
// event.getCommand().setEnabled(productSelected && hasBands && hasGeoCoding);
// }
// }
//}
| 16,348 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MaskEnabledAllBandsCheckbox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/MaskEnabledAllBandsCheckbox.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 10:27 AM
* To change this template use File | Settings | File Templates.
*/
public class MaskEnabledAllBandsCheckbox {
private BathymetryData bathymetryData;
private JLabel jLabel;
private JCheckBox jCheckBox = new JCheckBox();
private static String DEFAULT_NAME = "Enabled in All Bands";
private static String DEFAULT_TOOLTIPS = "Set Bathymetry Mask Enabled in All Bands";
public MaskEnabledAllBandsCheckbox(BathymetryData bathymetryData) {
this.bathymetryData = bathymetryData;
jLabel = new JLabel(DEFAULT_NAME);
jLabel.setToolTipText(DEFAULT_TOOLTIPS);
jCheckBox.setSelected(bathymetryData.isShowMaskAllBands());
addControlListeners();
}
private void addControlListeners() {
jCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
bathymetryData.setShowMaskAllBands(jCheckBox.isSelected());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JCheckBox getjCheckBox() {
return jCheckBox;
}
}
| 1,352 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MaskColorComboBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/MaskColorComboBox.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import org.openide.awt.ColorComboBox;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 10:57 AM
* To change this template use File | Settings | File Templates.
*/
public class MaskColorComboBox {
private BathymetryData bathymetryData;
private JLabel jLabel;
private ColorComboBox colorExComboBox = new ColorComboBox();
public MaskColorComboBox(BathymetryData bathymetryData) {
this.bathymetryData = bathymetryData;
jLabel = new JLabel("Mask Color");
jLabel.setToolTipText("set mask color");
colorExComboBox.setSelectedColor(new Color(225,225,225));
colorExComboBox.setPreferredSize(colorExComboBox.getPreferredSize());
colorExComboBox.setMinimumSize(colorExComboBox.getPreferredSize());
colorExComboBox.setSelectedColor((bathymetryData.getMaskColor()));
addControlListeners();
}
private void addControlListeners() {
colorExComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
bathymetryData.setMaskColor(colorExComboBox.getSelectedColor());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JComboBox getColorExComboBox() {
return colorExComboBox;
}
}
| 1,521 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MaskTransparencySpinner.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/MaskTransparencySpinner.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.text.DecimalFormat;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 9:20 AM
* To change this template use File | Settings | File Templates.
*/
public class MaskTransparencySpinner {
private BathymetryData bathymetryData;
private JLabel jLabel;
private JSpinner jSpinner = new JSpinner();
public MaskTransparencySpinner(BathymetryData bathymetryData) {
this.bathymetryData = bathymetryData;
jLabel = new JLabel("Mask Transparency");
jLabel.setToolTipText("set mask transparency");
jSpinner.setModel(new SpinnerNumberModel(100, 0, 100, 100));
jSpinner.setPreferredSize(jSpinner.getPreferredSize());
jSpinner.setSize(jSpinner.getPreferredSize());
jSpinner.setModel(new SpinnerNumberModel(bathymetryData.getMaskTransparency(), 0.0, 1.0, 0.1));
JSpinner.NumberEditor editor = (JSpinner.NumberEditor) jSpinner.getEditor();
DecimalFormat format = editor.getFormat();
format.setMinimumFractionDigits(1);
addControlListeners();
}
private void addControlListeners() {
jSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent changeEvent) {
bathymetryData.setMaskTransparency((Double) jSpinner.getValue());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JSpinner getjSpinner() {
return jSpinner;
}
}
| 1,665 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
TopographyBandCreateCheckbox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/TopographyBandCreateCheckbox.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 10:27 AM
* To change this template use File | Settings | File Templates.
*/
public class TopographyBandCreateCheckbox {
private BathymetryData bathymetryData;
private JLabel jLabel;
private JCheckBox jCheckBox = new JCheckBox();
private static String DEFAULT_NAME = "Create topography band";
private static String DEFAULT_TOOLTIPS = "Note: this can take longer to run";
public TopographyBandCreateCheckbox(BathymetryData bathymetryData) {
this.bathymetryData = bathymetryData;
jLabel = new JLabel(DEFAULT_NAME);
jLabel.setToolTipText(DEFAULT_TOOLTIPS);
jCheckBox.setSelected(bathymetryData.isCreateTopographyBand());
addControlListeners();
}
private void addControlListeners() {
jCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
bathymetryData.setCreateTopographyBand(jCheckBox.isSelected());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JCheckBox getjCheckBox() {
return jCheckBox;
}
}
| 1,356 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
SourceFileInfo.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/SourceFileInfo.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import gov.nasa.gsfc.seadas.bathymetry.operator.BathymetryOp;
import gov.nasa.gsfc.seadas.bathymetry.util.ResourceInstallationUtils;
import java.io.File;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/5/12
* Time: 9:53 AM
* To change this template use File | Settings | File Templates.
*/
public class SourceFileInfo {
public enum Unit {
METER("m"),
KILOMETER("km");
private Unit(String name) {
this.name = name;
}
private final String name;
public String toString() {
return name;
}
}
private int resolution;
private Unit unit;
private String description;
private File file;
private boolean status;
private String statusMessage;
public SourceFileInfo(int resolution, Unit unit, File file) {
setUnit(unit);
setResolution(resolution);
setFile(file);
setDescription();
}
// public SourceFileInfo(int resolution, Unit unit, String filename) {
// setUnit(unit);
// setResolution(resolution);
// setFile(filename);
// setDescription();
// }
public int getResolution() {
return resolution;
}
public int getResolution(Unit unit) {
// resolution is returned in units of meters
if (unit == getUnit()) {
return resolution;
} else if (unit == Unit.METER && getUnit() == Unit.KILOMETER) {
return resolution * 1000;
} else if (unit == Unit.KILOMETER && getUnit() == Unit.METER) {
float x = resolution / 1000;
return Math.round(x);
}
return resolution;
}
private void setResolution(int resolution) {
this.resolution = resolution;
}
public Unit getUnit() {
return unit;
}
private void setUnit(Unit unit) {
this.unit = unit;
}
public String getDescription() {
return description;
}
private void setDescription() {
if (isEnabled()) {
String core = "Filename=" + getExistingFile();
this.description = "<html>" + core + "</html>";
} else {
String core = "Filename=" + getAltFile();
this.description = "<html>" + core + "<br> NOTE: this file is not currently installed -- see help</html>";
}
}
public File getFile() {
if (file == null) {
return null;
}
return file;
}
public File getExistingFile() {
if (getFile() == null) {
return null;
}
if (getFile().exists()) {
return getFile();
}
if (getAltFile() != null && getAltFile().exists()) {
return getAltFile();
}
return null;
}
private void setFile(File file) {
this.file = file;
setStatus(true, null);
}
public File getAltFile() {
File altFile = ResourceInstallationUtils.getTargetFile(file.getName());
return altFile;
}
public boolean isEnabled() {
if (getExistingFile() == null) {
return false;
}
return getStatus();
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public void setStatus(boolean status, String statusMessage) {
this.status = status;
this.statusMessage = statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public String getStatusMessage() {
return statusMessage;
}
public boolean getStatus() {
return status;
}
public String toString() {
if (file == null) {
return "";
}
return file.getName();
}
}
| 3,945 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
FileInstallRunnable.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/FileInstallRunnable.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import gov.nasa.gsfc.seadas.bathymetry.util.ResourceInstallationUtils;
import java.io.IOException;
import java.net.URL;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 2/18/13
* Time: 4:07 PM
* To change this template use File | Settings | File Templates.
*/
class FileInstallRunnable implements Runnable {
URL sourceUrl;
BathymetryData bathymetryData;
SourceFileInfo sourceFileInfo;
String filename;
boolean valid = true;
public FileInstallRunnable(URL sourceUrl, String filename, SourceFileInfo sourceFileInfo, BathymetryData bathymetryData) {
if (sourceUrl== null || filename == null || sourceFileInfo == null || bathymetryData == null) {
valid = false;
return;
}
this.sourceUrl = sourceUrl;
this.sourceFileInfo = sourceFileInfo;
this.bathymetryData = bathymetryData;
this.filename = filename;
}
public void run() {
if (!valid) {
return;
}
try {
ResourceInstallationUtils.installAuxdata(sourceUrl, filename);
} catch (IOException e) {
sourceFileInfo.setStatus(false, e.getMessage());
}
bathymetryData.fireEvent(BathymetryData.NOTIFY_USER_FILE_INSTALL_RESULTS_EVENT, null, sourceFileInfo);
}
}
| 1,361 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
BathymetryDialog.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/BathymetryDialog.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import gov.nasa.gsfc.seadas.bathymetry.operator.BathymetryOp;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.openide.util.HelpCtx;
import javax.help.HelpBroker;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
//import org.esa.beam.framework.help.HelpSys;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/5/12
* Time: 8:46 AM
* To change this template use File | Settings | File Templates.
*/
class BathymetryDialog extends JDialog {
private BathymetryData bathymetryData = null;
private Component helpButton = null;
private HelpBroker helpBroker = null;
private final static String HELP_ID = "bathymetry";
private final static String HELP_ICON = "icons/Help24.gif";
public BathymetryDialog(BathymetryData bathymetryData, boolean masksCreated, boolean bandCreated) {
this.bathymetryData = bathymetryData;
helpButton = getHelpButton(HELP_ID);
if (masksCreated) {
createNotificationUI();
} else {
createBathymetryUI(bandCreated);
}
}
protected AbstractButton getHelpButton(String helpId) {
if (helpId != null) {
final AbstractButton helpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon(HELP_ICON),
false);
helpButton.setToolTipText("Help.");
helpButton.setName("helpButton");
helpButton.addActionListener(e -> getHelpCtx(helpId).display());
return helpButton;
}
return null;
}
public HelpCtx getHelpCtx(String helpId) {
return new HelpCtx(helpId);
}
public final void createNotificationUI() {
JButton createMasks = new JButton("Recreate Bathymetry Mask");
createMasks.setPreferredSize(createMasks.getPreferredSize());
createMasks.setMinimumSize(createMasks.getPreferredSize());
createMasks.setMaximumSize(createMasks.getPreferredSize());
createMasks.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
bathymetryData.setDeleteMasks(true);
dispose();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.setPreferredSize(cancelButton.getPreferredSize());
cancelButton.setMinimumSize(cancelButton.getPreferredSize());
cancelButton.setMaximumSize(cancelButton.getPreferredSize());
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
JLabel filler = new JLabel(" ");
JPanel buttonsJPanel = new JPanel(new GridBagLayout());
buttonsJPanel.add(cancelButton,
new ExGridBagConstraints(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
buttonsJPanel.add(filler,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
buttonsJPanel.add(createMasks,
new ExGridBagConstraints(2, 0, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
buttonsJPanel.add(helpButton,
new ExGridBagConstraints(3, 0, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
JLabel jLabel = new JLabel("Bathymetry has already been created for this product");
JPanel jPanel = new JPanel(new GridBagLayout());
jPanel.add(jLabel,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
jPanel.add(buttonsJPanel,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
add(jPanel);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("Create Bathymetry Mask and Elevation Bands");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setPreferredSize(getPreferredSize());
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setSize(getPreferredSize());
}
public final void createBathymetryUI(boolean bandCreated) {
final int rightInset = 5;
final TopographyBandCreateCheckbox topographyBandCreateCheckbox = new TopographyBandCreateCheckbox(bathymetryData);
final ElevationBandCreateCheckbox elevationBandCreateCheckbox = new ElevationBandCreateCheckbox(bathymetryData);
final MaskEnabledAllBandsCheckbox maskEnabledAllBandsCheckbox = new MaskEnabledAllBandsCheckbox(bathymetryData);
final MaskTransparencySpinner maskTransparencySpinner = new MaskTransparencySpinner(bathymetryData);
final MaskColorComboBox maskColorComboBox = new MaskColorComboBox(bathymetryData);
final MaskMaxDepthTextfield maskMaxDepthTextfield = new MaskMaxDepthTextfield(bathymetryData);
final MaskMinDepthTextfield maskMinDepthTextfield = new MaskMinDepthTextfield(bathymetryData);
final boolean[] fileSelectorEnabled = {true};
if (bandCreated) {
fileSelectorEnabled[0] = false;
} else {
fileSelectorEnabled[0] = true;
}
final ResolutionComboBox resolutionComboBox = new ResolutionComboBox(bathymetryData);
JPanel resolutionSamplingPanel = new JPanel(new GridBagLayout());
resolutionSamplingPanel.setBorder(BorderFactory.createTitledBorder(""));
if (fileSelectorEnabled[0]) {
resolutionSamplingPanel.add(resolutionComboBox.getjLabel(),
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
JComboBox jComboBox = resolutionComboBox.getjComboBox();
jComboBox.setEnabled(fileSelectorEnabled[0]);
bathymetryData.addPropertyChangeListener(BathymetryData.PROMPT_REQUEST_TO_INSTALL_FILE_EVENT, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (!bathymetryData.isInstallingFile()) {
SourceFileInfo sourceFileInfo = (SourceFileInfo) resolutionComboBox.getjComboBox().getSelectedItem();
InstallBathymetryFileDialog dialog = new InstallBathymetryFileDialog(bathymetryData, sourceFileInfo, InstallBathymetryFileDialog.Step.INSTALLATION);
dialog.setVisible(true);
dialog.setEnabled(true);
}
}
});
resolutionSamplingPanel.add(jComboBox,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
} else {
resolutionSamplingPanel.add(new JLabel("Note: Cannot recreate a different band, only a different mask"),
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
}
JTextField maskNameTextfield = new JTextField(bathymetryData.getMaskName());
maskNameTextfield.setEditable(false);
maskNameTextfield.setEnabled(true);
maskNameTextfield.setToolTipText("Name of the mask to be created (this field is not editable)");
JTextField bathymetryBandNameTextfield = new JTextField(BathymetryOp.BATHYMETRY_BAND_NAME);
bathymetryBandNameTextfield.setEditable(false);
bathymetryBandNameTextfield.setEnabled(true);
bathymetryBandNameTextfield.setToolTipText("Name of the band to be created (this field is not editable)");
JTextField topographyBandNameTextfield = new JTextField(BathymetryOp.TOPOGRAPHY_BAND_NAME);
topographyBandNameTextfield.setEditable(false);
topographyBandNameTextfield.setEnabled(true);
topographyBandNameTextfield.setToolTipText("Name of the band to be created (this field is not editable)");
JTextField elevationBandNameTextfield = new JTextField(BathymetryOp.ELEVATION_BAND_NAME);
elevationBandNameTextfield.setEditable(false);
elevationBandNameTextfield.setEnabled(true);
elevationBandNameTextfield.setToolTipText("Name of the band to be created (this field is not editable)");
JPanel maskJPanel = new JPanel(new GridBagLayout());
maskJPanel.setBorder(BorderFactory.createTitledBorder("Bathymetry Mask Parameters"));
int gridy = 0;
maskJPanel.add(new JLabel("Mask Name"),
new ExGridBagConstraints(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
maskJPanel.add(maskNameTextfield,
new ExGridBagConstraints(1, gridy, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
gridy++;
maskJPanel.add(maskColorComboBox.getjLabel(),
new ExGridBagConstraints(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
maskJPanel.add(maskColorComboBox.getColorExComboBox(),
new ExGridBagConstraints(1, gridy, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
gridy++;
maskJPanel.add(maskTransparencySpinner.getjLabel(),
new ExGridBagConstraints(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
maskJPanel.add(maskTransparencySpinner.getjSpinner(),
new ExGridBagConstraints(1, gridy, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
gridy++;
maskJPanel.add(maskMinDepthTextfield.getjLabel(),
new ExGridBagConstraints(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
maskJPanel.add(maskMinDepthTextfield.getjTextField(),
new ExGridBagConstraints(1, gridy, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
gridy++;
maskJPanel.add(maskMaxDepthTextfield.getjLabel(),
new ExGridBagConstraints(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
maskJPanel.add(maskMaxDepthTextfield.getjTextField(),
new ExGridBagConstraints(1, gridy, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
gridy++;
maskJPanel.add(maskEnabledAllBandsCheckbox.getjLabel(),
new ExGridBagConstraints(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
maskJPanel.add(maskEnabledAllBandsCheckbox.getjCheckBox(),
new ExGridBagConstraints(1, gridy, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
JPanel bandsJPanel = new JPanel(new GridBagLayout());
bandsJPanel.setBorder(BorderFactory.createTitledBorder("Bands"));
gridy = 0;
bandsJPanel.add(new JLabel("Bathymetry Band"),
new ExGridBagConstraints(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
bandsJPanel.add(bathymetryBandNameTextfield,
new ExGridBagConstraints(1, gridy, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
gridy++;
bandsJPanel.add(topographyBandCreateCheckbox.getjLabel(),
new ExGridBagConstraints(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
bandsJPanel.add(topographyBandCreateCheckbox.getjCheckBox(),
new ExGridBagConstraints(1, gridy, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
JLabel topographyBandLabel = new JLabel("Topography Band");
JLabel elevationBandLabel = new JLabel("Elevation Band");
gridy++;
bandsJPanel.add(topographyBandLabel,
new ExGridBagConstraints(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
bandsJPanel.add(topographyBandNameTextfield,
new ExGridBagConstraints(1, gridy, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
gridy++;
bandsJPanel.add(elevationBandCreateCheckbox.getjLabel(),
new ExGridBagConstraints(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
bandsJPanel.add(elevationBandCreateCheckbox.getjCheckBox(),
new ExGridBagConstraints(1, gridy, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
gridy++;
bandsJPanel.add(elevationBandLabel,
new ExGridBagConstraints(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
bandsJPanel.add(elevationBandNameTextfield,
new ExGridBagConstraints(1, gridy, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
topographyBandLabel.setEnabled(topographyBandCreateCheckbox.getjCheckBox().isSelected());
topographyBandNameTextfield.setEnabled(topographyBandCreateCheckbox.getjCheckBox().isSelected());
elevationBandLabel.setEnabled(elevationBandCreateCheckbox.getjCheckBox().isSelected());
elevationBandNameTextfield.setEnabled(elevationBandCreateCheckbox.getjCheckBox().isSelected());
topographyBandCreateCheckbox.getjCheckBox().addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
topographyBandLabel.setEnabled(topographyBandCreateCheckbox.getjCheckBox().isSelected());
topographyBandNameTextfield.setEnabled(topographyBandCreateCheckbox.getjCheckBox().isSelected());
}
});
elevationBandCreateCheckbox.getjCheckBox().addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
elevationBandLabel.setEnabled(elevationBandCreateCheckbox.getjCheckBox().isSelected());
elevationBandNameTextfield.setEnabled(elevationBandCreateCheckbox.getjCheckBox().isSelected());
}
});
JPanel mainPanel = new JPanel(new GridBagLayout());
// todo if we want a file selector then here it is
// I removed it because right now there is only one file - DANNY
//
// mainPanel.add(resolutionSamplingPanel,
// new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3));
mainPanel.add(maskJPanel,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3));
mainPanel.add(bandsJPanel,
new ExGridBagConstraints(0, 2, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3));
String label;
if (bandCreated) {
label = "Recreate Bathymetry Mask";
} else {
label = "Create Bands and Mask";
}
JButton createMasks = new JButton(label);
createMasks.setPreferredSize(createMasks.getPreferredSize());
createMasks.setMinimumSize(createMasks.getPreferredSize());
createMasks.setMaximumSize(createMasks.getPreferredSize());
createMasks.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
SourceFileInfo sourceFileInfo = (SourceFileInfo) resolutionComboBox.getjComboBox().getSelectedItem();
if (!sourceFileInfo.isEnabled()) {
bathymetryData.fireEvent(BathymetryData.PROMPT_REQUEST_TO_INSTALL_FILE_EVENT);
} else if (!bathymetryData.isInstallingFile()) {
bathymetryData.setCreateMasks(true);
dispose();
}
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.setPreferredSize(cancelButton.getPreferredSize());
cancelButton.setMinimumSize(cancelButton.getPreferredSize());
cancelButton.setMaximumSize(cancelButton.getPreferredSize());
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
JLabel filler = new JLabel(" ");
JPanel buttonsJPanel = new JPanel(new GridBagLayout());
buttonsJPanel.add(cancelButton,
new ExGridBagConstraints(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
buttonsJPanel.add(filler,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
buttonsJPanel.add(createMasks,
new ExGridBagConstraints(2, 0, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
buttonsJPanel.add(helpButton,
new ExGridBagConstraints(3, 0, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
createMasks.setAlignmentX(0.5f);
mainPanel.add(buttonsJPanel,
new ExGridBagConstraints(0, 4, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
add(mainPanel);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("Create Bathymetry Mask & Elevation Bands");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setPreferredSize(getPreferredSize());
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setSize(getPreferredSize());
}
}
| 18,023 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MaskMaxDepthTextfield.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/MaskMaxDepthTextfield.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 6/14/13
* Time: 12:56 PM
* To change this template use File | Settings | File Templates.
*/
public class MaskMaxDepthTextfield {
private BathymetryData bathymetryData;
private JLabel jLabel;
private JTextField jTextField = new JTextField();
public MaskMaxDepthTextfield(BathymetryData bathymetryData) {
this.bathymetryData = bathymetryData;
jLabel = new JLabel("Max Depth");
jLabel.setToolTipText("set maximum depth");
getjTextField().setText(bathymetryData.getMaskMaxDepthString());
getjTextField().setPreferredSize(getjTextField().getPreferredSize());
getjTextField().setMinimumSize(getjTextField().getPreferredSize());
getjTextField().setMaximumSize(getjTextField().getPreferredSize());
addControlListeners();
}
private void addControlListeners() {
jTextField.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
bathymetryData.setMaskMaxDepth(jTextField.getText().toString());
}
});
jTextField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
bathymetryData.setMaskMaxDepth(jTextField.getText().toString());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JTextField getjTextField() {
return jTextField;
}
}
| 1,843 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ExGridBagConstraints.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/ExGridBagConstraints.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import java.awt.*;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 1:57 PM
* To change this template use File | Settings | File Templates.
*/
public class ExGridBagConstraints extends GridBagConstraints {
public ExGridBagConstraints(int gridx, int gridy) {
this.gridx = gridx;
this.gridy = gridy;
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, int pad) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
this.insets = new Insets(pad, pad, pad, pad);
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, Insets insets) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
this.insets = insets;
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, int pad, int gridwidth) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
this.insets = new Insets(pad, pad, pad, pad);
this.gridwidth = gridwidth;
}
} | 1,798 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
BathymetryData.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/BathymetryData.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import com.bc.ceres.core.runtime.RuntimeContext;
//import gov.nasa.gsfc.seadas.OCSSWInfo;
import gov.nasa.gsfc.seadas.bathymetry.operator.BathymetryOp;
import gov.nasa.gsfc.seadas.bathymetry.util.ResourceInstallationUtils;
//import gov.nasa.gsfc.seadas.processing.common.SeadasLogger;
import javax.swing.event.SwingPropertyChangeSupport;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 9:13 AM
* To change this template use File | Settings | File Templates.
*/
public class BathymetryData {
BathymetryData bathymetryData = this;
public static final int RESOLUTION_BATHYMETRY_FILE = 1855;
public static final String FILENAME_BATHYMETRY = "ETOPO1_ocssw.nc";
public static String NOTIFY_USER_FILE_INSTALL_RESULTS_EVENT = "NOTIFY_USER_FILE_INSTALL_RESULTS_EVENT";
public static String FILE_INSTALLED_EVENT2 = "FILE_INSTALLED_EVENT2";
public static String PROMPT_REQUEST_TO_INSTALL_FILE_EVENT = "REQUEST_TO_INSTALL_FILE_EVENT";
public static String CONFIRMED_REQUEST_TO_INSTALL_FILE_EVENT = "CONFIRMED_REQUEST_TO_INSTALL_FILE_EVENT";
public static String LANDMASK_URL = "https://oceandata.sci.gsfc.nasa.gov/SeaDAS/installer/landmask";
private boolean createMasks = false;
private boolean deleteMasks = false;
private boolean isInstallingFile = false;
private double maskTransparency = 0.7;
private boolean showMaskAllBands = false;
private Color maskColor = new Color(0, 0, 255);
private String maskName = "BATHYMETRY_MASK";
private String maskDescription = "Bathymetry pixels";
private double maskMinDepth = 0;
private double maskMaxDepth = 10923;
public static final String OCSSWROOT_ENVVAR = "OCSSWROOT";
public static final String OCSSWROOT_PROPERTY = "ocssw.root";
private int superSampling = 1;
private boolean createTopographyBand = false;
private boolean createElevationBand = false;
// private String bathymetryBandName = "elevation";
private ArrayList<SourceFileInfo> sourceFileInfos = new ArrayList<SourceFileInfo>();
private SourceFileInfo sourceFileInfo;
private final SwingPropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this);
public BathymetryData() {
SourceFileInfo sourceFileInfo;
File bathymetryFile = getBathymetryFile(FILENAME_BATHYMETRY);
// File ocsswRootDir = getOcsswRoot();
// File ocsswRunDir = new File(ocsswRootDir, "run");
// File ocsswRunDataDir = new File(ocsswRunDir, "data");
// File ocsswRunDataCommonDir = new File(ocsswRunDataDir, "common");
// File bathymetryFile = new File(ocsswRunDataCommonDir, FILENAME_BATHYMETRY);
sourceFileInfo = new SourceFileInfo(RESOLUTION_BATHYMETRY_FILE,
SourceFileInfo.Unit.METER,
bathymetryFile);
getSourceFileInfos().add(sourceFileInfo);
// set the default
this.sourceFileInfo = sourceFileInfo;
this.addPropertyChangeListener(BathymetryData.NOTIFY_USER_FILE_INSTALL_RESULTS_EVENT, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
SourceFileInfo sourceFileInfo = (SourceFileInfo) evt.getNewValue();
InstallBathymetryFileDialog dialog = new InstallBathymetryFileDialog(bathymetryData, sourceFileInfo, InstallBathymetryFileDialog.Step.CONFIRMATION);
dialog.setVisible(true);
dialog.setEnabled(true);
}
});
}
public static File getOcsswRoot() {
String test = System.getenv(OCSSWROOT_ENVVAR);
if (test != null && test.length() > 1) {
return new File(RuntimeContext.getConfig().getContextProperty(OCSSWROOT_PROPERTY, System.getenv(OCSSWROOT_ENVVAR)));
}
return null;
}
public boolean isCreateTopographyBand() {
return createTopographyBand;
}
public void setCreateTopographyBand(boolean createTopographyBand) {
this.createTopographyBand = createTopographyBand;
}
public boolean isCreateElevationBand() {
return createElevationBand;
}
public void setCreateElevationBand(boolean createElevationBand) {
this.createElevationBand = createElevationBand;
}
public boolean isCreateMasks() {
return createMasks;
}
public void setCreateMasks(boolean closeClicked) {
this.createMasks = closeClicked;
}
public double getMaskTransparency() {
return maskTransparency;
}
public void setMaskTransparency(double maskTransparency) {
this.maskTransparency = maskTransparency;
}
public boolean isShowMaskAllBands() {
return showMaskAllBands;
}
public void setShowMaskAllBands(boolean showMaskAllBands) {
this.showMaskAllBands = showMaskAllBands;
}
public Color getMaskColor() {
return maskColor;
}
public void setMaskColor(Color maskColor) {
this.maskColor = maskColor;
}
public int getSuperSampling() {
return superSampling;
}
public void setSuperSampling(int superSampling) {
this.superSampling = superSampling;
}
public SourceFileInfo getSourceFileInfo() {
return sourceFileInfo;
}
public void setSourceFileInfo(SourceFileInfo resolution) {
this.sourceFileInfo = resolution;
}
// public String getBathymetryBandName() {
// return bathymetryBandName;
// }
//
// public void setBathymetryBandName(String bathymetryBandName) {
// this.bathymetryBandName = bathymetryBandName;
// }
public String getMaskName() {
return maskName;
}
public void setMaskName(String maskName) {
this.maskName = maskName;
}
public String getMaskMath() {
// StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append(BathymetryOp.ELEVATION_BAND_NAME);
// stringBuilder.append(" >= ");
// stringBuilder.append(new Double(-getMaskMaxDepth()).toString());
// stringBuilder.append(" and ");
// stringBuilder.append(BathymetryOp.ELEVATION_BAND_NAME);
// stringBuilder.append(" <= ");
// stringBuilder.append(new Double(-getMaskMinDepth()).toString());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(BathymetryOp.BATHYMETRY_BAND_NAME);
stringBuilder.append(" >= ");
stringBuilder.append(new Double(getMaskMinDepth()).toString());
stringBuilder.append(" and ");
stringBuilder.append(BathymetryOp.BATHYMETRY_BAND_NAME);
stringBuilder.append(" <= ");
stringBuilder.append(new Double(getMaskMaxDepth()).toString());
return stringBuilder.toString();
}
public String getMaskDescription() {
return maskDescription;
}
public void setMaskDescription(String maskDescription) {
this.maskDescription = maskDescription;
}
public boolean isDeleteMasks() {
return deleteMasks;
}
public void setDeleteMasks(boolean deleteMasks) {
this.deleteMasks = deleteMasks;
}
public ArrayList<SourceFileInfo> getSourceFileInfos() {
return sourceFileInfos;
}
public void setSourceFileInfos(ArrayList<SourceFileInfo> sourceFileInfos) {
this.sourceFileInfos = sourceFileInfos;
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(propertyName, listener);
}
public void fireEvent(String propertyName) {
propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(this, propertyName, null, null));
}
public void fireEvent(String propertyName, SourceFileInfo oldValue, SourceFileInfo newValue) {
propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(this, propertyName, oldValue, newValue));
}
public double getMaskMinDepth() {
return maskMinDepth;
}
public String getMaskMinDepthString() {
return new Double(maskMinDepth).toString();
}
public void setMaskMinDepth(double maskMinDepth) {
this.maskMinDepth = maskMinDepth;
}
public void setMaskMinDepth(String maskMinDepth) {
this.maskMinDepth = Double.parseDouble(maskMinDepth);
}
public double getMaskMaxDepth() {
return maskMaxDepth;
}
public String getMaskMaxDepthString() {
return new Double(maskMaxDepth).toString();
}
public void setMaskMaxDepth(double maskMaxDepth) {
this.maskMaxDepth = maskMaxDepth;
}
public void setMaskMaxDepth(String maskMaxDepth) {
this.maskMaxDepth = Double.parseDouble(maskMaxDepth);
}
static public File getBathymetryFile(String bathymetryFilename) {
// File ocsswRootDir = getOcsswRoot();
//todo Danny commented this out to skip OCSSWROOT and use .seadas for file location until we figure this out
// if (1 == 2) {
// File ocsswRootDir = null;
// try {
// ocsswRootDir = new File(OCSSWInfo.getInstance().getOcsswRoot());
// } catch (Exception e) {
// SeadasLogger.getLogger().warning("ocssw root not found, will try to use alternate source for bathymetry");
// }
// if (ocsswRootDir != null && ocsswRootDir.exists()) {
// File ocsswRunDir = new File(ocsswRootDir, "run");
// if (ocsswRootDir.exists()) {
// File ocsswRunDataDir = new File(ocsswRunDir, "data");
// if (ocsswRunDataDir.exists()) {
// File ocsswRunDataCommonDir = new File(ocsswRunDataDir, "common");
// if (ocsswRunDataCommonDir.exists()) {
// File bathymetryFile = new File(ocsswRunDataCommonDir, bathymetryFilename);
// if (bathymetryFile.exists()) {
// return bathymetryFile;
// }
// }
// }
// }
// }
// }
File bathymetryFile = ResourceInstallationUtils.getTargetFile(bathymetryFilename);
// if (bathymetryFile.exists()) {
return bathymetryFile;
// }
// return null;
}
public boolean isInstallingFile() {
return isInstallingFile;
}
public void setInstallingFile(boolean installingFile) {
isInstallingFile = installingFile;
}
}
| 11,004 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ElevationBandCreateCheckbox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/ElevationBandCreateCheckbox.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 10:27 AM
* To change this template use File | Settings | File Templates.
*/
public class ElevationBandCreateCheckbox {
private BathymetryData bathymetryData;
private JLabel jLabel;
private JCheckBox jCheckBox = new JCheckBox();
private static String DEFAULT_NAME = "Create elevation band";
private static String DEFAULT_TOOLTIPS = "Note: this can take longer to run";
public ElevationBandCreateCheckbox(BathymetryData bathymetryData) {
this.bathymetryData = bathymetryData;
jLabel = new JLabel(DEFAULT_NAME);
jLabel.setToolTipText(DEFAULT_TOOLTIPS);
jCheckBox.setSelected(bathymetryData.isCreateElevationBand());
addControlListeners();
}
private void addControlListeners() {
jCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
bathymetryData.setCreateElevationBand(jCheckBox.isSelected());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JCheckBox getjCheckBox() {
return jCheckBox;
}
}
| 1,351 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
InstallBathymetryFileDialog.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/InstallBathymetryFileDialog.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import gov.nasa.gsfc.seadas.bathymetry.util.ResourceInstallationUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URL;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 1/16/13
* Time: 1:01 PM
* To change this template use File | Settings | File Templates.
*/
class InstallBathymetryFileDialog extends JDialog {
public static enum Step {
INSTALLATION,
CONFIRMATION
}
public SourceFileInfo sourceFileInfo;
private JLabel jLabel;
private BathymetryData bathymetryData;
public InstallBathymetryFileDialog(BathymetryData bathymetryData, SourceFileInfo sourceFileInfo, Step step) {
this.bathymetryData = bathymetryData;
this.sourceFileInfo = sourceFileInfo;
if (step == Step.INSTALLATION) {
installationRequestUI();
} else if (step == Step.CONFIRMATION) {
installationResultsUI();
}
}
public final void installationRequestUI() {
JButton installButton = new JButton("Install File");
installButton.setPreferredSize(installButton.getPreferredSize());
installButton.setMinimumSize(installButton.getPreferredSize());
installButton.setMaximumSize(installButton.getPreferredSize());
installButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
// acquire in example: "https://oceandata.sci.gsfc.nasa.gov/SeaDAS/installer/landmask/50m.zip"
try {
bathymetryData.setInstallingFile(true);
bathymetryData.fireEvent(BathymetryData.CONFIRMED_REQUEST_TO_INSTALL_FILE_EVENT);
if (sourceFileInfo.getAltFile() != null) {
final String filename = sourceFileInfo.getAltFile().getName().toString();
final URL sourceUrl = new URL(BathymetryData.LANDMASK_URL + "/" + filename);
File targetFile = ResourceInstallationUtils.getTargetFile(filename);
if (!targetFile.exists()) {
Thread t = new Thread(new FileInstallRunnable(sourceUrl, filename, sourceFileInfo, bathymetryData));
t.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.setPreferredSize(cancelButton.getPreferredSize());
cancelButton.setMinimumSize(cancelButton.getPreferredSize());
cancelButton.setMaximumSize(cancelButton.getPreferredSize());
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
JLabel filler = new JLabel(" ");
JPanel buttonsJPanel = new JPanel(new GridBagLayout());
buttonsJPanel.add(cancelButton,
new ExGridBagConstraints(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
buttonsJPanel.add(filler,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
buttonsJPanel.add(installButton,
new ExGridBagConstraints(2, 0, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
jLabel = new JLabel("Do you want to install file " + sourceFileInfo.getAltFile().getName().toString() + " ?");
JPanel jPanel = new JPanel(new GridBagLayout());
jPanel.add(jLabel,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
jPanel.add(buttonsJPanel,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
add(jPanel);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("File Installation");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setPreferredSize(getPreferredSize());
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setSize(getPreferredSize());
}
public final void installationResultsUI() {
JButton okayButton = new JButton("Okay");
okayButton.setPreferredSize(okayButton.getPreferredSize());
okayButton.setMinimumSize(okayButton.getPreferredSize());
okayButton.setMaximumSize(okayButton.getPreferredSize());
okayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
if (sourceFileInfo.isEnabled()) {
jLabel = new JLabel("File " + sourceFileInfo.getAltFile().getName().toString() + " has been installed");
bathymetryData.fireEvent(BathymetryData.FILE_INSTALLED_EVENT2);
} else {
jLabel = new JLabel("File " + sourceFileInfo.getAltFile().getName().toString() + " installation failure");
}
bathymetryData.setInstallingFile(false);
JPanel jPanel = new JPanel(new GridBagLayout());
jPanel.add(jLabel,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
jPanel.add(okayButton,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
add(jPanel);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("File Installation");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setPreferredSize(getPreferredSize());
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setSize(getPreferredSize());
}
}
| 6,129 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MaskMinDepthTextfield.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/MaskMinDepthTextfield.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 6/14/13
* Time: 12:40 PM
* To change this template use File | Settings | File Templates.
*/
public class MaskMinDepthTextfield {
private BathymetryData bathymetryData;
private JLabel jLabel;
private JTextField jTextField = new JTextField();
public MaskMinDepthTextfield(BathymetryData bathymetryData) {
this.bathymetryData = bathymetryData;
jLabel = new JLabel("Min Depth");
jLabel.setToolTipText("set minimum depth");
getjTextField().setText(bathymetryData.getMaskMaxDepthString());
getjTextField().setPreferredSize(getjTextField().getPreferredSize());
getjTextField().setMinimumSize(getjTextField().getPreferredSize());
getjTextField().setMaximumSize(getjTextField().getPreferredSize());
getjTextField().setText(bathymetryData.getMaskMinDepthString());
addControlListeners();
}
private void addControlListeners() {
jTextField.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
bathymetryData.setMaskMinDepth(jTextField.getText().toString());
}
});
jTextField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
bathymetryData.setMaskMinDepth(jTextField.getText().toString());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JTextField getjTextField() {
return jTextField;
}
}
| 1,916 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ResolutionComboBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/ResolutionComboBox.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
import javax.swing.*;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/5/12
* Time: 11:07 AM
* To change this template use File | Settings | File Templates.
*/
public class ResolutionComboBox {
private BathymetryData bathymetryData;
private JLabel jLabel;
private JComboBox jComboBox;
private int validSelectedIndex;
public ResolutionComboBox(final BathymetryData bathymetryData) {
this.bathymetryData = bathymetryData;
ArrayList<SourceFileInfo> jComboBoxArrayList = new ArrayList<SourceFileInfo>();
ArrayList<String> toolTipsArrayList = new ArrayList<String>();
ArrayList<Boolean> enabledArrayList = new ArrayList<Boolean>();
for (SourceFileInfo sourceFileInfo : bathymetryData.getSourceFileInfos()) {
jComboBoxArrayList.add(sourceFileInfo);
if (sourceFileInfo.getDescription() != null) {
toolTipsArrayList.add(sourceFileInfo.getDescription());
} else {
toolTipsArrayList.add(null);
}
enabledArrayList.add(new Boolean(sourceFileInfo.isEnabled()));
}
final SourceFileInfo[] jComboBoxArray = new SourceFileInfo[jComboBoxArrayList.size()];
int i = 0;
for (SourceFileInfo sourceFileInfo : bathymetryData.getSourceFileInfos()) {
jComboBoxArray[i] = sourceFileInfo;
i++;
}
final String[] toolTipsArray = new String[jComboBoxArrayList.size()];
int j = 0;
for (String validValuesToolTip : toolTipsArrayList) {
toolTipsArray[j] = validValuesToolTip;
j++;
}
final Boolean[] enabledArray = new Boolean[jComboBoxArrayList.size()];
int k = 0;
for (Boolean enabled : enabledArrayList) {
enabledArray[k] = enabled;
k++;
}
jComboBox = new JComboBox(jComboBoxArray);
final MyComboBoxRenderer myComboBoxRenderer = new MyComboBoxRenderer();
myComboBoxRenderer.setTooltipList(toolTipsArray);
myComboBoxRenderer.setEnabledList(enabledArray);
jComboBox.setRenderer(myComboBoxRenderer);
jComboBox.setEditable(false);
for (SourceFileInfo sourceFileInfo : jComboBoxArray) {
if (sourceFileInfo == bathymetryData.getSourceFileInfo()) {
jComboBox.setSelectedItem(sourceFileInfo);
}
}
validSelectedIndex = jComboBox.getSelectedIndex();
jLabel = new JLabel("Bathymetry Dataset");
jLabel.setToolTipText("Determines which bathymetry source dataset to use");
addControlListeners();
addEventHandlers();
}
private void addEventHandlers() {
bathymetryData.addPropertyChangeListener(BathymetryData.FILE_INSTALLED_EVENT2, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateJComboBox();
}
});
bathymetryData.addPropertyChangeListener(BathymetryData.CONFIRMED_REQUEST_TO_INSTALL_FILE_EVENT, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
SourceFileInfo sourceFileInfo = (SourceFileInfo) jComboBox.getSelectedItem();
jComboBox.setSelectedIndex(getValidSelectedIndex());
}
});
}
private void addControlListeners() {
jComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SourceFileInfo sourceFileInfo = (SourceFileInfo) jComboBox.getSelectedItem();
if (sourceFileInfo.isEnabled()) {
bathymetryData.setSourceFileInfo(sourceFileInfo);
validSelectedIndex = jComboBox.getSelectedIndex();
} else {
// restore to prior selection
// jComboBox.setSelectedIndex(selectedIndex);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
bathymetryData.fireEvent(BathymetryData.PROMPT_REQUEST_TO_INSTALL_FILE_EVENT);
}
});
}
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JComboBox getjComboBox() {
return jComboBox;
}
public void updateJComboBox() {
ArrayList<SourceFileInfo> jComboBoxArrayList = new ArrayList<SourceFileInfo>();
ArrayList<String> toolTipsArrayList = new ArrayList<String>();
ArrayList<Boolean> enabledArrayList = new ArrayList<Boolean>();
for (SourceFileInfo sourceFileInfo : bathymetryData.getSourceFileInfos()) {
jComboBoxArrayList.add(sourceFileInfo);
if (sourceFileInfo.getDescription() != null) {
toolTipsArrayList.add(sourceFileInfo.getDescription());
} else {
toolTipsArrayList.add(null);
}
enabledArrayList.add(new Boolean(sourceFileInfo.isEnabled()));
}
final SourceFileInfo[] jComboBoxArray = new SourceFileInfo[jComboBoxArrayList.size()];
int i = 0;
for (SourceFileInfo sourceFileInfo : bathymetryData.getSourceFileInfos()) {
jComboBoxArray[i] = sourceFileInfo;
i++;
}
final String[] toolTipsArray = new String[jComboBoxArrayList.size()];
int j = 0;
for (String validValuesToolTip : toolTipsArrayList) {
toolTipsArray[j] = validValuesToolTip;
j++;
}
final Boolean[] enabledArray = new Boolean[jComboBoxArrayList.size()];
int k = 0;
for (Boolean enabled : enabledArrayList) {
enabledArray[k] = enabled;
k++;
}
final MyComboBoxRenderer myComboBoxRenderer = new MyComboBoxRenderer();
myComboBoxRenderer.setTooltipList(toolTipsArray);
myComboBoxRenderer.setEnabledList(enabledArray);
jComboBox.setRenderer(myComboBoxRenderer);
jComboBox.setEditable(false);
for (SourceFileInfo sourceFileInfo : jComboBoxArray) {
if (sourceFileInfo == bathymetryData.getSourceFileInfo()) {
jComboBox.setSelectedItem(sourceFileInfo);
}
}
validSelectedIndex = jComboBox.getSelectedIndex();
// int i = 0;
// for (SourceFileInfo sourceFileInfo : jComboBoxArray) {
// enabledArray[i] = sourceFileInfo.isEnabled();
// i++;
// }
//
//
// final MyComboBoxRenderer myComboBoxRenderer = new MyComboBoxRenderer();
// myComboBoxRenderer.setTooltipList(toolTipsArray);
// myComboBoxRenderer.setEnabledList(enabledArray);
//
// jComboBox.setRenderer(myComboBoxRenderer);
//
//
// for (SourceFileInfo sourceFileInfo : jComboBoxArray) {
// if (sourceFileInfo == bathymetryData.getSourceFileInfo()) {
// jComboBox.setSelectedItem(sourceFileInfo);
// }
// }
//
// selectedIndex = jComboBox.getSelectedIndex();
//
}
public int getValidSelectedIndex() {
return validSelectedIndex;
}
class MyComboBoxRenderer extends BasicComboBoxRenderer {
private String[] tooltips;
private Boolean[] enabledList;
// public void MyComboBoxRenderer(String[] tooltips) {
// this.tooltips = tooltips;
// }
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected) {
if (-1 < index && index < tooltips.length) {
list.setToolTipText(tooltips[index]);
}
if (-1 < index && index < enabledList.length) {
if (enabledList[index] == true) {
setBackground(Color.blue);
setForeground(Color.black);
} else {
setBackground(Color.blue);
setForeground(Color.gray);
}
}
} else {
if (-1 < index && index < enabledList.length) {
if (enabledList[index] == true) {
setBackground(Color.white);
setForeground(Color.black);
} else {
setBackground(Color.white);
setForeground(Color.gray);
}
}
}
setFont(list.getFont());
setText((value == null) ? "" : value.toString());
return this;
}
public void setTooltipList(String[] tooltipList) {
this.tooltips = tooltipList;
}
public void setEnabledList(Boolean[] enabledList) {
this.enabledList = enabledList;
}
}
}
| 9,412 | 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-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/ui/SimpleDialogMessage.java | package gov.nasa.gsfc.seadas.bathymetry.ui;
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 ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
jPanel.add(okayButton,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
add(jPanel);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle(title);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setPreferredSize(getPreferredSize());
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setSize(getPreferredSize());
}
} | 1,629 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
BathymetryReader.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/operator/BathymetryReader.java | package gov.nasa.gsfc.seadas.bathymetry.operator;
import ucar.ma2.Array;
import ucar.ma2.InvalidRangeException;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;
import java.io.File;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 7/2/13
* Time: 9:28 AM
* To change this template use File | Settings | File Templates.
*/
public class BathymetryReader {
// For test purposes here is the command line view:
// OCSSWOldModel/run/data/common: ncdump -h ETOPO1_ocssw.nc
private NetcdfFile ncFile;
float startLat = 0;
float endLat = 0;
float startLon = 0;
float endLon = 0;
float deltaLat;
float deltaLon;
float deltaLatStrange;
float deltaLonStrange;
int dimensionLat = 0;
int dimensionLon = 0;
Variable heightVariable;
Variable waterSurfaceHeightVariable;
private short missingValue;
public BathymetryReader(File file) throws IOException {
ncFile = NetcdfFile.open(file.getAbsolutePath());
startLon = ncFile.findGlobalAttribute("left_lon").getNumericValue().floatValue();
endLon = ncFile.findGlobalAttribute("right_lon").getNumericValue().floatValue();
startLat = ncFile.findGlobalAttribute("lower_lat").getNumericValue().floatValue();
endLat = ncFile.findGlobalAttribute("upper_lat").getNumericValue().floatValue();
dimensionLat = ncFile.findDimension("lat").getLength();
dimensionLon = ncFile.findDimension("lon").getLength();
deltaLat = (endLat - startLat) / dimensionLat;
deltaLon = (endLon - startLon) / dimensionLon;
deltaLatStrange = (endLat - startLat) / (dimensionLat-1);
deltaLonStrange = (endLon - startLon) / (dimensionLon-1);
heightVariable = ncFile.findVariable("height");
waterSurfaceHeightVariable = ncFile.findVariable("water_surface_height");
missingValue = heightVariable.findAttribute("missing_value").getNumericValue().shortValue();
}
public void close() throws IOException {
if (ncFile != null) {
ncFile.close();
}
}
public Array getHeightArray(int[] origin, int[] shape) {
Array heightArray = null;
try {
heightArray = heightVariable.read(origin, shape);
} catch (IOException e) {
} catch (InvalidRangeException e) {
}
if (heightArray != null) {
return heightArray;
} else {
return null;
}
}
public Array getWaterSurfaceHeightArray(int[] origin, int[] shape) {
Array heightArray = null;
try {
heightArray = waterSurfaceHeightVariable.read(origin, shape);
} catch (IOException e) {
} catch (InvalidRangeException e) {
}
if (heightArray != null) {
return heightArray;
} else {
return null;
}
}
public short getHeight(int latIndex, int lonIndex) {
short height;
int[] origin = new int[]{latIndex, lonIndex};
int[] shape = new int[]{1, 1};
try {
height = heightVariable.read(origin, shape).getShort(0);
} catch (IOException e) {
return getMissingValue();
} catch (InvalidRangeException e) {
return getMissingValue();
}
return height;
}
public float getLon(int lonIndex) {
if (lonIndex > dimensionLon - 1) {
lonIndex = dimensionLon - 1;
}
if (lonIndex < 0) {
lonIndex = 0;
}
return startLon + lonIndex * deltaLonStrange;
}
public float getLat(int latIndex) {
if (latIndex > dimensionLat - 1) {
latIndex = dimensionLat - 1;
}
if (latIndex < 0) {
latIndex = 0;
}
return startLat + latIndex * deltaLatStrange;
}
public int getLatIndex(double lat) {
int latIndex = (int) ((lat - startLat) / deltaLatStrange);
if (latIndex > dimensionLat - 1) {
latIndex = dimensionLat - 1;
}
if (latIndex < 0) {
latIndex = 0;
}
return latIndex;
}
public int getLonIndex(double lon) {
int lonIndex = (int) ((lon - startLon) / deltaLonStrange);
if (lonIndex > dimensionLon - 1) {
lonIndex = dimensionLon - 1;
}
if (lonIndex < 0) {
lonIndex = 0;
}
return lonIndex;
}
public short getMissingValue() {
return missingValue;
}
}
| 4,587 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
EarthBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/operator/EarthBox.java | package gov.nasa.gsfc.seadas.bathymetry.operator;
import org.esa.snap.core.datamodel.GeoPos;
/**
* 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 EarthBox {
public static final float NULL_COORDINATE = (float) -999;
public static final int NULL_LENGTH = -999;
private double minLatLimit = (float) -90;
private double maxLatLimit = (float) 90;
private double minLonLimit = (float) -180;
private double maxLonLimit = (float) 180;
private double minLat = NULL_COORDINATE;
private double maxLat = NULL_COORDINATE;
private double minLon = NULL_COORDINATE;
private double maxLon = NULL_COORDINATE;
double deltaLat = NULL_COORDINATE;
double deltaLon = NULL_COORDINATE;
private int latDimensionLength = NULL_LENGTH;
private int lonDimensionLength = NULL_LENGTH;
private short[][] values;
private short[][] waterSurfaceValues;
private short missingValue;
private boolean getValueAverage = true;
public EarthBox() {
}
public void add(GeoPos geoPos) {
double lat = geoPos.lat;
double lon = geoPos.lon;
add(lat, lon);
}
public void add(double lat, double 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);
}
}
private void setDeltaLon() {
if (getMinLon() != NULL_COORDINATE && getMaxLon() != NULL_COORDINATE && getLonDimensionLength() != NULL_LENGTH) {
deltaLon = (getMaxLon() - getMinLon()) / (getLonDimensionLength()-1);
}
}
private void setDeltaLat() {
if (getMinLat() != NULL_COORDINATE && getMaxLat() != NULL_COORDINATE && getLatDimensionLength() != NULL_LENGTH) {
deltaLat = (getMaxLat() - getMinLat()) / (getLatDimensionLength()-1);
}
}
private void setMinLat(double minLat) {
if (minLat < minLatLimit) {
minLat = minLatLimit;
}
this.minLat = minLat;
this.deltaLat = NULL_COORDINATE;
}
private void setMaxLat(double maxLat) {
if (maxLat > maxLatLimit) {
maxLat = maxLatLimit;
}
this.maxLat = maxLat;
this.deltaLat = NULL_COORDINATE;
}
private void setMinLon(double minLon) {
if (minLon < minLonLimit) {
minLon = minLonLimit;
}
this.minLon = minLon;
this.deltaLon = NULL_COORDINATE;
}
private void setMaxLon(double maxLon) {
if (maxLon > maxLonLimit) {
maxLon = maxLonLimit;
}
this.maxLon = maxLon;
this.deltaLon = NULL_COORDINATE;
}
private void setLatDimensionLength(int latDimensionLength) {
this.latDimensionLength = latDimensionLength;
this.deltaLat = NULL_COORDINATE;
}
private void setLonDimensionLength(int lonDimensionLength) {
this.lonDimensionLength = lonDimensionLength;
this.deltaLon = NULL_COORDINATE;
}
public void setValues(double minLat, double maxLat, double minLon, double maxLon, short[][] values, short[][] waterSurfaceValues, short missingValue) {
this.values = values;
this.waterSurfaceValues = waterSurfaceValues;
setMaxLat(maxLat);
setMinLat(minLat);
setMaxLon(maxLon);
setMinLon(minLon);
setLatDimensionLength(values.length);
setLonDimensionLength(values[0].length);
setDeltaLat();
setDeltaLon();
setMissingValue(missingValue);
}
public double getMinLat() {
return minLat;
}
public double getMaxLat() {
return maxLat;
}
public double getMinLon() {
return minLon;
}
public double getMaxLon() {
return maxLon;
}
public int getLatDimensionLength() {
return latDimensionLength;
}
public int getLonDimensionLength() {
return lonDimensionLength;
}
public short getValue(GeoPos geoPos) {
return getValue(geoPos.lat, geoPos.lon);
}
public short getWaterSurfaceValue(GeoPos geoPos) {
return getWaterSurfaceValue(geoPos.lat, geoPos.lon);
}
public short getValue(double lat, double lon) {
int latIndex = getLatIndex(lat);
int lonIndex = getLonIndex(lon);
short value;
if (isGetValueAverage()) {
double lutLat = getLat(latIndex);
double lutLon = getLon(lonIndex);
double lutLatN;
double lutLatS;
int lutLatIndexN;
int lutLatIndexS;
if (lat > lutLat) {
if (latIndex < latDimensionLength - 1) {
lutLatIndexN = latIndex + 1;
lutLatN = getLat(lutLatIndexN);
} else {
lutLatIndexN = latIndex;
lutLatN = lutLat;
}
lutLatIndexS = latIndex;
lutLatS = lutLat;
} else {
lutLatN = lutLat;
lutLatIndexN = latIndex;
if (latIndex > 0) {
lutLatIndexS = latIndex - 1;
lutLatS = getLat(lutLatIndexS);
} else {
lutLatIndexS = 0;
lutLatS = lutLat;
}
}
double lutLonE;
double lutLonW;
int lutLonIndexE;
int lutLonIndexW;
if (lon > lutLon) {
if (lonIndex < lonDimensionLength - 1) {
lutLonIndexE = lonIndex + 1;
lutLonE = getLon(lutLonIndexE);
} else {
lutLonIndexE = lonIndex;
lutLonE = lutLon;
}
lutLonIndexW = lonIndex;
lutLonW = lutLon;
} else {
lutLonE = lutLon;
lutLonIndexE = lonIndex;
if (lonIndex > 0) {
lutLonIndexW = lonIndex - 1;
lutLonW = getLon(lutLonIndexW);
} else {
lutLonIndexW = 0;
lutLonW = lutLon;
}
}
GeoPos geoPosNW = new GeoPos(lutLatN, lutLonW);
GeoPos geoPosNE = new GeoPos(lutLatN, lutLonE);
GeoPos geoPosSW = new GeoPos(lutLatS, lutLonW);
GeoPos geoPosSE = new GeoPos(lutLatS, lutLonE);
short cornerValueNW = getValue(lutLatIndexN, lutLonIndexW);
short cornerValueNE = getValue(lutLatIndexN, lutLonIndexE);
short cornerValueSW = getValue(lutLatIndexS, lutLonIndexW);
short cornerValueSE = getValue(lutLatIndexS, lutLonIndexE);
if (cornerValueNW != getMissingValue() && cornerValueNE != getMissingValue() && cornerValueSW != getMissingValue() && cornerValueSE != getMissingValue()) {
double deltaLutLat = lutLatN - lutLatS;
short sideValueW;
short sideValueE;
if (deltaLutLat > 0) {
double weightLutLatS = (lutLatN - lat) / deltaLutLat;
double weightLutLatN = 1 - weightLutLatS;
sideValueW = (short) (weightLutLatN * cornerValueNW + weightLutLatS * cornerValueSW);
sideValueE = (short) (weightLutLatN * cornerValueNE + weightLutLatS * cornerValueSE);
} else {
sideValueW = cornerValueNW;
sideValueE = cornerValueNE;
}
double deltaLutLon = lutLonE - lutLonW;
if (deltaLutLon > 0) {
double weightSideW = (lutLonE - lon) / deltaLutLon;
double weightSideE = 1 - weightSideW;
value = (short) (weightSideW * sideValueW + weightSideE * sideValueE);
} else {
value = sideValueE;
}
} else {
value = getValue(latIndex, lonIndex);
}
} else {
value = getValue(latIndex, lonIndex);
}
return value;
}
public short getWaterSurfaceValue(double lat, double lon) {
int latIndex = getLatIndex(lat);
int lonIndex = getLonIndex(lon);
short waterSurfaceValue;
if (isGetValueAverage()) {
double lutLat = getLat(latIndex);
double lutLon = getLon(lonIndex);
double lutLatN;
double lutLatS;
int lutLatIndexN;
int lutLatIndexS;
if (lat > lutLat) {
if (latIndex < latDimensionLength - 1) {
lutLatIndexN = latIndex + 1;
lutLatN = getLat(lutLatIndexN);
} else {
lutLatIndexN = latIndex;
lutLatN = lutLat;
}
lutLatIndexS = latIndex;
lutLatS = lutLat;
} else {
lutLatN = lutLat;
lutLatIndexN = latIndex;
if (latIndex > 0) {
lutLatIndexS = latIndex - 1;
lutLatS = getLat(lutLatIndexS);
} else {
lutLatIndexS = 0;
lutLatS = lutLat;
}
}
double lutLonE;
double lutLonW;
int lutLonIndexE;
int lutLonIndexW;
if (lon > lutLon) {
if (lonIndex < lonDimensionLength - 1) {
lutLonIndexE = lonIndex + 1;
lutLonE = getLon(lutLonIndexE);
} else {
lutLonIndexE = lonIndex;
lutLonE = lutLon;
}
lutLonIndexW = lonIndex;
lutLonW = lutLon;
} else {
lutLonE = lutLon;
lutLonIndexE = lonIndex;
if (lonIndex > 0) {
lutLonIndexW = lonIndex - 1;
lutLonW = getLon(lutLonIndexW);
} else {
lutLonIndexW = 0;
lutLonW = lutLon;
}
}
GeoPos geoPosNW = new GeoPos(lutLatN, lutLonW);
GeoPos geoPosNE = new GeoPos(lutLatN, lutLonE);
GeoPos geoPosSW = new GeoPos(lutLatS, lutLonW);
GeoPos geoPosSE = new GeoPos(lutLatS, lutLonE);
short cornerValueNW = getWaterSurfaceValue(lutLatIndexN, lutLonIndexW);
short cornerValueNE = getWaterSurfaceValue(lutLatIndexN, lutLonIndexE);
short cornerValueSW = getWaterSurfaceValue(lutLatIndexS, lutLonIndexW);
short cornerValueSE = getWaterSurfaceValue(lutLatIndexS, lutLonIndexE);
if (cornerValueNW != getMissingValue() && cornerValueNE != getMissingValue() && cornerValueSW != getMissingValue() && cornerValueSE != getMissingValue()) {
double deltaLutLat = lutLatN - lutLatS;
short sideValueW;
short sideValueE;
if (deltaLutLat > 0) {
double weightLutLatS = (lutLatN - lat) / deltaLutLat;
double weightLutLatN = 1 - weightLutLatS;
sideValueW = (short) (weightLutLatN * cornerValueNW + weightLutLatS * cornerValueSW);
sideValueE = (short) (weightLutLatN * cornerValueNE + weightLutLatS * cornerValueSE);
} else {
sideValueW = cornerValueNW;
sideValueE = cornerValueNE;
}
double deltaLutLon = lutLonE - lutLonW;
if (deltaLutLon > 0) {
double weightSideW = (lutLonE - lon) / deltaLutLon;
double weightSideE = 1 - weightSideW;
waterSurfaceValue = (short) (weightSideW * sideValueW + weightSideE * sideValueE);
} else {
waterSurfaceValue = sideValueE;
}
} else {
waterSurfaceValue = getWaterSurfaceValue(latIndex, lonIndex);
}
} else {
waterSurfaceValue = getWaterSurfaceValue(latIndex, lonIndex);
}
return waterSurfaceValue;
}
public short getValue(int latIndex, int lonIndex) {
return values[latIndex][lonIndex];
}
public short getWaterSurfaceValue(int latIndex, int lonIndex) {
return waterSurfaceValues[latIndex][lonIndex];
}
public double getLon(int lonIndex) {
if (lonIndex > getLonDimensionLength() - 1) {
lonIndex = getLonDimensionLength() - 1;
}
if (lonIndex < 0) {
lonIndex = 0;
}
return getMinLon() + lonIndex * getDeltaLon();
}
public double getLat(int latIndex) {
if (latIndex > getLatDimensionLength() - 1) {
latIndex = getLatDimensionLength() - 1;
}
if (latIndex < 0) {
latIndex = 0;
}
return getMinLat() + latIndex * getDeltaLat();
}
private double getDeltaLat() {
if (deltaLat == NULL_COORDINATE) {
setDeltaLat();
}
return deltaLat;
}
private double getDeltaLon() {
if (deltaLon == NULL_COORDINATE) {
setDeltaLon();
}
return deltaLon;
}
private int getLatIndex(double lat) {
int latIndex = (int) ((lat - getMinLat()) / getDeltaLat());
if (latIndex > getLatDimensionLength() - 1) {
latIndex = getLatDimensionLength() - 1;
}
if (latIndex < 0) {
latIndex = 0;
}
return latIndex;
}
private int getLonIndex(double lon) {
int lonIndex = (int) ((lon - getMinLon()) / getDeltaLon());
if (lonIndex > getLonDimensionLength() - 1) {
lonIndex = getLonDimensionLength() - 1;
}
if (lonIndex < 0) {
lonIndex = 0;
}
return lonIndex;
}
public boolean isGetValueAverage() {
return getValueAverage;
}
public void setGetValueAverage(boolean getValueAverage) {
this.getValueAverage = getValueAverage;
}
public short getMissingValue() {
return missingValue;
}
public void setMissingValue(short missingValue) {
this.missingValue = missingValue;
}
}
| 14,839 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
BathymetryOp.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/operator/BathymetryOp.java | package gov.nasa.gsfc.seadas.bathymetry.operator;
import com.bc.ceres.core.ProgressMonitor;
import gov.nasa.gsfc.seadas.bathymetry.ui.BathymetryData;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.gpf.Operator;
import org.esa.snap.core.gpf.OperatorException;
import org.esa.snap.core.gpf.OperatorSpi;
import org.esa.snap.core.gpf.Tile;
import org.esa.snap.core.gpf.annotations.OperatorMetadata;
import org.esa.snap.core.gpf.annotations.Parameter;
import org.esa.snap.core.gpf.annotations.SourceProduct;
import org.esa.snap.core.gpf.annotations.TargetProduct;
import org.esa.snap.core.util.ProductUtils;
import ucar.ma2.Array;
import java.awt.*;
import java.io.File;
import java.io.IOException;
/**
* The bathymetry operator is a GPF-Operator. It takes the geographic bounds of the input product and creates a new
* product with the same bounds. The output product contains a single band, which is a land/water fraction mask.
* For each pixel, it contains the fraction of water; a value of 0.0 indicates land, a value of 100.0 indicates water,
* and every value in between indicates a mixed pixel.
* <br/>
* Since the base data may exhibit a higher resolution than the input product, a subsampling ≥1 may be specified;
* therefore, mixed pixels may occur.
*
* @author Danny Knowles
*/
@SuppressWarnings({"FieldCanBeLocal"})
@OperatorMetadata(alias = "BathymetryOp",
version = "1.0",
internal = true,
authors = "Danny Knowles",
copyright = "",
description = "Operator creating a bathymetry band, elevation band, topography band and bathymetry mask")
public class BathymetryOp extends Operator {
public static final String BATHYMETRY_BAND_NAME = "bathymetry";
public static final String ELEVATION_BAND_NAME = "elevation";
public static final String TOPOGRAPHY_BAND_NAME = "topography";
@SourceProduct(alias = "source", description = "The Product the land/water-mask shall be computed for.",
label = "Name")
private Product sourceProduct;
@Parameter(description = "Specifies on which resolution the water mask shall be based.", unit = "m/pixel",
label = "Resolution", defaultValue = "1855", valueSet = {"1855"})
private int resolution;
@Parameter(description = "Bathymetry filename",
label = "Filename", defaultValue = "ETOPO1_ocssw.nc",
valueSet = {"ETOPO1_ocssw.nc"})
private String filename;
@TargetProduct
private Product targetProduct;
private BathymetryReader bathymetryReader;
@Override
public void initialize() throws OperatorException {
File bathymetryFile = BathymetryData.getBathymetryFile(filename);
if (bathymetryFile != null) {
if (bathymetryFile.exists()) {
System.out.print("Reading bathymetry source file " + bathymetryFile.getAbsolutePath()+"\n");
} else {
System.out.print("Bathymetry source file does not exist " + bathymetryFile.getAbsolutePath()+"\n");
}
} else {
System.out.print("Reading bathymetry source file " + filename+"\n");
}
try {
bathymetryReader = new BathymetryReader(bathymetryFile);
} catch (IOException e) {
if (bathymetryFile != null) {
if (bathymetryFile.exists()) {
System.out.print("Error: Reading bathymetry source file " + bathymetryFile.getAbsolutePath()+"\n");
} else {
System.out.print("Error: Bathymetry source file does not exist " + bathymetryFile.getAbsolutePath()+"\n");
}
} else {
System.out.print("Error: Reading bathymetry source file " + filename+"\n");
}
// if (bathymetryFile != null) {
// if (bathymetryFile.exists()) {
// SeadasLogger.getLogger().warning("Error reading bathymetry source file '" + bathymetryFile.getAbsolutePath());
// } else {
// SeadasLogger.getLogger().warning("Bathymetry source file does not exist '" + bathymetryFile.getAbsolutePath());
// }
// } else {
// SeadasLogger.getLogger().warning("Error reading bathymetry source file '" + filename);
// }
}
validateParameter();
validateSourceProduct();
initTargetProduct();
}
private void validateParameter() {
if (resolution != BathymetryData.RESOLUTION_BATHYMETRY_FILE) {
throw new OperatorException(String.format("Resolution needs to be %d ",
BathymetryData.RESOLUTION_BATHYMETRY_FILE));
}
}
private void validateSourceProduct() {
final GeoCoding geoCoding = sourceProduct.getSceneGeoCoding();
if (geoCoding == null) {
throw new OperatorException("The source product must be geo-coded.");
}
if (!geoCoding.canGetGeoPos()) {
throw new OperatorException("The geo-coding of the source product can not be used.\n" +
"It does not provide the geo-position for a pixel position.");
}
}
private void initTargetProduct() {
targetProduct = new Product("BathymetryProductTemporary", ProductData.TYPESTRING_UINT8, sourceProduct.getSceneRasterWidth(),
sourceProduct.getSceneRasterHeight());
final Band bathymetryBand = targetProduct.addBand(BATHYMETRY_BAND_NAME, ProductData.TYPE_FLOAT32);
bathymetryBand.setNoDataValue(bathymetryReader.getMissingValue());
bathymetryBand.setNoDataValueUsed(true);
final Band topographyBand = targetProduct.addBand(TOPOGRAPHY_BAND_NAME, ProductData.TYPE_FLOAT32);
topographyBand.setNoDataValue(bathymetryReader.getMissingValue());
topographyBand.setNoDataValueUsed(true);
final Band elevationBand = targetProduct.addBand(ELEVATION_BAND_NAME, ProductData.TYPE_FLOAT32);
elevationBand.setNoDataValue(bathymetryReader.getMissingValue());
elevationBand.setNoDataValueUsed(true);
ProductUtils.copyGeoCoding(sourceProduct, targetProduct);
}
@SuppressWarnings({"UnusedDeclaration"})
public static class Spi extends OperatorSpi {
public Spi() {
super(BathymetryOp.class);
}
}
@Override
public void computeTile(Band targetBand, Tile targetTile, ProgressMonitor pm) throws OperatorException {
final String targetBandName = targetBand.getName();
final Rectangle rectangle = targetTile.getRectangle();
// not sure if this is really needed but just in case
if (!targetBandName.equals(BATHYMETRY_BAND_NAME)
&& !targetBandName.equals(TOPOGRAPHY_BAND_NAME)
&& !targetBandName.equals(ELEVATION_BAND_NAME)) {
for (int y = rectangle.y; y < rectangle.y + rectangle.height; y++) {
for (int x = rectangle.x; x < rectangle.x + rectangle.width; x++) {
int dataValue = 0;
targetTile.setSample(x, y, dataValue);
}
}
return;
}
try {
final GeoCoding geoCoding = sourceProduct.getSceneGeoCoding();
final PixelPos pixelPos = new PixelPos();
final GeoPos geoPos = new GeoPos();
// loop through tile, adding each pixel geolocation to it's appropriate earthBox via motherEarthBox
// at this point the earthBoxes will adjust their mins and maxes based on the given lats and lons.
MotherEarthBox motherEarthBox = new MotherEarthBox();
for (int y = rectangle.y; y < rectangle.y + rectangle.height; y++) {
for (int x = rectangle.x; x < rectangle.x + rectangle.width; x++) {
pixelPos.setLocation(x, y);
geoCoding.getGeoPos(pixelPos, geoPos);
motherEarthBox.add(geoPos);
}
}
// for each of the earthBoxes, add in the bathymetry height array which is obtained at
// this point from the source in a single chunk call.
for (EarthBox earthBox : motherEarthBox.getFilledEarthBoxes()) {
// add dimensions to the earthBox
int minLatIndex = bathymetryReader.getLatIndex(earthBox.getMinLat());
int maxLatIndex = bathymetryReader.getLatIndex(earthBox.getMaxLat());
int minLonIndex = bathymetryReader.getLonIndex(earthBox.getMinLon());
int maxLonIndex = bathymetryReader.getLonIndex(earthBox.getMaxLon());
if (minLatIndex > 0) {
minLatIndex--;
}
if (maxLatIndex < bathymetryReader.dimensionLat - 1) {
maxLatIndex++;
}
if (minLonIndex > 0) {
minLonIndex--;
}
if (maxLonIndex < bathymetryReader.dimensionLon - 1) {
maxLonIndex++;
}
// determine length of each dimension for the chunk array to be pulled out of the netcdf source
int latDimensionLength = maxLatIndex - minLatIndex + 1;
int lonDimensionLength = maxLonIndex - minLonIndex + 1;
// get the bathymetry height array from the netcdf source
int[] origin = new int[]{minLatIndex, minLonIndex};
int[] shape = new int[]{latDimensionLength, lonDimensionLength};
// retrieve the bathymetry height array from netcdf
Array heightArray = bathymetryReader.getHeightArray(origin, shape);
Array waterSurfaceheightArray = bathymetryReader.getWaterSurfaceHeightArray(origin, shape);
// convert heightArray from ucar.ma2.Array format to regular java array
short heights[][] = (short[][]) heightArray.copyToNDJavaArray();
short waterSurfaceHeights[][] = (short[][]) waterSurfaceheightArray.copyToNDJavaArray();
// add the value array to the earthBox
float minLat = bathymetryReader.getLat(minLatIndex);
float maxLat = bathymetryReader.getLat(maxLatIndex);
float minLon = bathymetryReader.getLon(minLonIndex);
float maxLon = bathymetryReader.getLon(maxLonIndex);
short missingValue = bathymetryReader.getMissingValue();
earthBox.setValues(minLat, maxLat, minLon, maxLon, heights, waterSurfaceHeights, missingValue);
earthBox.setGetValueAverage(true);
}
// loop through all the tile pixels, geolocate them, and get their bathymetry height from motherEarthBox.
for (int y = rectangle.y; y < rectangle.y + rectangle.height; y++) {
for (int x = rectangle.x; x < rectangle.x + rectangle.width; x++) {
pixelPos.setLocation(x, y);
geoCoding.getGeoPos(pixelPos, geoPos);
int value;
int waterSurfaceHeight;
int height;
if (geoPos.isValid()) {
height = motherEarthBox.getValue(geoPos);
waterSurfaceHeight = motherEarthBox.getWaterSurfaceValue(geoPos);
if (targetBandName.equals(ELEVATION_BAND_NAME)) {
value = height;
} else if (targetBandName.equals(TOPOGRAPHY_BAND_NAME)) {
int valueSurface = height - waterSurfaceHeight;
if (valueSurface > 0) {
value = motherEarthBox.getValue(geoPos);
} else {
value = bathymetryReader.getMissingValue();
}
} else if (targetBandName.equals(BATHYMETRY_BAND_NAME)) {
int valueSurface = height - waterSurfaceHeight;
if (valueSurface <= 0) {
value = valueSurface;
} else {
value = bathymetryReader.getMissingValue();
}
// convert to positive if not NaN
if (value > -32000) {
value = -value;
}
} else {
value = bathymetryReader.getMissingValue();
}
} else {
value = bathymetryReader.getMissingValue();
}
targetTile.setSample(x, y, value);
}
}
} catch (Exception e) {
throw new OperatorException("Error computing tile '" + targetTile.getRectangle().toString() + "'.", e);
}
}
// public void computeTileGood(Band targetBand, Tile targetTile, ProgressMonitor pm) throws OperatorException {
//
// final String targetBandName = targetBand.getName();
//
// final Rectangle rectangle = targetTile.getRectangle();
//
// // not sure if this is really needed but just in case
// if (!targetBandName.equals(BATHYMETRY_BAND_NAME)) {
// for (int y = rectangle.y; y < rectangle.y + rectangle.height; y++) {
// for (int x = rectangle.x; x < rectangle.x + rectangle.width; x++) {
// int dataValue = 0;
// targetTile.setSample(x, y, dataValue);
// }
// }
//
// return;
// }
//
//
// try {
// final GeoCoding geoCoding = sourceProduct.getGeoCoding();
// final PixelPos pixelPos = new PixelPos();
// final GeoPos geoPos = new GeoPos();
//
// // establish 4 locations on the earth to minimize any effects of dateline and pole crossing
// EarthBox earthBoxNW = new EarthBox();
// EarthBox earthBoxNE = new EarthBox();
// EarthBox earthBoxSW = new EarthBox();
// EarthBox earthBoxSE = new EarthBox();
//
// // loop through perimeter of tile, adding each pixel geolocation to it's appropriate earthBox
// // at this point the earthBoxes will be adjusted their mins and maxes of the lats and lons.
// for (int y = rectangle.y; y < rectangle.y + rectangle.height; y++) {
// for (int x = rectangle.x; x < rectangle.x + rectangle.width; x++) {
// pixelPos.setLocation(x, y);
//
// geoCoding.getGeoPos(pixelPos, geoPos);
//
// if (geoPos.lat >= 0) {
// if (geoPos.lon >= 0) {
// earthBoxNE.add(geoPos);
// } else {
// earthBoxNW.add(geoPos);
// }
// } else {
// if (geoPos.lon >= 0) {
// earthBoxSE.add(geoPos);
// } else {
// earthBoxSW.add(geoPos);
// }
// }
// }
// }
//
//
// // for all applicable earthBoxes add in the dimensions and bathymetry height array which is obtained at
// // this point from the source in a single chunk call.
// EarthBox earthBoxes[] = {earthBoxNE, earthBoxNW, earthBoxSE, earthBoxSW};
//
// for (EarthBox earthBox : earthBoxes) {
// if (earthBox.getMaxLat() != EarthBox.NULL_COORDINATE) {
// // add dimensions to the earthBox
// int minLatIndex = bathymetryReader.getLatIndex(earthBox.getMinLat());
// int maxLatIndex = bathymetryReader.getLatIndex(earthBox.getMaxLat());
//
// int minLonIndex = bathymetryReader.getLonIndex(earthBox.getMinLon());
// int maxLonIndex = bathymetryReader.getLonIndex(earthBox.getMaxLon());
//
// // determine length of each dimension for the chunk array to be pulled out of the netcdf source
// int latDimensionLength = maxLatIndex - minLatIndex + 1;
// int lonDimensionLength = maxLonIndex - minLonIndex + 1;
//
// // get the bathymetry height array from the netcdf source
// int[] origin = new int[]{minLatIndex, minLonIndex};
// int[] shape = new int[]{latDimensionLength, lonDimensionLength};
//
// // retrieve the bathymetry height array from netcdf
// Array heightArray = bathymetryReader.getHeightArray(origin, shape);
//
// // convert heightArray from ucar.ma2.Array format to regular java array
// short heights[][] = (short[][]) heightArray.copyToNDJavaArray();
//
// // add the value array to the earthBox
// // earthBox.setValues(heights);
// }
// }
//
//
// // loop through all the tile pixels, geolocate them, and get their bathymetry height from the
// // appropriate earthBox.
// for (int y = rectangle.y; y < rectangle.y + rectangle.height; y++) {
// for (int x = rectangle.x; x < rectangle.x + rectangle.width; x++) {
// pixelPos.setLocation(x, y);
// geoCoding.getGeoPos(pixelPos, geoPos);
//
// final short bathymetryValue;
// if (geoPos.isValid()) {
// if (geoPos.lat >= 0) {
// if (geoPos.lon >= 0) {
// bathymetryValue = earthBoxNE.getValue(geoPos);
// } else {
// bathymetryValue = earthBoxNW.getValue(geoPos);
// }
// } else {
// if (geoPos.lon >= 0) {
// bathymetryValue = earthBoxSE.getValue(geoPos);
// } else {
// bathymetryValue = earthBoxSW.getValue(geoPos);
// }
// }
// } else {
// bathymetryValue = bathymetryReader.getMissingValue();
// }
//
// targetTile.setSample(x, y, bathymetryValue);
// }
// }
//
// } catch (Exception e) {
// throw new OperatorException("Error computing tile '" + targetTile.getRectangle().toString() + "'.", e);
// }
// }
}
| 18,893 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MotherEarthBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/operator/MotherEarthBox.java | package gov.nasa.gsfc.seadas.bathymetry.operator;
import org.esa.snap.core.datamodel.GeoPos;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 10/31/13
* Time: 11:45 AM
* To change this template use File | Settings | File Templates.
*/
public class MotherEarthBox {
// establish 4 locations on the earth to minimize any effects of dateline and pole crossing
private EarthBox earthBoxNW = new EarthBox();
private EarthBox earthBoxNE = new EarthBox();
private EarthBox earthBoxSW = new EarthBox();
private EarthBox earthBoxSE = new EarthBox();
private EarthBox[] earthBoxes = {getEarthBoxNE(), getEarthBoxNW(), getEarthBoxSE(), getEarthBoxSW()};
public MotherEarthBox() {
}
public void add(GeoPos geoPos) {
if (geoPos.lat >= 0) {
if (geoPos.lon >= 0) {
getEarthBoxNE().add(geoPos);
} else {
getEarthBoxNW().add(geoPos);
}
} else {
if (geoPos.lon >= 0) {
getEarthBoxSE().add(geoPos);
} else {
getEarthBoxSW().add(geoPos);
}
}
}
public short getValue(GeoPos geoPos) {
short bathymetryValue;
if (geoPos.lat >= 0) {
if (geoPos.lon >= 0) {
bathymetryValue = earthBoxNE.getValue(geoPos);
} else {
bathymetryValue = earthBoxNW.getValue(geoPos);
}
} else {
if (geoPos.lon >= 0) {
bathymetryValue = earthBoxSE.getValue(geoPos);
} else {
bathymetryValue = earthBoxSW.getValue(geoPos);
}
}
return bathymetryValue;
}
public short getWaterSurfaceValue(GeoPos geoPos) {
short waterSurfaceValue;
if (geoPos.lat >= 0) {
if (geoPos.lon >= 0) {
waterSurfaceValue = earthBoxNE.getWaterSurfaceValue(geoPos);
} else {
waterSurfaceValue = earthBoxNW.getWaterSurfaceValue(geoPos);
}
} else {
if (geoPos.lon >= 0) {
waterSurfaceValue = earthBoxSE.getWaterSurfaceValue(geoPos);
} else {
waterSurfaceValue = earthBoxSW.getWaterSurfaceValue(geoPos);
}
}
return waterSurfaceValue;
}
public EarthBox getEarthBoxNW() {
return earthBoxNW;
}
public EarthBox getEarthBoxNE() {
return earthBoxNE;
}
public EarthBox getEarthBoxSW() {
return earthBoxSW;
}
public EarthBox getEarthBoxSE() {
return earthBoxSE;
}
public EarthBox[] getEarthBoxes() {
return earthBoxes;
}
public ArrayList<EarthBox> getFilledEarthBoxes() {
ArrayList<EarthBox> filledBoxesArrayList = new ArrayList<EarthBox>();
for (EarthBox earthBox : earthBoxes) {
if (earthBox.getMaxLat() != EarthBox.NULL_COORDINATE) {
filledBoxesArrayList.add(earthBox);
}
}
return filledBoxesArrayList;
}
}
| 3,112 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
BathymetryUtils.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/operator/BathymetryUtils.java | package gov.nasa.gsfc.seadas.bathymetry.operator;
public class BathymetryUtils {
private BathymetryUtils() {
}
/**
* Computes the side length of the images to be generated for the given resolution.
*
* @param resolution The resolution.
*
* @return The side length of the images to be generated.
*/
public static int computeSideLength(int resolution) {
final int pixelXCount = 40024000 / resolution;
final int pixelXCountPerTile = pixelXCount / 360;
// these two lines needed to create a multiple of 8
final int temp = pixelXCountPerTile / 8;
return temp * 8;
}
/**
* Creates the name of the img file for the given latitude and longitude.
*
* @param lat latitude in degree
* @param lon longitude in degree
*
* @return the name of the img file
*/
public static String createImgFileName(float lat, float lon) {
final boolean geoPosIsWest = lon < 0;
final boolean geoPosIsSouth = lat < 0;
StringBuilder result = new StringBuilder();
final String eastOrWest = geoPosIsWest ? "w" : "e";
result.append(eastOrWest);
int positiveLon = (int) Math.abs(Math.floor(lon));
if (positiveLon >= 10 && positiveLon < 100) {
result.append("0");
} else if (positiveLon < 10) {
result.append("00");
}
result.append(positiveLon);
final String northOrSouth = geoPosIsSouth ? "s" : "n";
result.append(northOrSouth);
final int positiveLat = (int) Math.abs(Math.floor(lat));
if (positiveLat < 10) {
result.append("0");
}
result.append(positiveLat);
result.append(".img");
return result.toString();
}
}
| 1,799 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
PNGSourceImage.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/operator/PNGSourceImage.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.bathymetry.operator;
import org.esa.snap.core.image.ImageHeader;
import org.esa.snap.core.util.ImageUtils;
import org.esa.snap.core.util.jai.SingleBandedSampleModel;
import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.SourcelessOpImage;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* OpImage to read from GlobCover-based water mask images.
*
* @author Thomas Storm
*/
public class PNGSourceImage extends SourcelessOpImage {
private final ZipFile zipFile;
private int resolution;
static PNGSourceImage create(Properties properties, File zipFile, int resolution) throws IOException {
final ImageHeader imageHeader = ImageHeader.load(properties, null);
return new PNGSourceImage(imageHeader, zipFile, resolution);
}
private PNGSourceImage(ImageHeader imageHeader, File zipFile, int resolution) throws IOException {
super(imageHeader.getImageLayout(),
null,
ImageUtils.createSingleBandedSampleModel(DataBuffer.TYPE_BYTE,
imageHeader.getImageLayout().getSampleModel(null).getWidth(),
imageHeader.getImageLayout().getSampleModel(null).getHeight()),
imageHeader.getImageLayout().getMinX(null),
imageHeader.getImageLayout().getMinY(null),
imageHeader.getImageLayout().getWidth(null),
imageHeader.getImageLayout().getHeight(null));
this.zipFile = new ZipFile(zipFile);
this.resolution = resolution;
// this image uses its own tile cache in order not to disturb the GPF tile cache.
setTileCache(JAI.createTileCache(50L * 1024 * 1024));
}
@Override
public Raster computeTile(int tileX, int tileY) {
Raster raster;
try {
raster = computeRawRaster(tileX, tileY);
} catch (IOException e) {
throw new RuntimeException(MessageFormat.format("Failed to read image tile ''{0} | {1}''.", tileX, tileY), e);
}
return raster;
}
private Raster computeRawRaster(int tileX, int tileY) throws IOException {
final String fileName = getFileName(tileX, tileY);
final WritableRaster targetRaster = createWritableRaster(tileX, tileY);
final ZipEntry zipEntry = zipFile.getEntry(fileName);
InputStream inputStream = null;
try {
inputStream = zipFile.getInputStream(zipEntry);
BufferedImage image = ImageIO.read(inputStream);
Raster imageData = image.getData();
for (int y = 0; y < imageData.getHeight(); y++) {
int yPos = tileYToY(tileY) + y;
for (int x = 0; x < imageData.getWidth(); x++) {
byte sample = (byte) imageData.getSample(x, y, 0);
sample = (byte) Math.abs(sample - 1);
int xPos = tileXToX(tileX) + x;
targetRaster.setSample(xPos, yPos, 0, sample);
}
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return targetRaster;
}
private WritableRaster createWritableRaster(int tileX, int tileY) {
final Point location = new Point(tileXToX(tileX), tileYToY(tileY));
final SampleModel sampleModel = new SingleBandedSampleModel(DataBuffer.TYPE_BYTE, getTileWidth(), getTileHeight());
return createWritableRaster(sampleModel, location);
}
private String getFileName(int tileX, int tileY) {
String res = String.valueOf(resolution / 1000);
return String.format("gshhs_%s_%02d_%02d.png", res, tileY, tileX);
}
}
| 4,807 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ResourceInstallationUtils.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/util/ResourceInstallationUtils.java | package gov.nasa.gsfc.seadas.bathymetry.util;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import gov.nasa.gsfc.seadas.bathymetry.operator.BathymetryOp;
import org.esa.snap.core.util.ResourceInstaller;
import org.esa.snap.core.util.SystemUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Path;
import java.util.logging.Level;
import gov.nasa.gsfc.seadas.bathymetry.ui.BathymetryData;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 1/17/13
* Time: 2:56 PM
* To change this template use File | Settings | File Templates.
*/
public class ResourceInstallationUtils {
public static String BATHYMETRY_MODULE_NAME = "seadas-bathymetry-operator";
public static String AUXDIR = "auxdata";
public static String BATHYMETRY_PATH = "gov/nasa/gsfc/seadas/bathymetry/";
public static String AUXPATH = BATHYMETRY_PATH + "operator/" + AUXDIR + "/";
public static String ICON_PATH = BATHYMETRY_PATH + "ui/icons/";
public static String getIconFilename(String icon, Class sourceClass) {
Path sourceUrl = ResourceInstaller.findModuleCodeBasePath(sourceClass);
String iconFilename = sourceUrl.toString() + ICON_PATH + icon;
return iconFilename;
}
public static void writeFileFromUrlOld(URL sourceUrl, File targetFile) throws IOException {
try {
InputStreamReader inputStreamReader = new InputStreamReader(sourceUrl.openStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
boolean exist = targetFile.createNewFile();
if (!exist) {
// file already exists
} else {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(targetFile));
String line;
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
}
bufferedWriter.close();
}
bufferedReader.close();
} catch (Exception e) {
throw new IOException("failed to write file from url: " + e.getMessage());
}
}
public static void writeFileFromUrl(URL sourceUrl, File targetFile) throws IOException {
HttpURLConnection connection = (HttpURLConnection) sourceUrl.openConnection();
connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream(targetFile);
FileCopy(in, out, 1024);
out.close();
}
public static void FileCopy(InputStream input, OutputStream output, int bufferSize) throws IOException {
byte[] buf = new byte[bufferSize];
int n = input.read(buf);
while (n >= 0) {
output.write(buf, 0, n);
n = input.read(buf);
}
output.flush();
}
public static File getTargetDir() {
return BathymetryData.getOcsswRoot().getParentFile();
}
public static File getModuleDir(String moduleName) {
if (moduleName == null) {
return null;
}
return new File(SystemUtils.getApplicationDataDir(), moduleName);
}
public static File getTargetFile(String filename) {
// File targetFile = new File(getTargetDir(), filename);
File targetModuleDir = new File(SystemUtils.getApplicationDataDir(), BATHYMETRY_MODULE_NAME);
File targetDir = new File(targetModuleDir, AUXDIR);
File targetFile = new File(targetDir, filename);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
return targetFile;
}
public static void installAuxdata(URL sourceUrl, String filename) throws IOException {
File targetFile = getTargetFile(filename);
try {
writeFileFromUrl(sourceUrl, targetFile);
} catch (IOException e) {
targetFile.delete();
throw new IOException();
}
}
public static File installAuxdata(Class sourceClass, String filename) throws IOException {
File targetFile = getTargetFile(filename);
if (!targetFile.canRead()) {
Path sourceUrl = ResourceInstaller.findModuleCodeBasePath(sourceClass);
ResourceInstaller resourceInstaller = new ResourceInstaller(sourceUrl, targetFile.getParentFile().toPath());
try {
resourceInstaller.install(filename, ProgressMonitor.NULL);
} catch (Exception e) {
throw new IOException("file failed: " + e.getMessage());
}
}
return targetFile;
}
}
| 4,723 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
RasterImageOutputter.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/util/RasterImageOutputter.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.bathymetry.util;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.core.util.math.Histogram;
import org.esa.snap.core.util.math.Range;
import gov.nasa.gsfc.seadas.bathymetry.operator.BathymetryUtils;
import javax.imageio.ImageIO;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
class RasterImageOutputter {
private static final int TILE_WIDTH = BathymetryUtils.computeSideLength(50);
public static void main(String[] args) throws IOException {
final File file = new File(args[0]);
if (file.isDirectory()) {
final File[] imgFiles = file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".img");
}
});
final ExecutorService executorService = Executors.newFixedThreadPool(6);
for (File imgFile : imgFiles) {
final File outputFile = FileUtils.exchangeExtension(imgFile, ".png");
if (!outputFile.exists()) {
executorService.submit(new ImageWriterRunnable(imgFile, outputFile));
}
}
executorService.shutdown();
while (!executorService.isTerminated()) {
try {
executorService.awaitTermination(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
final InputStream inputStream;
if (file.getName().toLowerCase().endsWith(".zip")) {
ZipFile zipFile = new ZipFile(file);
String shapefile = args[1];
final ZipEntry entry = zipFile.getEntry(shapefile);
inputStream = zipFile.getInputStream(entry);
} else {
inputStream = new FileInputStream(file);
}
writeImage(inputStream, new File(args[args.length - 1]));
}
}
private static boolean writeImage(InputStream inputStream, File outputFile) throws IOException {
WritableRaster targetRaster = Raster.createPackedRaster(0, TILE_WIDTH, TILE_WIDTH, 1, 1,
new Point(0, 0));
final byte[] data = ((DataBufferByte) targetRaster.getDataBuffer()).getData();
inputStream.read(data);
final BufferedImage image = new BufferedImage(TILE_WIDTH, TILE_WIDTH, BufferedImage.TYPE_BYTE_BINARY);
image.setData(targetRaster);
boolean valid = validateImage(image);
ImageIO.write(image, "png", outputFile);
return valid;
}
private static boolean validateImage(BufferedImage image) {
final Histogram histogram = Histogram.computeHistogram(image, null, 3, new Range(0, 3));
final int[] binCounts = histogram.getBinCounts();
// In both bins must be values
for (int binCount : binCounts) {
if (binCount == 0) {
return false;
}
}
return true;
}
private static class ImageWriterRunnable implements Runnable {
private File inputFile;
private File outputFile;
private ImageWriterRunnable(File inputFile, File outputFile) {
this.inputFile = inputFile;
this.outputFile = outputFile;
}
@Override
public void run() {
InputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(inputFile);
final boolean valid = writeImage(fileInputStream, outputFile);
if(!valid) {
System.out.printf("Not valid: %s%n", outputFile);
}else {
System.out.printf("Written: %s%n", outputFile);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
} | 5,463 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ImageDescriptor.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/util/ImageDescriptor.java | package gov.nasa.gsfc.seadas.bathymetry.util;
import java.io.*;
/**
*/
public interface ImageDescriptor {
int getImageWidth();
int getImageHeight();
int getTileWidth();
int getTileHeight();
File getAuxdataDir();
String getZipFileName();
}
| 272 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ImageDescriptorBuilder.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/util/ImageDescriptorBuilder.java | package gov.nasa.gsfc.seadas.bathymetry.util;
import java.io.*;
public class ImageDescriptorBuilder {
private int imageWidth;
private int imageHeight;
private int tileWidth;
private int tileHeight;
private File auxdataDir;
private String zipFileName;
public ImageDescriptorBuilder width(int imageWidth) {
this.imageWidth = imageWidth;
return this;
}
public ImageDescriptorBuilder height(int imageHeight) {
this.imageHeight = imageHeight;
return this;
}
public ImageDescriptorBuilder tileWidth(int tileWidth) {
this.tileWidth = tileWidth;
return this;
}
public ImageDescriptorBuilder tileHeight(int tileHeight) {
this.tileHeight = tileHeight;
return this;
}
public ImageDescriptorBuilder auxdataDir(File auxdataDir) {
this.auxdataDir = auxdataDir;
return this;
}
public ImageDescriptorBuilder zipFileName(String fileName) {
this.zipFileName = fileName;
return this;
}
public ImageDescriptor build() {
final ImageDescriptorImpl imageDescriptor = new ImageDescriptorImpl();
imageDescriptor.imageWidth = imageWidth;
imageDescriptor.imageHeight = imageHeight;
imageDescriptor.tileWidth = tileWidth;
imageDescriptor.tileHeight = tileHeight;
imageDescriptor.auxdataDir = auxdataDir;
imageDescriptor.zipFileName = zipFileName;
return imageDescriptor;
}
private class ImageDescriptorImpl implements ImageDescriptor {
private int imageWidth;
private int imageHeight;
private int tileWidth;
private int tileHeight;
private File auxdataDir;
private String zipFileName;
@Override
public int getImageWidth() {
return imageWidth;
}
@Override
public int getImageHeight() {
return imageHeight;
}
@Override
public int getTileWidth() {
return tileWidth;
}
@Override
public int getTileHeight() {
return tileHeight;
}
@Override
public File getAuxdataDir() {
return auxdataDir;
}
@Override
public String getZipFileName() {
return zipFileName;
}
}
}
| 2,359 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ShapeFileRasterizer.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/util/ShapeFileRasterizer.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.bathymetry.util;
import gov.nasa.gsfc.seadas.bathymetry.operator.BathymetryUtils;
import org.geotools.coverage.grid.GridEnvelope2D;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.MapContent;
import org.geotools.map.MapViewport;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.referencing.operation.builder.GridToEnvelopeMapper;
import org.geotools.renderer.lite.StreamingRenderer;
import org.geotools.styling.*;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.FilterFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.datum.PixelInCell;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Responsible for transferring shapefiles containing a land/water-mask into a rasterized image.
*
* @author Thomas Storm
*/
class ShapeFileRasterizer {
private final File targetDir;
private final String tempDir;
ShapeFileRasterizer(File targetDir) {
this.targetDir = targetDir;
tempDir = System.getProperty("java.io.tmpdir", ".");
}
/**
* The main method of this tool.
*
* @param args Three arguments are needed: 1) directory containing shapefiles. 2) target directory.
* 3) resolution in meters / pixel.
* @throws java.io.IOException If some IO error occurs.
*/
public static void main(String[] args) throws IOException {
final File resourceDir = new File(args[0]);
final File targetDir = new File(args[1]);
targetDir.mkdirs();
int sideLength = BathymetryUtils.computeSideLength(Integer.parseInt(args[2]));
boolean createImage = false;
if (args.length == 4) {
createImage = Boolean.parseBoolean(args[3]);
}
final ShapeFileRasterizer rasterizer = new ShapeFileRasterizer(targetDir);
rasterizer.rasterizeShapeFiles(resourceDir, sideLength, createImage);
}
void rasterizeShapeFiles(File directory, int tileSize, boolean createImage) throws IOException {
File[] shapeFiles = directory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".zip");
}
});
if (shapeFiles != null) {
rasterizeShapeFiles(shapeFiles, tileSize, createImage);
}
File[] subdirs = directory.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
if (subdirs != null) {
for (File subDir : subdirs) {
rasterizeShapeFiles(subDir, tileSize, createImage);
}
}
}
void rasterizeShapeFiles(File[] zippedShapeFiles, int tileSize, boolean createImage) {
final ExecutorService executorService = Executors.newFixedThreadPool(12);
for (int i = 0; i < zippedShapeFiles.length; i++) {
File shapeFile = zippedShapeFiles[i];
int shapeFileIndex = i + 1;
ShapeFileRunnable runnable = new ShapeFileRunnable(shapeFile, tileSize, shapeFileIndex,
zippedShapeFiles.length, createImage);
executorService.submit(runnable);
}
executorService.shutdown();
while (!executorService.isTerminated()) {
try {
executorService.awaitTermination(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
BufferedImage createImage(File shapeFile, int tileSize) throws Exception {
CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;
final String shapeFileName = shapeFile.getName();
final ReferencedEnvelope referencedEnvelope = parseEnvelopeFromShapeFileName(shapeFileName, crs);
final MapViewport viewport = new MapViewport();
viewport.setBounds(referencedEnvelope);
viewport.setCoordinateReferenceSystem(crs);
//MapContext context = new DefaultMapContext(crs);
MapContent mapContent = new MapContent();
mapContent.setViewport(viewport);
final URL shapeFileUrl = shapeFile.toURI().toURL();
final FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = getFeatureSource(shapeFileUrl);
org.geotools.map.FeatureLayer featureLayer = new org.geotools.map.FeatureLayer(featureSource, createPolygonStyle());
mapContent.addLayer(featureLayer);
BufferedImage landMaskImage = new BufferedImage(tileSize, tileSize, BufferedImage.TYPE_BYTE_BINARY);
Graphics2D graphics = landMaskImage.createGraphics();
StreamingRenderer renderer = new StreamingRenderer();
renderer.setMapContent(mapContent);
Rectangle paintArea = new Rectangle(0, 0, tileSize, tileSize);
// the transform is computed here, because it ensures that the pixel anchor is in the pixel center and
// not at the corner as the StreamingRenderer does by default
AffineTransform transform = createWorldToScreenTransform(referencedEnvelope, paintArea);
renderer.paint(graphics, paintArea, referencedEnvelope, transform);
return landMaskImage;
}
private AffineTransform createWorldToScreenTransform(ReferencedEnvelope referencedEnvelope, Rectangle paintArea) throws Exception {
GridEnvelope2D gridRange = new GridEnvelope2D(paintArea);
final GridToEnvelopeMapper mapper = new GridToEnvelopeMapper(gridRange, referencedEnvelope);
mapper.setPixelAnchor(PixelInCell.CELL_CENTER);
return mapper.createAffineTransform().createInverse();
}
private ReferencedEnvelope parseEnvelopeFromShapeFileName(String shapeFileName, CoordinateReferenceSystem crs) {
int lonMin = Integer.parseInt(shapeFileName.substring(1, 4));
int lonMax;
if (shapeFileName.startsWith("e")) {
lonMax = lonMin + 1;
} else if (shapeFileName.startsWith("w")) {
lonMin--;
lonMin = lonMin * -1;
lonMax = lonMin--;
} else {
throw new IllegalStateException("Wrong shapefile-name: '" + shapeFileName + "'.");
}
int latMin = Integer.parseInt(shapeFileName.substring(5, 7));
int latMax;
if (shapeFileName.charAt(4) == 'n') {
latMax = latMin + 1;
} else if (shapeFileName.charAt(4) == 's') {
latMin--;
latMin = latMin * -1;
latMax = latMin--;
} else {
throw new IllegalStateException("Wrong shapefile-name: '" + shapeFileName + "'.");
}
return new ReferencedEnvelope(lonMin, lonMax, latMin, latMax, crs);
}
private void writeToFile(BufferedImage image, String name, boolean createImage) throws IOException {
String fileName = getFilenameWithoutExtension(name);
fileName = fileName.substring(0, fileName.length() - 1);
String imgFileName = fileName + ".img";
File outputFile = new File(targetDir.getAbsolutePath(), imgFileName);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
try {
byte[] data = ((DataBufferByte) image.getData().getDataBuffer()).getData();
fileOutputStream.write(data);
if (createImage) {
ImageIO.write(image, "png", new File(targetDir.getAbsolutePath(), fileName + ".png"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
List<File> createTempFiles(ZipFile zipFile) {
final Enumeration<? extends ZipEntry> entries = zipFile.entries();
List<File> tempShapeFiles;
try {
tempShapeFiles = unzipTempFiles(zipFile, entries);
} catch (IOException e) {
throw new IllegalStateException(
"Error generating temp files from shapefile '" + zipFile.getName() + "'.", e);
}
return tempShapeFiles;
}
private List<File> unzipTempFiles(ZipFile zipFile, Enumeration<? extends ZipEntry> entries) throws
IOException {
List<File> files = new ArrayList<File>();
while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
File file = readIntoTempFile(zipFile, entry);
files.add(file);
}
return files;
}
private File readIntoTempFile(ZipFile zipFile, ZipEntry entry) throws IOException {
File file = new File(tempDir, entry.getName());
final InputStream reader = zipFile.getInputStream(entry);
final FileOutputStream writer = new FileOutputStream(file);
try {
byte[] buffer = new byte[1024 * 1024];
int bytesRead = reader.read(buffer);
while (bytesRead != -1) {
writer.write(buffer, 0, bytesRead);
bytesRead = reader.read(buffer);
}
} finally {
reader.close();
writer.close();
}
return file;
}
@SuppressWarnings({"ResultOfMethodCallIgnored"})
private void deleteTempFiles(List<File> tempFiles) {
for (File tempFile : tempFiles) {
tempFile.delete();
}
tempFiles.clear();
}
private static String getFilenameWithoutExtension(String fileName) {
int i = fileName.lastIndexOf('.');
if (i > 0 && i < fileName.length() - 1) {
return fileName.substring(0, i);
}
return fileName;
}
private FeatureSource<SimpleFeatureType, SimpleFeature> getFeatureSource(URL url) throws IOException {
Map<String, Object> parameterMap = new HashMap<String, Object>();
parameterMap.put(ShapefileDataStoreFactory.URLP.key, url);
parameterMap.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key, Boolean.TRUE);
DataStore shapefileStore = DataStoreFinder.getDataStore(parameterMap);
String typeName = shapefileStore.getTypeNames()[0]; // Shape files do only have one type name
FeatureSource<SimpleFeatureType, SimpleFeature> featureSource;
featureSource = shapefileStore.getFeatureSource(typeName);
return featureSource;
}
private Style createPolygonStyle() {
StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(null);
FilterFactory filterFactory = CommonFactoryFinder.getFilterFactory(null);
PolygonSymbolizer symbolizer = styleFactory.createPolygonSymbolizer();
org.geotools.styling.Stroke stroke = styleFactory.createStroke(
filterFactory.literal("#FFFFFF"),
filterFactory.literal(0.0)
);
symbolizer.setStroke(stroke);
Fill fill = styleFactory.createFill(
filterFactory.literal("#FFFFFF"),
filterFactory.literal(1.0)
);
symbolizer.setFill(fill);
Rule rule = styleFactory.createRule();
rule.symbolizers().add(symbolizer);
FeatureTypeStyle fts = styleFactory.createFeatureTypeStyle();
fts.rules().add(rule);
Style style = styleFactory.createStyle();
style.featureTypeStyles().add(fts);
return style;
}
private class ShapeFileRunnable implements Runnable {
private final File shapeFile;
private int tileSize;
private int index;
private int shapeFileCount;
private boolean createImage;
ShapeFileRunnable(File shapeFile, int tileSize, int shapeFileIndex, int shapeFileCount, boolean createImage) {
this.shapeFile = shapeFile;
this.tileSize = tileSize;
this.index = shapeFileIndex;
this.shapeFileCount = shapeFileCount;
this.createImage = createImage;
}
@Override
public void run() {
try {
List<File> tempShapeFiles;
ZipFile zipFile = new ZipFile(shapeFile);
try {
tempShapeFiles = createTempFiles(zipFile);
} finally {
zipFile.close();
}
for (File file : tempShapeFiles) {
if (file.getName().endsWith("shp")) {
final BufferedImage image = createImage(file, tileSize);
writeToFile(image, shapeFile.getName(), createImage);
}
}
deleteTempFiles(tempShapeFiles);
System.out.printf("File %d of %d%n", index, shapeFileCount);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
} | 14,350 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
LandMaskRasterCreator.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-bathymetry-operator/src/main/java/gov/nasa/gsfc/seadas/bathymetry/util/LandMaskRasterCreator.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package gov.nasa.gsfc.seadas.bathymetry.util;
import com.bc.ceres.glevel.MultiLevelImage;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
/**
* @author Thomas Storm
*/
public class LandMaskRasterCreator {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
printUsage();
System.exit(-1);
}
final LandMaskRasterCreator landMaskRasterCreator = new LandMaskRasterCreator(args[1]);
final String sourcePath = args[0];
landMaskRasterCreator.createRasterFile(sourcePath);
}
private static void printUsage() {
System.out.println("Usage: ");
System.out.println(" LandMaskRasterCreator $sourceFile $targetPath");
System.out.println(" System will exit.");
}
private final String targetPath;
public LandMaskRasterCreator(String targetPath) {
this.targetPath = targetPath;
}
void createRasterFile(String sourcePath) throws IOException {
validateSourcePath(sourcePath);
final Product lwProduct = readLwProduct(sourcePath);
final Band band = lwProduct.getBand("lw-mask");
final MultiLevelImage sourceImage = band.getSourceImage();
final int numXTiles = sourceImage.getNumXTiles();
final int numYTiles = sourceImage.getNumYTiles();
final int tileWidth = sourceImage.getTileWidth();
final int tileHeight = sourceImage.getTileHeight();
final BufferedImage image = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_BYTE_BINARY);
int count = 0;
for (int tileX = 0; tileX < numXTiles; tileX++) {
for (int tileY = 0; tileY < numYTiles; tileY++) {
count++;
final Raster tile = sourceImage.getTile(tileX, tileY);
final int minX = tile.getMinX();
for (int x = minX; x < minX + tile.getWidth(); x++) {
final int minY = tile.getMinY();
for (int y = minY; y < minY + tile.getHeight(); y++) {
image.getRaster().setSample(x - minX, y - minY, 0, (byte) tile.getSample(x, y, 0));
}
}
image.setData(sourceImage.getTile(tileX, tileY));
System.out.println("Writing image " + count + "/" + numXTiles * numYTiles + ".");
ImageIO.write(image, "png", new File(targetPath, String.format("%d-%d.png", tileX, tileY)));
}
}
}
private Product readLwProduct(String sourcePath) {
final Product lwProduct;
try {
lwProduct = ProductIO.readProduct(sourcePath);
} catch (IOException e) {
throw new IllegalArgumentException(MessageFormat.format("Unable to read from file ''{0}''.", sourcePath), e);
}
return lwProduct;
}
void validateSourcePath(String sourcePath) {
final File path = new File(sourcePath);
if (path.isDirectory()) {
throw new IllegalArgumentException(MessageFormat.format("Source path ''''{0}'' points to a directory, but " +
"must point to a file.", sourcePath));
}
if (!path.exists()) {
throw new IllegalArgumentException(MessageFormat.format("Source path ''{0}'' does not exist.", sourcePath));
}
}
}
| 4,388 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ProxyPanelAutomationHelper.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-installer/izpack-panels/src/main/java/com/izforge/izpack/panels/mypanels/ProxyPanelAutomationHelper.java | import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.api.adaptator.impl.XMLElementImpl;
import com.izforge.izpack.api.data.InstallData;
import com.izforge.izpack.api.data.Overrides;
import com.izforge.izpack.api.data.Variables;
import com.izforge.izpack.api.exception.InstallerException;
import com.izforge.izpack.installer.automation.PanelAutomation;
import static com.shuttle.panel.ProxyPanel.ENTRIES;
import java.util.*;
import java.util.logging.Logger;
/**
* Functions to support automated usage of the ProxyPanel.
*
*/
public class ProxyPanelAutomationHelper implements PanelAutomation {
private static final Logger LOGGER = Logger.getLogger(ProxyPanelAutomationHelper.class.getName());
// ------------------------------------------------------
// automatic script section keys
// ------------------------------------------------------
private static final String AUTO_KEY_ENTRY = "entry";
// ------------------------------------------------------
// automatic script keys attributes
// ------------------------------------------------------
private static final String AUTO_ATTRIBUTE_KEY = "key";
private static final String AUTO_ATTRIBUTE_VALUE = "value";
/**
* Default constructor, used during automated installation.
*/
public ProxyPanelAutomationHelper() {
}
/**
* Serialize state to XML and insert under panelRoot.
*
* @param installData The installation installData GUI.
* @param rootElement The XML root element of the panels blackbox tree.
*/
@Override
public void createInstallationRecord(InstallData installData, IXMLElement rootElement) {
IXMLElement dataElement;
for (String key : ENTRIES) {
dataElement = new XMLElementImpl(AUTO_KEY_ENTRY, rootElement);
dataElement.setAttribute(AUTO_ATTRIBUTE_KEY, key);
String value = installData.getVariable(key);
dataElement.setAttribute(AUTO_ATTRIBUTE_VALUE, value);
rootElement.addChild(dataElement);
}
}
/**
* Deserialize state from panelRoot and set installData variables
* accordingly.
*
* @param idata The installation installDataGUI.
* @param panelRoot The XML root element of the panels blackbox tree.
* @throws InstallerException if some elements are missing.
*/
@Override
public void runAutomated(InstallData idata, IXMLElement panelRoot) throws InstallerException {
String variable;
String value;
List<IXMLElement> userEntries = panelRoot.getChildrenNamed(AUTO_KEY_ENTRY);
HashSet<String> blockedVariablesList = new HashSet<String>();
// ----------------------------------------------------
// retieve each entry and substitute the associated
// variable
// ----------------------------------------------------
Variables variables = idata.getVariables();
for (IXMLElement dataElement : userEntries) {
variable = dataElement.getAttribute(AUTO_ATTRIBUTE_KEY);
// Substitute variable used in the 'value' field
value = dataElement.getAttribute(AUTO_ATTRIBUTE_VALUE);
value = variables.replace(value);
LOGGER.fine("Setting variable " + variable + " to " + value);
idata.setVariable(variable, value);
blockedVariablesList.add(variable);
}
idata.getVariables().registerBlockedVariableNames(blockedVariablesList, panelRoot.getName());
}
@Override
public void processOptions(InstallData installData, Overrides overrides) {
}
} | 3,659 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ProxyPanel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-installer/izpack-panels/src/main/java/com/izforge/izpack/panels/mypanels/ProxyPanel.java | import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.api.data.Panel;
import com.izforge.izpack.api.resource.Resources;
import com.izforge.izpack.gui.IzPanelLayout;
import static com.izforge.izpack.gui.LayoutConstants.NEXT_LINE;
import com.izforge.izpack.gui.log.Log;
import com.izforge.izpack.installer.data.GUIInstallData;
import com.izforge.izpack.installer.gui.InstallerFrame;
import com.izforge.izpack.installer.gui.IzPanel;
import com.nellarmonia.commons.utils.NellCipher;
import java.awt.Insets;
import java.awt.LayoutManager2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* A custom panel representing a proxy configuration.
*
* @author Samir Hadzic
*/
public class ProxyPanel extends IzPanel {
static final List<String> ENTRIES = new ArrayList();
static final String USE_PROXY = "client.useproxy";
static final String USE_DEFAULT_CONFIG = "client.proxyusedefaultconfiguration";
static final String PROXY_HOST = "client.proxyhost";
static final String PROXY_PORT = "client.proxyport";
static final String PROXY_PORT_ADDIN = "client.proxyportaddin";
static final String USE_CREDENTIALS = "client.proxyusecredentials";
static final String USE_SHUTTLE_CREDENTIALS = "client.proxyuseshuttlecredentials";
static final String PROXY_LOGIN = "client.proxylogin";
static final String PROXY_PASSWORD = "client.proxypassword";
static {
ENTRIES.add(USE_PROXY);
ENTRIES.add(USE_DEFAULT_CONFIG);
ENTRIES.add(PROXY_HOST);
ENTRIES.add(PROXY_PORT);
ENTRIES.add(USE_CREDENTIALS);
ENTRIES.add(USE_SHUTTLE_CREDENTIALS);
ENTRIES.add(PROXY_LOGIN);
ENTRIES.add(PROXY_PASSWORD);
/**
* Creates an installation record for unattended installations on
* {@link UserInputPanel}, created during GUI installations.
*
* @param rootElement
*/
@Override
public void createInstallationRecord(IXMLElement rootElement) {
new ProxyPanelAutomationHelper().createInstallationRecord(installData, rootElement);
}
/**
* Configure the first part by adding the proxy configuration.
*/
private void configureProxySettings() {
defaultProxy = new JRadioButton("Use default proxy server");
//Default proxy must be selected
defaultProxy.setSelected(true);
defaultProxy.setMargin(indentedInset);
followingProxy = new JRadioButton("Use following proxy server");
followingProxy.setMargin(indentedInset);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(defaultProxy);
buttonGroup.add(followingProxy);
checkboxProxy = new JCheckBox("Use proxy server");
//If we are on this panel, we want to use a proxy.
checkboxProxy.setSelected(true);
checkboxProxy.setMargin(new Insets(50, 70, 0, 0));
checkboxProxy.addChangeListener(uiChangeListener);
followingProxy.addChangeListener(uiChangeListener);
add(checkboxProxy, NEXT_LINE);
add(defaultProxy, NEXT_LINE);
add(followingProxy, NEXT_LINE);
JLabel hostLabel = new JLabel("Host");
hostLabel.setBorder(paddingBorder);
hostField = new JTextField(TEXTFIELD_LENGTH);
JLabel portLabel = new JLabel("Port");
portLabel.setBorder(paddingBorder);
portField = new JTextField(TEXTFIELD_LENGTH);
add(hostLabel, NEXT_LINE);
add(hostField, NEXT_COLUMN);
add(portLabel, NEXT_LINE);
add(portField, NEXT_COLUMN);
}
/**
* Configure the second part by adding all the credentials configuration.
*/
private void configureProxyCredentials() {
followingCredentials = new JRadioButton("Use the following credentials");
followingCredentials.setMargin(indentedInset);
followingCredentials.setSelected(true);
installData.setVariable(USE_PROXY, Boolean.toString(checkboxProxy.isSelected()));
installData.setVariable(USE_DEFAULT_CONFIG, Boolean.toString(defaultProxy.isSelected()));
if (followingProxy.isSelected()) {
installData.setVariable(PROXY_HOST, hostField.getText());
installData.setVariable(PROXY_PORT, portField.getText());
if (!portField.getText().isEmpty()) {
installData.setVariable(PROXY_PORT_ADDIN, portField.getText());
}
}
//Proxy credentials
installData.setVariable(USE_CREDENTIALS, Boolean.toString(checkboxCredentials.isSelected()));
if (checkboxCredentials.isSelected()) {
installData.setVariable(USE_SHUTTLE_CREDENTIALS, Boolean.toString(shuttleCredentials.isSelected()));
if (followingCredentials.isSelected()) {
installData.setVariable(PROXY_LOGIN, loginField.getText());
//We encrypt the password.
installData.setVariable(PROXY_PASSWORD, NellCipher.encryptWithMarker(new String(passwordField.getPassword()), true));
}
}
}
/**
* The panel is consider valid only if the passwords are equals.
*
* @return
*/
@Override
public boolean isValidated() {
if (!Arrays.equals(passwordField.getPassword(), retypePasswordField.getPassword())) {
emitWarning("Password mismatch", "Both passwords must match.");
return false;
}
return true;
}
} | 6,087 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MyHelloPanel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-installer/izpack-panels/src/main/java/com/izforge/izpack/panels/mypanels/MyHelloPanel.java | /*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2002 Jan Blok
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.izforge.izpack.panels.mypanels;
import com.izforge.izpack.api.GuiId;
import com.izforge.izpack.api.data.Info;
import com.izforge.izpack.api.data.Panel;
import com.izforge.izpack.api.resource.Resources;
import com.izforge.izpack.gui.IzPanelLayout;
import com.izforge.izpack.gui.LabelFactory;
import com.izforge.izpack.gui.LayoutConstants;
import com.izforge.izpack.gui.log.Log;
import com.izforge.izpack.installer.gui.InstallerFrame;
import com.izforge.izpack.installer.gui.IzPanel;
import com.izforge.izpack.installer.data.GUIInstallData;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
/**
* The Hello panel class.
*
* @author Julien Ponge
*/
public class MyHelloPanel extends IzPanel
{
/**
*
*/
private static final long serialVersionUID = 3257848774955905587L;
/**
* The constructor.
*
* @param parent The parent.
* @param idata The installation installDataGUI.
*/
public MyHelloPanel(Panel panel, InstallerFrame parent, GUIInstallData idata, Resources resources, Log log)
{
this(panel, parent, idata, new IzPanelLayout(log), resources);
}
/**
* Creates a new MyHelloPanel object with the given layout manager. Valid layout manager are the
* IzPanelLayout and the GridBagLayout. New panels should be use the IzPanelLaout. If lm is
* null, no layout manager will be created or initialized.
*
* @param parent The parent IzPack installer frame.
* @param idata The installer internal installDataGUI.
* @param layout layout manager to be used with this IzPanel
*/
public MyHelloPanel(Panel panel, InstallerFrame parent, GUIInstallData idata, LayoutManager2 layout, Resources resources)
{
// Layout handling. This panel was changed from a mixed layout handling
// with GridBagLayout and BoxLayout to IzPanelLayout. It can be used as an
// example how to use the IzPanelLayout. For this there are some comments
// which are excrescent for a "normal" panel.
// Set a IzPanelLayout as layout for this panel.
// This have to be the first line during layout if IzPanelLayout will be used.
//com.izforge.izpack.installer.gui.InstallerFrame cannot be converted to com.izforge.izpack.api.data.Panel
/*
public IzPanel(Panel panel, InstallerFrame parent, GUIInstallData installData, Resources resources)
*/
super(panel, parent, idata, layout, resources);
// We create and put the labels
String welcomeText = installData.getAttribute("welcome1") + idata.getInfo().getAppName() + " "
+ idata.getInfo().getAppVersion() + installData.getAttribute("welcome2");
JLabel welcomeLabel = LabelFactory.create(welcomeText, parent.getIcons().get("host"), LEADING);
welcomeLabel.setName(GuiId.HELLO_PANEL_LABEL.id);
// IzPanelLayout is a constraint orientated layout manager. But if no constraint is
// given, a default will be used. It starts in the first line.
// NEXT_LINE have to insert also in the first line!!
add(welcomeLabel, NEXT_LINE);
// Yes, there exist also a strut for the IzPanelLayout.
// But the strut will be only used for one cell. A vertical strut will be use
// NEXT_ROW, a horizontal NEXT_COLUMN. For more information see the java doc.
// add(IzPanelLayout.createVerticalStrut(20));
// But for a strut you have to define a fixed height. Alternative it is possible
// to create a paragraph gap which is configurable.
add(IzPanelLayout.createParagraphGap());
ArrayList<Info.Author> authors = idata.getInfo().getAuthors();
if (!authors.isEmpty())
{
String authorText = (String)installData.getAttribute("MyHelloPanel.authors");
JLabel appAuthorsLabel = LabelFactory.create(authorText, parent.getIcons()
.get("information"), LEADING);
// If nothing will be sad to the IzPanelLayout the position of an add will be
// determined in the default constraint. For labels it is CURRENT_ROW, NEXT_COLUMN.
// But at this point we would place the label in the next row. It is possible
// to create an IzPanelConstraint with this options, but it is also possible to
// use simple the NEXT_LINE object as constraint. Attention!! Do not use
// LayoutConstants.NEXT_ROW else LayoutConstants.NEXT_LINE because NEXT_ROW is an
// int and with it an other add method will be used without any warning (there the
// parameter will be used as position of the component in the panel, not the
// layout manager.
add(appAuthorsLabel, LayoutConstants.NEXT_LINE);
JLabel label;
for (Info.Author author : authors)
{
String email = (author.getEmail() != null && author.getEmail().length() > 0) ? (" <"
+ author.getEmail() + ">") : "";
label = LabelFactory.create(" - " + author.getName() + email, parent.getIcons()
.get("empty"), LEADING);
add(label, NEXT_LINE);
}
add(IzPanelLayout.createParagraphGap());
}
if (idata.getInfo().getAppURL() != null)
{
String urlText = installData.getAttribute("MyHelloPanel.url") + idata.getInfo().getAppURL();
JLabel appURLLabel = LabelFactory.create(urlText, parent.getIcons().get("bookmark"),
LEADING);
add(appURLLabel, LayoutConstants.NEXT_LINE);
}
// At end of layouting we should call the completeLayout method also they do nothing.
getLayoutHelper().completeLayout();
}
/**
* Indicates wether the panel has been validated or not.
*
* @return Always true.
*/
public boolean isValidated()
{
return true;
}
}
| 6,690 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ProxyConsolePanel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-installer/izpack-panels/src/main/java/com/izforge/izpack/panels/mypanels/ProxyConsolePanel.java | import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.api.data.InstallData;
import com.izforge.izpack.installer.console.AbstractConsolePanel;
import com.izforge.izpack.installer.console.ConsolePanel;
import com.izforge.izpack.installer.panel.PanelView;
import com.izforge.izpack.util.Console;
import com.nellarmonia.commons.utils.NellCipher;
import static com.shuttle.panel.ProxyPanel.PROXY_HOST;
import static com.shuttle.panel.ProxyPanel.PROXY_LOGIN;
import static com.shuttle.panel.ProxyPanel.PROXY_PASSWORD;
import static com.shuttle.panel.ProxyPanel.PROXY_PORT;
import static com.shuttle.panel.ProxyPanel.PROXY_PORT_ADDIN;
import static com.shuttle.panel.ProxyPanel.USE_CREDENTIALS;
import static com.shuttle.panel.ProxyPanel.USE_DEFAULT_CONFIG;
import static com.shuttle.panel.ProxyPanel.USE_PROXY;
import static com.shuttle.panel.ProxyPanel.USE_SHUTTLE_CREDENTIALS;
import java.util.Properties;
/**
* The ProxyPanel console helper class.
*
*/
public class ProxyConsolePanel extends AbstractConsolePanel {
private InstallData installData;
private boolean useProxy = false;
private boolean useDefaultProxy = true;
private boolean useFollowingProxy = false;
private String proxyHost = "";
private String proxyPort = "";
private boolean useCredentials = false;
private boolean useFollowingCredentials = true;
private String login = "";
private String password = "";
private boolean useShuttleCredentials = false;
/**
* Constructs a <tt>ProxyConsolePanel</tt>.
*
* @param panel the parent panel/view. May be {@code null}
* @param installData
*/
public ProxyConsolePanel(PanelView<ConsolePanel> panel, InstallData installData) {
super(panel);
this.installData = installData;
}
/**
* Runs the panel using the specified console.
*
* @param installData the installation data
* @param console the console
* @return <tt>true</tt> if the panel ran successfully, otherwise
* <tt>false</tt>
*/
@Override
public boolean run(InstallData installData, Console console) {
this.installData = installData;
printHeadLine(installData, console);
while (!promptUseProxy(console)) {
//Continue to ask
}
if (useProxy) {
if (!promptUseProxyRadio(console)) {
return promptRerunPanel(installData, console);
}
if (!promptUseCredentials(console)) {
return promptRerunPanel(installData, console);
}
if (useCredentials) {
if (!promptUseCredentialRadio(console)) {
return promptRerunPanel(installData, console);
}
}
}
registerInputs();
return promptEndPanel(installData, console);
}
private void registerInputs() {
//Proxy
installData.setVariable(USE_PROXY, Boolean.toString(useProxy));
installData.setVariable(USE_DEFAULT_CONFIG, Boolean.toString(useDefaultProxy));
if (useFollowingProxy) {
installData.setVariable(PROXY_HOST, proxyHost);
installData.setVariable(PROXY_PORT, proxyPort);
if (!proxyPort.isEmpty()) {
installData.setVariable(PROXY_PORT_ADDIN, proxyPort);
}
}
//Proxy credentials
installData.setVariable(USE_CREDENTIALS, Boolean.toString(useCredentials));
if (useCredentials) {
installData.setVariable(USE_SHUTTLE_CREDENTIALS, Boolean.toString(useShuttleCredentials));
if (useFollowingCredentials) {
installData.setVariable(PROXY_LOGIN, login);
//We encrypt the password.
installData.setVariable(PROXY_PASSWORD, NellCipher.encryptWithMarker(password, true));
}
}
}
private boolean promptUseProxyRadio(Console console) {
console.println("Proxy use");
console.println("0 [x] Use default proxy");
console.println("1 [ ] Use custom proxy");
int value = console.prompt("Input selection:", 0, 1, 0, -1);
if (value != -1) {
useDefaultProxy = value == 0;
useFollowingProxy = value == 1;
if (useFollowingProxy) {
console.println("Using custom proxy.");
proxyHost = console.prompt("Proxy host : ", "");
proxyPort = console.prompt("Proxy port : ", "");
}
return true;
} else {
return false;
}
}
private boolean promptUseProxy(Console console) {
console.println(" [x] Use Proxy");
int value = console.prompt("Enter 1 to select, 0 to deselect: ", 0, 1, 1, -1);
if (value != -1) {
useProxy = value == 1;
return true;
} else {
return false;
}
}
private boolean promptUseCredentials(Console console) {
console.println(" [ ] Use Credentials");
int value = console.prompt("Enter 1 to select, 0 to deselect: ", 0, 1, 1, -1);
if (value != -1) {
useCredentials = value == 1;
return true;
} else {
return false;
}
}
private boolean promptUseCredentialRadio(Console console) {
console.println("Credential use");
console.println("0 [x] Use following credentials");
console.println("1 [ ] Use shuttle credentials");
int value = console.prompt("Input selection:", 0, 1, 0, -1);
if (value != -1) {
useFollowingCredentials = value == 0;
useShuttleCredentials = value == 1;
if (useFollowingCredentials) {
console.println("Using following credentials.");
login = console.prompt("Username : ", "");
String firstPwd = console.prompt("Password : ", "");
String secondtPwd = console.prompt("Retype password : ", "");
if (!firstPwd.equals(secondtPwd)) {
console.println("Passwords mismatch.");
return false;
} else {
password = firstPwd;
return true;
}
}
return true;
} else {
return false;
}
}
@Override
public void createInstallationRecord(IXMLElement panelRoot) {
new ProxyPanelAutomationHelper().createInstallationRecord(installData, panelRoot);
}
@Override
public boolean run(InstallData id, Properties prprts) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| 6,779 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
WriteImageOpTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-writeimage-operator/src/test/java/gov/nasa/gsfc/seadas/writeimage/WriteImageOpTest.java | package gov.nasa.gsfc.seadas.writeimage;
import com.bc.ceres.core.ProgressMonitor;
import gov.nasa.gsfc.seadas.writeimage.operator.WriteImageOp;
import junit.framework.TestCase;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.Operator;
import org.esa.snap.core.gpf.OperatorSpi;
import org.esa.snap.core.gpf.Tile;
import org.esa.snap.core.gpf.annotations.OperatorMetadata;
import org.esa.snap.core.gpf.annotations.TargetProduct;
import org.esa.snap.core.gpf.common.WriteOp;
import org.esa.snap.core.gpf.graph.Graph;
import org.esa.snap.core.gpf.graph.GraphIO;
import org.esa.snap.core.gpf.graph.GraphProcessor;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.FileUtils;
import javax.media.jai.JAI;
import javax.media.jai.TileScheduler;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.StringReader;
/**
* Created by aabduraz on 7/30/15.
*/
public class WriteImageOpTest extends TestCase {
public static final String SNAP_TEST_DATA_INPUT_DIR_PROPERTY_NAME = "org.esa.snap.testdata.in";
public static final String SNAP_TEST_DATA_OUTPUT_DIR_PROPERTY_NAME = "org.esa.snap.testdata.out";
public static final String SNAP_TEST_DATA_INPUT_DIR_DEFAULT_PATH = "testdata" + File.separatorChar + "in";
public static final String SNAP_TEST_DATA_OUTPUT_DIR_DEFAULT_PATH = "testdata" + File.separatorChar + "out";
private static final int RASTER_WIDTH = 4;
private static final int RASTER_HEIGHT = 40;
private WriteImageOp.Spi writeImageSpi = new WriteImageOp.Spi();
private WriteOp.Spi writeSpi = new WriteOp.Spi();
private File outputFile;
private int oldParallelism;
@Override
protected void setUp() throws Exception {
GPF.getDefaultInstance().getOperatorSpiRegistry().addOperatorSpi(writeImageSpi);
GPF.getDefaultInstance().getOperatorSpiRegistry().addOperatorSpi(writeSpi);
outputFile = getBeamTestDataOutputFile("WriteImageOpTest/writtenProduct.dim");
outputFile.getParentFile().mkdirs();
TileScheduler tileScheduler = JAI.getDefaultInstance().getTileScheduler();
oldParallelism = tileScheduler.getParallelism();
tileScheduler.setParallelism(Runtime.getRuntime().availableProcessors());
}
public static File getBeamTestDataOutputFile(String relPath) {
return new File(getBeamTestDataOutputDirectory(),
SystemUtils.convertToLocalPath(relPath));
}
public static File getBeamTestDataOutputDirectory() {
return getDirectory(SNAP_TEST_DATA_OUTPUT_DIR_PROPERTY_NAME,
SNAP_TEST_DATA_OUTPUT_DIR_DEFAULT_PATH);
}
private static File getDirectory(String propertyName, String beamRelDefaultPath) {
String filePath = System.getProperty(propertyName);
if (filePath != null) {
return new File(filePath);
}
return new File(SystemUtils.getApplicationHomeDir(),
SystemUtils.convertToLocalPath(beamRelDefaultPath));
}
@Override
protected void tearDown() throws Exception {
GPF.getDefaultInstance().getOperatorSpiRegistry().removeOperatorSpi(writeImageSpi);
GPF.getDefaultInstance().getOperatorSpiRegistry().removeOperatorSpi(writeSpi);
File parentFile = outputFile.getParentFile();
FileUtils.deleteTree(parentFile);
TileScheduler tileScheduler = JAI.getDefaultInstance().getTileScheduler();
tileScheduler.setParallelism(oldParallelism);
}
public void testWrite() throws Exception {
String graphOpXml = "<graph id=\"myOneNodeGraph\">\n"
+ " <version>1.0</version>\n"
+ " <node id=\"node1\">\n"
+ " <operator>WriteImageOp</operator>\n"
+ " </node>\n"
+ " <node id=\"node2\">\n"
+ " <operator>Write</operator>\n"
+ " <sources>\n"
+ " <source refid=\"node1\"/>\n"
+ " </sources>\n"
+ " <parameters>\n"
+ " <file>" + outputFile.getAbsolutePath() + "</file>\n"
+ " <deleteOutputOnFailure>false</deleteOutputOnFailure>\n"
+ " </parameters>\n"
+ " </node>\n"
+ "</graph>";
StringReader reader = new StringReader(graphOpXml);
Graph graph = GraphIO.read(reader);
GraphProcessor processor = new GraphProcessor();
processor.executeGraph(graph, ProgressMonitor.NULL);
Product productOnDisk = ProductIO.readProduct(outputFile);
assertNotNull(productOnDisk);
assertEquals("writtenProduct", productOnDisk.getName());
assertEquals(3, productOnDisk.getNumBands());
assertEquals("OperatorBand", productOnDisk.getBandAt(0).getName());
assertEquals("ConstantBand", productOnDisk.getBandAt(1).getName());
assertEquals("VirtualBand", productOnDisk.getBandAt(2).getName());
Band operatorBand = productOnDisk.getBandAt(0);
operatorBand.loadRasterData();
//assertEquals(12345, operatorBand.getPixelInt(0, 0));
// Test that header has been rewritten due to data model changes in AlgoOp.computeTile()
final ProductNodeGroup<Placemark> placemarkProductNodeGroup = productOnDisk.getPinGroup();
// 40 pins expected --> one for each tile, we have 40 tiles
// This test fails sometimes and sometimes not. Probably due to some tiling-issues. Therefore commented out.
// assertEquals(40, placemarkProductNodeGroup.getNodeCount());
productOnDisk.dispose();
}
/**
* Some algorithm.
*/
@OperatorMetadata(alias = "Algo")
public static class AlgoOp extends Operator {
@TargetProduct
private Product targetProduct;
@Override
public void initialize() {
targetProduct = new Product("name", "desc", RASTER_WIDTH, RASTER_HEIGHT);
targetProduct.addBand("OperatorBand", ProductData.TYPE_INT8);
targetProduct.addBand("ConstantBand", ProductData.TYPE_INT8).setSourceImage(new BufferedImage(RASTER_WIDTH, RASTER_HEIGHT, BufferedImage.TYPE_BYTE_INDEXED));
targetProduct.addBand(new VirtualBand("VirtualBand", ProductData.TYPE_FLOAT32, RASTER_WIDTH, RASTER_HEIGHT, "OperatorBand + ConstantBand"));
targetProduct.setPreferredTileSize(2, 2);
}
@Override
public void computeTile(Band band, Tile targetTile, ProgressMonitor pm) {
// Fill the tile with the constant sample value 12345
//
for (Tile.Pos pos : targetTile) {
targetTile.setSample(pos.x, pos.y, 12345);
}
// Set a pin, so that we can test that the header is rewritten after
// a data model change.
//
final int minX = targetTile.getMinX();
final int minY = targetTile.getMinY();
Placemark placemark = Placemark.createPointPlacemark(PinDescriptor.getInstance(),
band.getName() + "-" + minX + "-" + minY,
"label", "descr",
new PixelPos(minX, minY), null,
targetProduct.getSceneGeoCoding());
targetProduct.getPinGroup().add(placemark);
System.out.println("placemark = " + placemark.getName());
}
public static class Spi extends OperatorSpi {
public Spi() {
super(AlgoOp.class);
}
}
}
public void testInitialize() throws Exception {
}
public void testComputeTile() throws Exception {
}
public void testDispose() throws Exception {
}
public void testWriteImage() throws Exception {
}
public void testCreateImage() throws Exception {
}
public void testCreateImage1() throws Exception {
}
public void testGetContourLayer() throws Exception {
}
} | 8,072 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
RGBUtils.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-writeimage-operator/src/main/java/gov/nasa/gsfc/seadas/writeimage/RGBUtils.java | package gov.nasa.gsfc.seadas.writeimage;
import org.esa.snap.core.datamodel.ColorPaletteDef;
import org.esa.snap.core.datamodel.ColorPaletteDef.Point;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Class containing helper methods for RGB image construction.
*
* TODO: a very basic implementation which works. Should be improved and unit tested.
*
* @author kutila
*/
public class RGBUtils
{
/**
* Load a default color palette definition.
*
* @param min
* @param max
* @param noData
* @return
*/
public static ColorPaletteDef buildColorPaletteDef(final double min, final double max)
{
System.out.println("Using default color palette definition");
return new ColorPaletteDef(new ColorPaletteDef.Point[] { new ColorPaletteDef.Point(min, Color.BLACK),
new ColorPaletteDef.Point(0.00, Color.DARK_GRAY), new ColorPaletteDef.Point(0.1, Color.WHITE),
new ColorPaletteDef.Point(0.2, Color.YELLOW), new ColorPaletteDef.Point(0.3, Color.CYAN),
new ColorPaletteDef.Point(0.4, Color.PINK), new ColorPaletteDef.Point(0.5, Color.ORANGE),
new ColorPaletteDef.Point(1.0, Color.GREEN), new ColorPaletteDef.Point(2.0, Color.RED),
new ColorPaletteDef.Point((min + max) / 2, Color.MAGENTA), new ColorPaletteDef.Point(max, Color.BLUE) });
}
/**
* Load color palette definition from the specified look up table on file.
*
* @param min
* @param max
* @param noData
* @param clutPath
* @return
*/
public static ColorPaletteDef buildColorPaletteDefFromFile(final double min, final double max, final double noData,
final String clutPath)
{
final List<Point> list = new ArrayList<Point>();
// set NO Data color
// list.add(new Point(noData, Color.GRAY));
FileReader fr = null;
BufferedReader br = null;
try
{
fr = new FileReader(clutPath);
br = new BufferedReader(fr);
int i = 0;
String line = br.readLine();
while(line != null)
{
final String[] cv = line.trim().split("\\s+");
if(cv.length != 3)
{
throw new IOException("CLUT row should have 3 columns");
}
final double sample =
// i * max/256;
Math.pow(i * max / 256 + min, 10);
final Color color = new Color(Integer.valueOf(cv[0]), Integer.valueOf(cv[1]), Integer.valueOf(cv[2]));
list.add(new Point(sample, color));
// System.out.println("(" + color.getRed() + " " + color.getGreen() + " " +
// color.getBlue() + " ) "
// + sample);
i++;
line = br.readLine();
}
final ColorPaletteDef cpd = new ColorPaletteDef(list.toArray(new Point[0]));
return cpd;
}
catch(final IOException e)
{
System.out.println("Ignored exception");
}
finally
{
try
{
if(br != null)
{
br.close();
}
if(fr != null)
{
fr.close();
}
}
catch(final Exception e)
{
}
}
return RGBUtils.buildColorPaletteDef(min, max);
}
} | 3,727 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.