List of usage examples for org.jdom2 Namespace getNamespace
public static Namespace getNamespace(final String uri)
Namespace
for the supplied URI, and make it usable as a default namespace, as no prefix is supplied. From source file:edu.wisc.ssec.mcidasv.data.hydra.SuomiNPPDataSource.java
License:Open Source License
public void setup() throws VisADException { // which format, NASA or NOAA? isNOAA = false;/* w ww . ja v a 2 s. c om*/ // store filenames for possible bundle unpersistence for (Object o : sources) { oldSources.add((String) o); } // time zone for product labels SimpleTimeZone stz = new SimpleTimeZone(0, "GMT"); sdf.setTimeZone(stz); sdfOut.setTimeZone(stz); // looking to populate 3 things - path to lat, path to lon, path to relevant products String pathToLat = null; String pathToLon = null; Set<String> pathToProducts = new LinkedHashSet<>(); Map<String, String> prodToDesc = new HashMap<>(); // flag to differentiate VIIRS from one of the other Suomi sensors boolean isVIIRS = true; // check source filenames to see if this is a combined product. everything // from last file separator to first underscore should be product info int lastSeparator = filename.lastIndexOf(File.separatorChar); int firstUnderscore = filename.indexOf("_", lastSeparator + 1); String prodStr = filename.substring(lastSeparator + 1, firstUnderscore); // only do this check for NOAA data if (filename.endsWith(".h5")) { isNOAA = true; StringTokenizer st = new StringTokenizer(prodStr, "-"); logger.debug("SNPPDS check for embedded GEO, tokenizing: " + prodStr); while (st.hasMoreTokens()) { String singleProd = st.nextToken(); for (int i = 0; i < JPSSUtilities.geoProductIDs.length; i++) { if (singleProd.equals(JPSSUtilities.geoProductIDs[i])) { logger.debug("Setting isCombinedProduct true, Found embedded GEO: " + singleProd); isCombinedProduct = true; break; } } } } // various metatdata we'll need to gather on a per-product basis Map<String, String> unsignedFlags = new LinkedHashMap<>(); Map<String, String> unpackFlags = new LinkedHashMap<>(); // geo product IDs for each granule Set<String> geoProductIDs = new LinkedHashSet<>(); // aggregations will use sets of NetCDFFile readers List<NetCDFFile> ncdfal = new ArrayList<>(); // we should be able to find an XML Product Profile for each data/product type SuomiNPPProductProfile nppPP = null; // and also Profile metadata for geolocation variables boolean haveGeoMetaData = false; // number of source granules which make up the data source int granuleCount = 1; try { nppPP = new SuomiNPPProductProfile(); // for each source file provided, find the appropriate geolocation, // get the nominal time and various other granule-level metadata Iterator keyIterator = filenameMap.keySet().iterator(); while (keyIterator.hasNext()) { String keyStr = (String) keyIterator.next(); List fileNames = (List) filenameMap.get(keyStr); granuleCount = fileNames.size(); setProperty(Constants.PROP_GRANULE_COUNT, granuleCount + " Granule"); for (int fileCount = 0; fileCount < granuleCount; fileCount++) { // need to open the main NetCDF file to determine the geolocation product NetcdfFile ncfile = null; String fileAbsPath = null; try { fileAbsPath = (String) fileNames.get(fileCount); logger.debug("Trying to open file: " + fileAbsPath); ncfile = NetcdfFile.open(fileAbsPath); if (!isCombinedProduct) { if (isNOAA) { Attribute a = ncfile.findGlobalAttribute("N_GEO_Ref"); logger.debug("Value of GEO global attribute: " + a.getStringValue()); String tmpGeoProductID = a.getStringValue(); geoProductIDs.add(tmpGeoProductID); } else { geoProductIDs.add(keyStr.replace("L1B", "GEO")); } } Group rg = ncfile.getRootGroup(); List<Group> gl = rg.getGroups(); if (gl != null) { for (Group g : gl) { logger.trace("Group name: " + g.getFullName()); if (isNOAA) { // when we find the Data_Products group, go down another group level and pull out // what we will use for nominal day and time (for now anyway). // XXX TJJ fileCount check is so we don't count the GEO file in time array! if (g.getFullName().contains("Data_Products") && (fileCount != fileNames.size())) { List<Group> dpg = g.getGroups(); // cycle through once looking for XML Product Profiles for (Group subG : dpg) { String subName = subG.getFullName(); // use actual product, not geolocation, to id XML Product Profile if (!subName.contains("-GEO")) { // determine the instrument name (VIIRS, ATMS, CrIS, OMPS) instrumentName = subG.findAttribute("Instrument_Short_Name"); // note any EDR products, will need to check for and remove // fill scans later Attribute adtt = subG.findAttribute("N_Dataset_Type_Tag"); if (adtt != null) { String baseName = adtt.getStringValue(); if ((baseName != null) && (baseName.equals("EDR"))) { // have to loop through sub groups variables to determine band List<Variable> tmpVar = subG.getVariables(); for (Variable v : tmpVar) { // if Imagery EDR attribute for band is specified, save it Attribute mBand = v.findAttribute("Band_ID"); if (mBand != null) { whichEDR = mBand.getStringValue(); } } } } // This is also where we find the attribute which tells us which // XML Product Profile to use! Attribute axpp = subG.findAttribute("N_Collection_Short_Name"); if (axpp != null) { String baseName = axpp.getStringValue(); productName = baseName; // TJJ Apr 2018 // Hack so we can look at CrIS Full Spectrum, until we can // track down existence of an official Product Profile for it. // http://mcidas.ssec.wisc.edu/inquiry-v/?inquiry=2634 // The regular SDR profile lets us visualize it. if (productName.equals("CrIS-FS-SDR")) productName = "CrIS-SDR"; String productProfileFileName = nppPP .getProfileFileName(productName); logger.trace("Found profile: " + productProfileFileName); if (productProfileFileName == null) { throw new Exception( "XML Product Profile not found in catalog"); } try { nppPP.addMetaDataFromFile(productProfileFileName); } catch (Exception nppppe) { logger.error("Error parsing XML Product Profile: " + productProfileFileName); throw new Exception("XML Product Profile Error", nppppe); } } } } // 2nd pass through sub-group to extract date/time for aggregation for (Group subG : dpg) { List<Variable> vl = subG.getVariables(); for (Variable v : vl) { Attribute aDate = v.findAttribute("AggregateBeginningDate"); Attribute aTime = v.findAttribute("AggregateBeginningTime"); // did we find the attributes we are looking for? if ((aDate != null) && (aTime != null)) { // set time for display to day/time of 1st granule examined if (!nameHasBeenSet) { String sDate = aDate.getStringValue(); String sTime = aTime.getStringValue(); logger.debug("For day/time, using: " + sDate + sTime.substring(0, sTime.indexOf('Z') - 3)); Date d = sdf.parse( sDate + sTime.substring(0, sTime.indexOf('Z') - 3)); theDate = d; setName(instrumentName.getStringValue() + " " + sdfOut.format(d)); nameHasBeenSet = true; } break; } } } if (!nameHasBeenSet) { throw new VisADException("No date time found in Suomi NPP granule"); } } } else { // NASA data - date/time from global attribute // set time for display to day/time of 1st granule examined Attribute timeStartNASA = ncfile.findGlobalAttribute("time_coverage_start"); Date d = sdfNASA.parse(timeStartNASA.getStringValue()); theDate = d; if (!nameHasBeenSet) { instrumentName = ncfile.findGlobalAttribute("instrument"); setName(instrumentName.getStringValue() + " " + sdfOut.format(d)); nameHasBeenSet = true; } } } } } catch (Exception e) { logger.warn("Exception during processing of file: " + fileAbsPath); throw (e); } finally { ncfile.close(); } } } // build each union aggregation element Iterator<String> iterator = geoProductIDs.iterator(); for (int elementNum = 0; elementNum < granuleCount; elementNum++) { String s = null; // build an XML (NCML actually) representation of the union aggregation of these two files Namespace ns = Namespace.getNamespace("http://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2"); Element root = new Element("netcdf", ns); Document document = new Document(root); Element agg = new Element("aggregation", ns); agg.setAttribute("type", "union"); // TJJ - Loop over filename map, could be several products that need to be aggregated Set set = filenameMap.keySet(); Iterator mapIter = set.iterator(); while (mapIter.hasNext()) { String key = (String) mapIter.next(); List l = (List) filenameMap.get(key); Element fData = new Element("netcdf", ns); fData.setAttribute("location", (String) l.get(elementNum)); agg.addContent(fData); s = (String) l.get(elementNum); } String geoFilename = null; Element fGeo = new Element("netcdf", ns); ; if (!isCombinedProduct) { if (isNOAA) { geoFilename = s.substring(0, s.lastIndexOf(File.separatorChar) + 1); // check if we have the whole file name or just the prefix String geoProductID = iterator.next(); if (geoProductID.endsWith("h5")) { geoFilename += geoProductID; } else { geoFilename += geoProductID; geoFilename += s.substring(s.lastIndexOf(File.separatorChar) + 6); } // Be sure file as specified by N_GEO_Ref global attribute really is there. File tmpGeo = new File(geoFilename); if (!tmpGeo.exists()) { // Ok, the expected file defined (supposedly) exactly by a global att is not there... // We need to check for similar geo files with different creation dates String geoFileRelative = geoFilename .substring(geoFilename.lastIndexOf(File.separatorChar) + 1); // also check for Terrain Corrected version of geo String geoTerrainCorrected = geoFileRelative; geoTerrainCorrected = geoTerrainCorrected.replace("OD", "TC"); geoTerrainCorrected = geoTerrainCorrected.replace("MG", "TC"); // now we make a file filter, and see if a matching geo file is present File fList = new File( geoFilename.substring(0, geoFilename.lastIndexOf(File.separatorChar) + 1)); // current directory FilenameFilter geoFilter = new FilenameFilter() { public boolean accept(File dir, String name) { if (name.matches(JPSSUtilities.SUOMI_GEO_REGEX_NOAA)) { return true; } else { return false; } } }; File[] files = fList.listFiles(geoFilter); for (File file : files) { if (file.isDirectory()) { continue; } // get the file name for convenience String fName = file.getName(); // is it one of the standard Ellipsoid geo types we are looking for? if (fName.substring(0, 5).equals(geoFileRelative.substring(0, 5))) { int geoStartIdx = geoFileRelative.indexOf("_d"); int prdStartIdx = fName.indexOf("_d"); String s1 = geoFileRelative.substring(geoStartIdx, geoStartIdx + JPSSUtilities.NOAA_CREATION_DATE_INDEX); String s2 = fName.substring(prdStartIdx, prdStartIdx + JPSSUtilities.NOAA_CREATION_DATE_INDEX); if (s1.equals(s2)) { geoFilename = s.substring(0, s.lastIndexOf(File.separatorChar) + 1) + fName; break; } } // same check, but for Terrain Corrected version if (fName.substring(0, 5).equals(geoTerrainCorrected.substring(0, 5))) { int geoStartIdx = geoTerrainCorrected.indexOf("_d"); int prdStartIdx = fName.indexOf("_d"); String s1 = geoTerrainCorrected.substring(geoStartIdx, geoStartIdx + JPSSUtilities.NOAA_CREATION_DATE_INDEX); String s2 = fName.substring(prdStartIdx, prdStartIdx + JPSSUtilities.NOAA_CREATION_DATE_INDEX); if (s1.equals(s2)) { geoFilename = s.substring(0, s.lastIndexOf(File.separatorChar) + 1) + fName; break; } } } } } else { // NASA format geoFilename = JPSSUtilities.replaceLast(s, "L1B", "GEO"); // get list of files in current directory File fList = new File( geoFilename.substring(0, geoFilename.lastIndexOf(File.separatorChar) + 1)); // make a NASA style file filter, and see if a matching geo file is present FilenameFilter geoFilter = new FilenameFilter() { public boolean accept(File dir, String name) { if (name.matches(JPSSUtilities.SUOMI_GEO_REGEX_NASA)) { return true; } else { return false; } } }; File[] files = fList.listFiles(geoFilter); for (File file : files) { if (file.isDirectory()) { continue; } // get the file name for convenience String fName = file.getName(); String tmpStr = geoFilename.substring(s.lastIndexOf(File.separatorChar) + 1, s.lastIndexOf(File.separatorChar) + (JPSSUtilities.NASA_CREATION_DATE_INDEX + 1)); if (fName.substring(0, JPSSUtilities.NASA_CREATION_DATE_INDEX) .equals(tmpStr.substring(0, JPSSUtilities.NASA_CREATION_DATE_INDEX))) { geoFilename = s.substring(0, s.lastIndexOf(File.separatorChar) + 1) + fName; break; } } } logger.debug("Determined GEO file name should be: " + geoFilename); fGeo.setAttribute("location", geoFilename); // add this to list used if we create a zipped bundle geoSources.add(geoFilename); agg.addContent(fGeo); } root.addContent(agg); XMLOutputter xmlOut = new XMLOutputter(); String ncmlStr = xmlOut.outputString(document); ByteArrayInputStream is = new ByteArrayInputStream(ncmlStr.getBytes()); MultiDimensionReader netCDFReader = new NetCDFFile(is); // let's try and look through the NetCDF reader and see what we can learn... NetcdfFile ncdff = ((NetCDFFile) netCDFReader).getNetCDFFile(); Group rg = ncdff.getRootGroup(); // this is a list filled with unpacked qflag products, if any ArrayList<VariableDS> qfProds = new ArrayList<VariableDS>(); // this is a list filled with pseudo Brightness Temp variables converted from Radiance ArrayList<VariableDS> btProds = new ArrayList<VariableDS>(); List<Group> gl = rg.getGroups(); if (gl != null) { int xDimNASA = -1; int yDimNASA = -1; // Make a first pass to determine the shape of the geolocation data for (Group g : gl) { if (g.getFullName().contains("geolocation_data")) { List<Variable> vl = g.getVariables(); for (Variable v : vl) { if (v.getShortName().equals("latitude")) { // XXX TJJ Nov 2015 // Hack because fill value in attribute does not match // what I am seeing in the data. Attribute fillAtt = new Attribute("_FillValue", -999.0); v.addAttribute(fillAtt); pathToLat = v.getFullName(); pathToProducts.add(v.getFullName()); prodToDesc.put(v.getFullName(), v.getDescription()); xDimNASA = v.getDimension(0).getLength(); yDimNASA = v.getDimension(1).getLength(); } if (v.getShortName().equals("longitude")) { // XXX TJJ Nov 2015 // Hack because fill value in attribute does not match // what I am seeing in the data. Attribute fillAtt = new Attribute("_FillValue", -999.0); v.addAttribute(fillAtt); pathToLon = v.getFullName(); pathToProducts.add(v.getFullName()); prodToDesc.put(v.getFullName(), v.getDescription()); } } } } for (Group g : gl) { logger.debug("Group name: " + g.getFullName()); // NASA only - looking through observation_data and geolocation_data if (g.getFullName().contains("observation_data")) { List<Variable> vl = g.getVariables(); for (Variable v : vl) { // keep any data which matches geolocation dimensions if (v.getDimension(0).getLength() == xDimNASA && v.getDimension(1).getLength() == yDimNASA) { logger.debug("Adding product: " + v.getFullName()); pathToProducts.add(v.getFullName()); prodToDesc.put(v.getFullName(), v.getDescription()); Attribute aUnsigned = v.findAttribute("_Unsigned"); if (aUnsigned != null) { unsignedFlags.put(v.getFullName(), aUnsigned.getStringValue()); } else { unsignedFlags.put(v.getFullName(), "false"); } // store units in a map for later Attribute unitAtt = v.findAttribute("units"); if (unitAtt != null) { unitsNASA.put(v.getShortName(), unitAtt.getStringValue()); } else { unitsNASA.put(v.getShortName(), "Unknown"); } // TJJ Nov 2018 - SIPS V2+ mods // Regridding with bow-tie interpolation wasn't working since there are // now multiple fill value categories and we need to look specifically // for the bowtie deletion flag Attribute longNameAtt = v.findAttribute("long_name"); String longName = "empty"; if (longNameAtt != null) longName = longNameAtt.getStringValue(); if (longName.contains("reflectance") || longName.contains("radiance")) { Attribute flagMeanings = v .findAttribute(JPSSUtilities.SIPS_FLAG_MEANINGS_ATTRIBUTE); // If this is not null, we must be v2.0.0 or higher if (flagMeanings != null) { String meanings = flagMeanings.getStringValue(); // Tokenize meanings string, multiple flags defined there StringTokenizer st = new StringTokenizer(meanings); int bowtieIdx = -1; boolean foundBowTieAttribute = false; String tokStr = null; while (st.hasMoreTokens()) { tokStr = st.nextToken(); bowtieIdx++; if (tokStr.equals(JPSSUtilities.SIPS_BOWTIE_DELETED_FLAG)) { foundBowTieAttribute = true; break; } } if (foundBowTieAttribute) { Attribute flagValues = v .findAttribute(JPSSUtilities.SIPS_FLAG_VALUES_ATTRIBUTE); Array flagValsArr = flagValues.getValues(); int bowTieVal = (int) flagValsArr.getInt(bowtieIdx); Attribute a1 = new Attribute("_FillValue", bowTieVal); v.addAttribute(a1); } } } // TJJ Feb 2016 - Create BT variables where applicable if ((v.getShortName().matches("M12|M13|M14|M15|M16")) || (v.getShortName().matches("I04|I05"))) { // Get the LUT variable, load into primitive array Variable lut = g .findVariable(v.getShortName() + "_brightness_temperature_lut"); int[] lutShape = lut.getShape(); logger.debug("Handling NASA LUT Variable, LUT size: " + lutShape[0]); // pull out valid min, max - these will be used for our new VariableDS Attribute aVMin = lut.findAttribute("valid_min"); Attribute aVMax = lut.findAttribute("valid_max"); Attribute fillAtt = lut.findAttribute("_FillValue"); logger.debug("valid_min from LUT: " + aVMin.getNumericValue()); logger.debug("valid_max from LUT: " + aVMax.getNumericValue()); // A little hacky, but at this point the class is such a mess // that what's a little more, right? Load M12-M16, I4-I5 LUTS if (v.getShortName().matches("M12")) { m12LUT = new float[lutShape[0]]; ArrayFloat.D1 lutArray = (ArrayFloat.D1) lut.read(); for (int lutIdx = 0; lutIdx < lutShape[0]; lutIdx++) { m12LUT[lutIdx] = lutArray.get(lutIdx); } } if (v.getShortName().matches("M13")) { m13LUT = new float[lutShape[0]]; ArrayFloat.D1 lutArray = (ArrayFloat.D1) lut.read(); for (int lutIdx = 0; lutIdx < lutShape[0]; lutIdx++) { m13LUT[lutIdx] = lutArray.get(lutIdx); } } if (v.getShortName().matches("M14")) { m14LUT = new float[lutShape[0]]; ArrayFloat.D1 lutArray = (ArrayFloat.D1) lut.read(); for (int lutIdx = 0; lutIdx < lutShape[0]; lutIdx++) { m14LUT[lutIdx] = lutArray.get(lutIdx); } } if (v.getShortName().matches("M15")) { m15LUT = new float[lutShape[0]]; ArrayFloat.D1 lutArray = (ArrayFloat.D1) lut.read(); for (int lutIdx = 0; lutIdx < lutShape[0]; lutIdx++) { m15LUT[lutIdx] = lutArray.get(lutIdx); } } if (v.getShortName().matches("M16")) { m16LUT = new float[lutShape[0]]; ArrayFloat.D1 lutArray = (ArrayFloat.D1) lut.read(); for (int lutIdx = 0; lutIdx < lutShape[0]; lutIdx++) { m16LUT[lutIdx] = lutArray.get(lutIdx); } } if (v.getShortName().matches("I04")) { i04LUT = new float[lutShape[0]]; ArrayFloat.D1 lutArray = (ArrayFloat.D1) lut.read(); for (int lutIdx = 0; lutIdx < lutShape[0]; lutIdx++) { i04LUT[lutIdx] = lutArray.get(lutIdx); } } if (v.getShortName().matches("I05")) { i05LUT = new float[lutShape[0]]; ArrayFloat.D1 lutArray = (ArrayFloat.D1) lut.read(); for (int lutIdx = 0; lutIdx < lutShape[0]; lutIdx++) { i05LUT[lutIdx] = lutArray.get(lutIdx); } } // Create a pseudo-variable, fill using LUT // make a copy of the source variable // NOTE: by using a VariableDS here, the original // variable is used for the I/O, this matters! VariableDS vBT = new VariableDS(g, v, false); // Name is orig name plus suffix vBT.setShortName(v.getShortName() + "_BT"); vBT.addAttribute(fillAtt); vBT.addAttribute(aVMin); vBT.addAttribute(aVMax); if (v.getShortName().matches("M12")) { lutMap.put(vBT.getFullName(), m12LUT); } if (v.getShortName().matches("M13")) { lutMap.put(vBT.getFullName(), m13LUT); } if (v.getShortName().matches("M14")) { lutMap.put(vBT.getFullName(), m14LUT); } if (v.getShortName().matches("M15")) { lutMap.put(vBT.getFullName(), m15LUT); } if (v.getShortName().matches("M16")) { lutMap.put(vBT.getFullName(), m16LUT); } if (v.getShortName().matches("I04")) { lutMap.put(vBT.getFullName(), i04LUT); } if (v.getShortName().matches("I05")) { lutMap.put(vBT.getFullName(), i05LUT); } pathToProducts.add(vBT.getFullName()); String newName = vBT.getDescription().replace("radiance", "brightness temperature"); prodToDesc.put(vBT.getFullName(), newName); btProds.add(vBT); } } } } if (g.getFullName().contains("geolocation_data")) { List<Variable> vl = g.getVariables(); for (Variable v : vl) { // keep any data which matches geolocation dimensions if (v.getDimension(0).getLength() == xDimNASA && v.getDimension(1).getLength() == yDimNASA) { // except we already found Lat and Lon, skip those if ((v.getShortName().equals("latitude")) || (v.getShortName().equals("latitude"))) continue; logger.debug("Adding product: " + v.getFullName()); pathToProducts.add(v.getFullName()); prodToDesc.put(v.getFullName(), v.getDescription()); } } } // NOAA only - we are looking through All_Data, finding displayable data if (g.getFullName().contains("All_Data")) { List<Group> adg = g.getGroups(); int xDim = -1; int yDim = -1; // two sub-iterations, first one to find geolocation and product dimensions for (Group subG : adg) { logger.debug("Sub group name: " + subG.getFullName()); String subName = subG.getFullName(); if (subName.contains("-GEO")) { // this is the geolocation data String geoBaseName = subG.getShortName(); geoBaseName = geoBaseName.substring(0, geoBaseName.indexOf('_')); if (!haveGeoMetaData) { String geoProfileFileName = nppPP.getProfileFileName(geoBaseName); // also add meta data from geolocation profile nppPP.addMetaDataFromFile(geoProfileFileName); haveGeoMetaData = true; } List<Variable> vl = subG.getVariables(); for (Variable v : vl) { if (v.getFullName().endsWith(SEPARATOR_CHAR + "Latitude")) { pathToLat = v.getFullName(); logger.debug("Ellipsoid Lat/Lon Variable: " + v.getFullName()); // get the dimensions of the lat variable Dimension dAlongTrack = v.getDimension(0); yDim = dAlongTrack.getLength(); Dimension dAcrossTrack = v.getDimension(1); xDim = dAcrossTrack.getLength(); logger.debug("Lat across track dim: " + dAcrossTrack.getLength()); } if (v.getFullName().endsWith(SEPARATOR_CHAR + "Longitude")) { // we got dimensions from lat, don't need 'em twice, but need path pathToLon = v.getFullName(); } } // one more pass in case there is terrain-corrected Lat/Lon for (Variable v : vl) { if (v.getFullName().endsWith(SEPARATOR_CHAR + "Latitude_TC")) { pathToLat = v.getFullName(); logger.debug("Switched Lat/Lon Variable to TC: " + v.getFullName()); // get the dimensions of the lat variable Dimension dAlongTrack = v.getDimension(0); yDim = dAlongTrack.getLength(); Dimension dAcrossTrack = v.getDimension(1); xDim = dAcrossTrack.getLength(); logger.debug("Lat across track dim: " + dAcrossTrack.getLength()); } if (v.getFullName().endsWith(SEPARATOR_CHAR + "Longitude_TC")) { // we got dimensions from lat, don't need 'em twice, but need path pathToLon = v.getFullName(); } } } } // second to identify displayable products for (Group subG : adg) { // this is the product data List<Variable> vl = subG.getVariables(); for (Variable v : vl) { boolean useThis = false; String vName = v.getFullName(); logger.trace("Variable: " + vName); String varShortName = vName.substring(vName.lastIndexOf(SEPARATOR_CHAR) + 1); // Special code to handle quality flags. We throw out anything // that does not match bounds of the geolocation data if (varShortName.startsWith("QF")) { logger.trace("Handling Quality Flag: " + varShortName); // this check is done later for ALL variables, but we need // it early here to weed out those quality flags that are // simply a small set of data w/no granule geo nbounds boolean xScanOk = false; boolean yScanOk = false; List<Dimension> dl = v.getDimensions(); // toss out > 2D Quality Flags if (dl.size() > 2) { logger.trace("SKIPPING QF, > 2D: " + varShortName); continue; } for (Dimension d : dl) { // in order to consider this a displayable product, make sure // both scan direction dimensions are present and look like a granule if (d.getLength() == xDim) { xScanOk = true; } if (d.getLength() == yDim) { yScanOk = true; } } if (!(xScanOk && yScanOk)) { logger.trace("SKIPPING QF, does not match geo bounds: " + varShortName); continue; } ArrayList<QualityFlag> qfal = nppPP.getQualityFlags(varShortName); if (qfal != null) { for (QualityFlag qf : qfal) { qf.setPackedName(vName); // make a copy of the qflag variable // NOTE: by using a VariableDS here, the original // variable is used for the I/O, this matters! VariableDS vqf = new VariableDS(subG, v, false); // prefix with QF num to help guarantee uniqueness across groups // this will cover most cases, but could still be dupe names // within a single QF. This is handled when fetching XMLPP metadata vqf.setShortName(varShortName.substring(0, 3) + "_" + qf.getName()); logger.debug("New QF var full name: " + vqf.getFullName()); qfProds.add(vqf); qfMap.put(vqf.getFullName(), qf); } } } // for CrIS instrument, first find dimensions of var matching // CrIS filter, then throw out all variables which don't match // those dimensions if (instrumentName.getStringValue().equals("CrIS")) { if (!vName.contains("GEO")) { if (!varShortName.startsWith(crisFilter)) { logger.trace("Skipping variable: " + varShortName); continue; } } else { // these variables are all GEO-related // if they match lat/lon bounds, keep them List<Dimension> dl = v.getDimensions(); if (dl.size() == 3) { boolean isDisplayableCrIS = true; for (Dimension d : dl) { if ((d.getLength() != xDim) && (d.getLength() != yDim) && (d.getLength() != 9)) { isDisplayableCrIS = false; } } if (!isDisplayableCrIS) { continue; } } } } DataType dt = v.getDataType(); if ((dt.getSize() != 4) && (dt.getSize() != 2) && (dt.getSize() != 1)) { continue; } List<Dimension> dl = v.getDimensions(); if (dl.size() > 4) { continue; } // for now, skip any 3D VIIRS data if (instrumentName.getStringValue().equals("VIIRS")) { if (dl.size() == 3) { continue; } } boolean xScanOk = false; boolean yScanOk = false; for (Dimension d : dl) { // in order to consider this a displayable product, make sure // both scan direction dimensions are present and look like a granule if (d.getLength() == xDim) { xScanOk = true; } if (d.getLength() == yDim) { yScanOk = true; } } if (xScanOk && yScanOk) { useThis = true; } // For ATMS, only 3-D variable we pass through is BrightnessTemperature // Dimensions for BT are (lon, lat, channel) if (instrumentName.getStringValue().equals("ATMS")) { if (dl.size() == 3) { boolean isDisplayableATMS = false; for (Dimension d : dl) { if (d.getLength() == JPSSUtilities.ATMSChannelCenterFrequencies.length) { isDisplayableATMS = true; logger.trace( "This variable has a dimension matching num ATMS channels"); break; } } if (!isDisplayableATMS) useThis = false; } } // sensor data with a channel dimension if (useThis) { if ((instrumentName.getStringValue().equals("CrIS")) || (instrumentName.getStringValue().equals("ATMS")) || (instrumentName.getStringValue().contains("OMPS"))) { isVIIRS = false; logger.debug("Handling non-VIIRS data source..."); } } if (useThis) { // loop through the variable list again, looking for a corresponding "Factors" float scaleVal = 1f; float offsetVal = 0f; boolean unpackFlag = false; // if the granule has an entry for this variable name // get the data, data1 = scale, data2 = offset // create and poke attributes with this data // endif String factorsVarName = nppPP.getScaleFactorName(varShortName); if (factorsVarName != null) { logger.debug("Mapping: " + varShortName + " to: " + factorsVarName); for (Variable fV : vl) { if (fV.getShortName().equals(factorsVarName)) { logger.trace("Pulling scale and offset values from variable: " + fV.getShortName()); ucar.ma2.Array a = fV.read(); float[] so = (float[]) a.copyTo1DJavaArray(); scaleVal = so[0]; offsetVal = so[1]; logger.trace("Scale value: " + scaleVal + ", Offset value: " + offsetVal); unpackFlag = true; break; } } } // poke in scale/offset attributes for now Attribute a1 = new Attribute("scale_factor", scaleVal); v.addAttribute(a1); Attribute a2 = new Attribute("add_offset", offsetVal); v.addAttribute(a2); // add valid range and fill value attributes here // try to fill in valid range if (nppPP.hasNameAndMetaData(varShortName)) { String rangeMin = nppPP.getRangeMin(varShortName); String rangeMax = nppPP.getRangeMax(varShortName); logger.trace("range min: " + rangeMin + ", range max: " + rangeMax); // only store range attribute if VALID range found if ((rangeMin != null) && (rangeMax != null)) { int[] shapeArr = new int[] { 2 }; ArrayFloat af = new ArrayFloat(shapeArr); try { af.setFloat(0, Float.parseFloat(rangeMin)); } catch (NumberFormatException nfe) { af.setFloat(0, new Float(Integer.MIN_VALUE)); } try { af.setFloat(1, Float.parseFloat(rangeMax)); } catch (NumberFormatException nfe) { af.setFloat(1, new Float(Integer.MAX_VALUE)); } Attribute rangeAtt = new Attribute("valid_range", af); v.addAttribute(rangeAtt); } // check for and load fill values too... // we need to check two places, first, the XML product profile ArrayList<Float> fval = nppPP.getFillValues(varShortName); // 2nd, does the variable already have one defined? // if there was already a fill value associated with this variable, make // sure we bring that along for the ride too... Attribute aFill = v.findAttribute("_FillValue"); // determine size of our fill value array int fvArraySize = 0; if (aFill != null) fvArraySize++; if (!fval.isEmpty()) fvArraySize += fval.size(); int[] fillShape = new int[] { fvArraySize }; // allocate the array ArrayFloat afFill = new ArrayFloat(fillShape); // and FINALLY, fill it! if (!fval.isEmpty()) { for (int fillIdx = 0; fillIdx < fval.size(); fillIdx++) { afFill.setFloat(fillIdx, fval.get(fillIdx)); logger.trace( "Adding fill value (from XML): " + fval.get(fillIdx)); } } if (aFill != null) { Number n = aFill.getNumericValue(); // is the data unsigned? Attribute aUnsigned = v.findAttribute("_Unsigned"); float fillValAsFloat = Float.NaN; if (aUnsigned != null) { if (aUnsigned.getStringValue().equals("true")) { DataType fvdt = aFill.getDataType(); logger.trace("Data String: " + aFill.toString()); logger.trace("DataType primitive type: " + fvdt.getPrimitiveClassType()); // signed byte that needs conversion? if (fvdt.getPrimitiveClassType() == byte.class) { fillValAsFloat = (float) Util .unsignedByteToInt(n.byteValue()); } else if (fvdt.getPrimitiveClassType() == short.class) { fillValAsFloat = (float) Util .unsignedShortToInt(n.shortValue()); } else { fillValAsFloat = n.floatValue(); } } } afFill.setFloat(fvArraySize - 1, fillValAsFloat); logger.trace( "Adding fill value (from variable): " + fillValAsFloat); } Attribute fillAtt = new Attribute("_FillValue", afFill); v.addAttribute(fillAtt); } Attribute aUnsigned = v.findAttribute("_Unsigned"); if (aUnsigned != null) { unsignedFlags.put(v.getFullName(), aUnsigned.getStringValue()); } else { unsignedFlags.put(v.getFullName(), "false"); } if (unpackFlag) { unpackFlags.put(v.getFullName(), "true"); } else { unpackFlags.put(v.getFullName(), "false"); } logger.debug("Adding product: " + v.getFullName()); pathToProducts.add(v.getFullName()); prodToDesc.put(v.getFullName(), v.getDescription()); } } } } } } // add in any unpacked qflag products for (VariableDS qfV : qfProds) { // skip the spares - they are reserved for future use if (qfV.getFullName().endsWith("Spare")) { continue; } // String.endsWith is case sensitive so gotta check both cases if (qfV.getFullName().endsWith("spare")) { continue; } ncdff.addVariable(qfV.getGroup(), qfV); logger.trace("Adding QF product: " + qfV.getFullName()); pathToProducts.add(qfV.getFullName()); prodToDesc.put(qfV.getFullName(), qfV.getDescription()); unsignedFlags.put(qfV.getFullName(), "true"); unpackFlags.put(qfV.getFullName(), "false"); } // add in any pseudo BT products from NASA data for (Variable vBT : btProds) { logger.trace("Adding BT product: " + vBT.getFullName()); ncdff.addVariable(vBT.getGroup(), vBT); unsignedFlags.put(vBT.getFullName(), "true"); unpackFlags.put(vBT.getFullName(), "false"); } ncdfal.add((NetCDFFile) netCDFReader); } } catch (Exception e) { logger.error("cannot create NetCDF reader for files selected", e); if (e.getMessage() != null && e.getMessage().equals("XML Product Profile Error")) { throw new VisADException("Unable to extract metadata from required XML Product Profile", e); } } // TJJ Feb 2018 // Doing a reorder of variable names here, as per HP's request from // http://mcidas.ssec.wisc.edu/inquiry-v/?inquiry=2613 if (isVIIRS) { // Copy the variable Set to a sortable List List<String> sortedList = new ArrayList(pathToProducts); Collections.sort(sortedList, new VIIRSSort()); // Clear the original data structure which retains insert order // (it's a LinkedHashSet) pathToProducts.clear(); // Re-add the variables in corrected order for (String s : sortedList) { pathToProducts.add(s); } } // initialize the aggregation reader object try { if (isNOAA) { nppAggReader = new GranuleAggregation(ncdfal, pathToProducts, "Track", "XTrack", isVIIRS); ((GranuleAggregation) nppAggReader).setQfMap(qfMap); } else { nppAggReader = new GranuleAggregation(ncdfal, pathToProducts, "number_of_lines", "number_of_pixels", isVIIRS); ((GranuleAggregation) nppAggReader).setLUTMap(lutMap); } } catch (Exception e) { throw new VisADException("Unable to initialize aggregation reader", e); } // make sure we found valid data if (pathToProducts.size() == 0) { throw new VisADException("No data found in files selected"); } logger.debug("Number of adapters needed: " + pathToProducts.size()); adapters = new MultiDimensionAdapter[pathToProducts.size()]; Hashtable<String, String[]> properties = new Hashtable<>(); Iterator<String> iterator = pathToProducts.iterator(); int pIdx = 0; boolean adapterCreated = false; while (iterator.hasNext()) { String pStr = iterator.next(); logger.debug("Working on adapter number " + (pIdx + 1) + ": " + pStr); Map<String, Object> swathTable = SwathAdapter.getEmptyMetadataTable(); Map<String, Object> spectTable = SpectrumAdapter.getEmptyMetadataTable(); swathTable.put("array_name", pStr); swathTable.put("lon_array_name", pathToLon); swathTable.put("lat_array_name", pathToLat); swathTable.put("XTrack", "XTrack"); swathTable.put("Track", "Track"); swathTable.put("geo_Track", "Track"); swathTable.put("geo_XTrack", "XTrack"); // TJJ is this even needed? Is product_name used anywhere? if (productName == null) productName = pStr.substring(pStr.indexOf(SEPARATOR_CHAR) + 1); swathTable.put("product_name", productName); swathTable.put("_mapping", prodToDesc); // array_name common to spectrum table spectTable.put("array_name", pStr); spectTable.put("product_name", productName); spectTable.put("_mapping", prodToDesc); if (!isVIIRS) { // 3D data is either ATMS, OMPS, or CrIS if ((instrumentName.getShortName() != null) && (instrumentName.getStringValue().equals("ATMS"))) { spectTable.put(SpectrumAdapter.channelIndex_name, "Channel"); swathTable.put(SpectrumAdapter.channelIndex_name, "Channel"); swathTable.put("array_dimension_names", new String[] { "Track", "XTrack", "Channel" }); swathTable.put("lon_array_dimension_names", new String[] { "Track", "XTrack" }); swathTable.put("lat_array_dimension_names", new String[] { "Track", "XTrack" }); spectTable.put("array_dimension_names", new String[] { "Track", "XTrack", "Channel" }); spectTable.put("lon_array_dimension_names", new String[] { "Track", "XTrack" }); spectTable.put("lat_array_dimension_names", new String[] { "Track", "XTrack" }); spectTable.put(SpectrumAdapter.channelType, "wavelength"); spectTable.put(SpectrumAdapter.channels_name, "Channel"); spectTable.put(SpectrumAdapter.x_dim_name, "XTrack"); spectTable.put(SpectrumAdapter.y_dim_name, "Track"); int numChannels = JPSSUtilities.ATMSChannelCenterFrequencies.length; float[] bandArray = new float[numChannels]; String[] bandNames = new String[numChannels]; for (int bIdx = 0; bIdx < numChannels; bIdx++) { bandArray[bIdx] = JPSSUtilities.ATMSChannelCenterFrequencies[bIdx]; bandNames[bIdx] = "Channel " + (bIdx + 1); } spectTable.put(SpectrumAdapter.channelValues, bandArray); spectTable.put(SpectrumAdapter.bandNames, bandNames); } else { if (instrumentName.getStringValue().equals("CrIS")) { swathTable.put("XTrack", "dim1"); swathTable.put("Track", "dim0"); swathTable.put("geo_XTrack", "dim1"); swathTable.put("geo_Track", "dim0"); swathTable.put("product_name", "CrIS_SDR"); swathTable.put(SpectrumAdapter.channelIndex_name, "dim3"); swathTable.put(SpectrumAdapter.FOVindex_name, "dim2"); spectTable.put(SpectrumAdapter.channelIndex_name, "dim3"); spectTable.put(SpectrumAdapter.FOVindex_name, "dim2"); spectTable.put(SpectrumAdapter.x_dim_name, "dim1"); spectTable.put(SpectrumAdapter.y_dim_name, "dim0"); } else if (instrumentName.getStringValue().contains("OMPS")) { spectTable.put(SpectrumAdapter.channelIndex_name, "Channel"); swathTable.put(SpectrumAdapter.channelIndex_name, "Channel"); swathTable.put("array_dimension_names", new String[] { "Track", "XTrack", "Channel" }); swathTable.put("lon_array_dimension_names", new String[] { "Track", "XTrack" }); swathTable.put("lat_array_dimension_names", new String[] { "Track", "XTrack" }); spectTable.put("array_dimension_names", new String[] { "Track", "XTrack", "Channel" }); spectTable.put("lon_array_dimension_names", new String[] { "Track", "XTrack" }); spectTable.put("lat_array_dimension_names", new String[] { "Track", "XTrack" }); spectTable.put(SpectrumAdapter.channelType, "wavelength"); spectTable.put(SpectrumAdapter.channels_name, "Channel"); spectTable.put(SpectrumAdapter.x_dim_name, "XTrack"); spectTable.put(SpectrumAdapter.y_dim_name, "Track"); int numChannels = 200; if (instrumentName.getStringValue().equals("OMPS-TC")) { numChannels = 260; } logger.debug("Setting up OMPS adapter, num channels: " + numChannels); float[] bandArray = new float[numChannels]; String[] bandNames = new String[numChannels]; for (int bIdx = 0; bIdx < numChannels; bIdx++) { bandArray[bIdx] = bIdx; bandNames[bIdx] = "Channel " + (bIdx + 1); } spectTable.put(SpectrumAdapter.channelValues, bandArray); spectTable.put(SpectrumAdapter.bandNames, bandNames); } else { // sorry, if we can't id the instrument, we can't display the data! throw new VisADException("Unable to determine instrument name"); } } } else { swathTable.put("array_dimension_names", new String[] { "Track", "XTrack" }); swathTable.put("lon_array_dimension_names", new String[] { "Track", "XTrack" }); swathTable.put("lat_array_dimension_names", new String[] { "Track", "XTrack" }); } swathTable.put("scale_name", "scale_factor"); swathTable.put("offset_name", "add_offset"); swathTable.put("fill_value_name", "_FillValue"); swathTable.put("range_name", pStr.substring(pStr.indexOf(SEPARATOR_CHAR) + 1)); spectTable.put("range_name", pStr.substring(pStr.indexOf(SEPARATOR_CHAR) + 1)); // set the valid range hash if data is available if (nppPP != null) { if (nppPP.getRangeMin(pStr.substring(pStr.lastIndexOf(SEPARATOR_CHAR) + 1)) != null) { swathTable.put("valid_range", "valid_range"); } } String unsignedAttributeStr = unsignedFlags.get(pStr); if ((unsignedAttributeStr != null) && (unsignedAttributeStr.equals("true"))) { swathTable.put("unsigned", unsignedAttributeStr); } String unpackFlagStr = unpackFlags.get(pStr); if ((unpackFlagStr != null) && (unpackFlagStr.equals("true"))) { swathTable.put("unpack", "true"); } // For Suomi NPP data, do valid range check AFTER applying scale/offset swathTable.put("range_check_after_scaling", "true"); // pass in a GranuleAggregation reader... if (!isVIIRS) { if (instrumentName.getStringValue().equals("ATMS")) { adapters[pIdx] = new SwathAdapter(nppAggReader, swathTable); adapterCreated = true; SpectrumAdapter sa = new SpectrumAdapter(nppAggReader, spectTable); DataCategory.createCategory("MultiSpectral"); categories = DataCategory.parseCategories("MultiSpectral;MultiSpectral;IMAGE"); MultiSpectralData msd = new MultiSpectralData((SwathAdapter) adapters[pIdx], sa, "BrightnessTemperature", "BrightnessTemperature", "SuomiNPP", "ATMS"); msd.setInitialWavenumber(JPSSUtilities.ATMSChannelCenterFrequencies[0]); multiSpectralData.add(msd); } if (instrumentName.getStringValue().equals("CrIS")) { if (pStr.contains(crisFilter)) { adapters[pIdx] = new CrIS_SDR_SwathAdapter(nppAggReader, swathTable); adapterCreated = true; CrIS_SDR_Spectrum csa = new CrIS_SDR_Spectrum(nppAggReader, spectTable); DataCategory.createCategory("MultiSpectral"); categories = DataCategory.parseCategories("MultiSpectral;MultiSpectral;IMAGE"); MultiSpectralData msd = new CrIS_SDR_MultiSpectralData( (CrIS_SDR_SwathAdapter) adapters[pIdx], csa); msd.setInitialWavenumber(csa.getInitialWavenumber()); msd_CrIS.add(msd); } } if (instrumentName.getStringValue().contains("OMPS")) { adapters[pIdx] = new SwathAdapter(nppAggReader, swathTable); adapterCreated = true; SpectrumAdapter sa = new SpectrumAdapter(nppAggReader, spectTable); DataCategory.createCategory("MultiSpectral"); categories = DataCategory.parseCategories("MultiSpectral;MultiSpectral;IMAGE"); MultiSpectralData msd = new MultiSpectralData((SwathAdapter) adapters[pIdx], sa, "RadianceEarth", "RadianceEarth", "SuomiNPP", "OMPS"); msd.setInitialWavenumber(0); multiSpectralData.add(msd); } if (pIdx == 0) { // generate default subset for ATMS and OMPS if (!instrumentName.getStringValue().equals("CrIS")) { defaultSubset = multiSpectralData.get(pIdx).getDefaultSubset(); } } } else { // setting NOAA-format units String varName = pStr.substring(pStr.indexOf(SEPARATOR_CHAR) + 1); String varShortName = pStr.substring(pStr.lastIndexOf(SEPARATOR_CHAR) + 1); String units = nppPP.getUnits(varShortName); // setting NASA-format units if (!isNOAA) { units = unitsNASA.get(varShortName); // Need to set _BT variables manually, since they are created on the fly if (varShortName.endsWith("_BT")) units = "Kelvin"; } if (units == null) units = "Unknown"; Unit u = null; try { u = Parser.parse(units); } catch (NoSuchUnitException e) { u = new DerivedUnit(units); logger.debug("Unknown units: " + units); } catch (ParseException e) { u = new DerivedUnit(units); logger.debug("Unparseable units: " + units); } // associate this variable with these units, if not done already RealType.getRealType(varName, u); adapters[pIdx] = new SwathAdapter(nppAggReader, swathTable); adapterCreated = true; if (pIdx == 0) { defaultSubset = adapters[pIdx].getDefaultSubset(); } categories = DataCategory.parseCategories("IMAGE"); } // only increment count if we created an adapter, some products are skipped if (adapterCreated) pIdx++; adapterCreated = false; } if (msd_CrIS.size() > 0) { try { MultiSpectralAggr aggr = new MultiSpectralAggr( msd_CrIS.toArray(new MultiSpectralData[msd_CrIS.size()])); aggr.setInitialWavenumber(902.25f); multiSpectralData.add(aggr); defaultSubset = ((MultiSpectralData) msd_CrIS.get(0)).getDefaultSubset(); } catch (Exception e) { logger.error("Exception: ", e); } } // Merge with pre-set properties Hashtable tmpHt = getProperties(); tmpHt.putAll(properties); setProperties(tmpHt); }
From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java
License:Apache License
/** * Method that generates the namespace declarations which will be appended to the root of the generated XSD files. * @param namespaceURIToPrefixMappings solved namespace URI-to-prefix mappings * @param xsdNamespace namespace of XSD// w ww . jav a 2 s. c o m * @return a list of {@link Namespace} JDOM2 object that describe the solved mappings and includes the declaration of the * XSD namespace used by the generated XSD itself. */ private List<Namespace> getNamespaceDeclarations(Map<String, String> namespaceURIToPrefixMappings, Namespace xsdNamespace) { List<Namespace> namespaceDeclarations = new ArrayList<>(namespaceURIToPrefixMappings.size() + 1); namespaceDeclarations.add(xsdNamespace); for (String namespaceURI : ImmutableSortedSet.copyOf(namespaceURIToPrefixMappings.keySet())) { String namespacePrefix = namespaceURIToPrefixMappings.get(namespaceURI).replace(":", ""); if (namespaceURI.equals("")) { namespaceDeclarations.add(Namespace.NO_NAMESPACE); } else if (namespacePrefix.equals("")) { namespaceDeclarations.add(Namespace.getNamespace(namespaceURI)); } else { namespaceDeclarations.add(Namespace.getNamespace(namespacePrefix, namespaceURI)); } } return namespaceDeclarations; }
From source file:fr.amap.lidar.amapvox.gui.viewer3d.Viewer3DFrameController.java
/** * Initializes the controller class./*w w w .j a v a2 s. c o m*/ */ @Override public void initialize(URL url, ResourceBundle rb) { treeviewSceneObjects .setCellFactory(new Callback<TreeView<SceneObjectWrapper>, TreeCell<SceneObjectWrapper>>() { @Override public TreeCell<SceneObjectWrapper> call(TreeView<SceneObjectWrapper> param) { return new SceneObjectTreeCell(); } }); root = new TreeItem<>(); root.setExpanded(true); treeviewSceneObjects.setRoot(root); checkMenuItemPerspective.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { checkMenuItemOrthographic.setSelected(!newValue); } }); checkMenuItemOrthographic.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { checkMenuItemPerspective.setSelected(!newValue); } }); checkMenuItemOrthographic.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue) { try { float near = Float.valueOf(textfieldCameraNear.getText()); float far = Float.valueOf(textfieldCameraFar.getText()); viewer3D.getJoglContext().getScene().getCamera().setViewToOrthographic(near, far, far, far, near, far); viewer3D.getJoglContext().updateCamera(); viewer3D.getJoglContext().refresh(); } catch (Exception e) { } } } }); checkMenuItemPerspective.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue) { try { float fov = Float.valueOf(textFieldPerspective.getText()); float near = Float.valueOf(textfieldCameraNear.getText()); float far = Float.valueOf(textfieldCameraFar.getText()); viewer3D.getJoglContext().getScene().getCamera().setViewToPerspective(fov, near, far); viewer3D.getJoglContext().updateCamera(); viewer3D.getJoglContext().refresh(); } catch (Exception e) { } } } }); textFieldPerspective.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { try { float fov = Float.valueOf(newValue); TrackballCamera camera = viewer3D.getJoglContext().getScene().getCamera(); viewer3D.getJoglContext().getScene().getCamera().setPerspective(fov, camera.getAspect(), camera.getNearPersp(), camera.getFarPersp()); viewer3D.getJoglContext().refresh(); } catch (Exception e) { } } }); tableColumnName.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<Viewer3DFrameController.Attribut, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TableColumn.CellDataFeatures<Attribut, String> param) { return new SimpleStringProperty(param.getValue().getName()); } }); tableColumnValue.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<Viewer3DFrameController.Attribut, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TableColumn.CellDataFeatures<Attribut, String> param) { return new SimpleStringProperty(String.valueOf(param.getValue().getValue())); } }); comboboxGradient.getItems().addAll(Util.AVAILABLE_GRADIENT_COLOR_NAMES); comboboxGradient.getSelectionModel().select("HEAT"); isHidden = false; colorPickerBackgroundColor.valueProperty().addListener(new ChangeListener<javafx.scene.paint.Color>() { @Override public void changed(ObservableValue<? extends javafx.scene.paint.Color> observable, javafx.scene.paint.Color oldValue, javafx.scene.paint.Color newValue) { try { //read sgv file URL resource = Viewer3DFrameController.class.getResource("/fxml/icons/pinceau.svg"); SAXBuilder sxb = new SAXBuilder(); Document document = sxb.build(resource); final Element root = document.getRootElement(); //edit svg file final List<Element> graphicElements = root.getChildren("g", root.getNamespace()); String hexColor = null; for (Element element : graphicElements) { String attributeValue = element.getAttributeValue("label", Namespace.getNamespace("http://www.inkscape.org/namespaces/inkscape")); if (attributeValue != null && attributeValue.equals("ciel")) { final Element ellipse = element.getChild("ellipse", root.getNamespace()); String style = ellipse.getAttributeValue("style"); int indexOf = style.indexOf("fill:#"); hexColor = Integer.toHexString((int) (newValue.getRed() * 255)) + Integer.toHexString((int) (newValue.getGreen() * 255)) + Integer.toHexString((int) (newValue.getBlue() * 255)); style = style.substring(0, indexOf + 6) + hexColor + style.substring(indexOf + 12); ellipse.setAttribute("style", style); } else if (attributeValue != null && attributeValue.equals("peinture")) { final Element path = element.getChild("path", root.getNamespace()); String style = path.getAttributeValue("style"); int indexOf = style.indexOf("fill:#"); DecimalFormat df = new DecimalFormat("##"); hexColor = Integer.toHexString((int) (newValue.getRed() * 255)) + Integer.toHexString((int) (newValue.getGreen() * 255)) + Integer.toHexString((int) (newValue.getBlue() * 255)); style = style.substring(0, indexOf + 6) + hexColor + style.substring(indexOf + 12); path.setAttribute("style", style); } } if (hexColor != null) { SVGConverter conv = new SVGConverter(); conv.setWidth(32.0f); conv.setHeight(32.0f); conv.setMediaType("image/png"); File tmpSVGFile = File.createTempFile("skycolor", ".svg"); File tmpPNGFile = File.createTempFile("skycolor", ".png"); //convert svg to png conv.setSources(new String[] { tmpSVGFile.toURI().toURL().toString() }); conv.setDst(tmpPNGFile); XMLOutputter output = new XMLOutputter(Format.getPrettyFormat()); output.output(document, new BufferedOutputStream(new FileOutputStream(tmpSVGFile))); conv.execute(); //change sky icon Image image = new Image(tmpPNGFile.toURI().toURL().toString()); imageviewSkyColor.setImage(image); } } catch (Exception ex) { java.util.logging.Logger.getLogger(Viewer3DFrameController.class.getName()).log(Level.SEVERE, null, ex); } if (viewer3D != null) { viewer3D.getJoglContext().setWorldColor(new Vec3F((float) newValue.getRed(), (float) newValue.getGreen(), (float) newValue.getBlue())); viewer3D.getJoglContext().refresh(); } } }); comboboxGradient.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { String gradient = newValue; Color[] gradientColor = ColorGradient.GRADIENT_RAINBOW; for (int i = 0; i < Util.AVAILABLE_GRADIENT_COLORS.size(); i++) { if (Util.AVAILABLE_GRADIENT_COLOR_NAMES.get(i).equals(gradient)) { gradientColor = Util.AVAILABLE_GRADIENT_COLORS.get(i); i = Util.AVAILABLE_GRADIENT_COLOR_NAMES.size() - 1; } } //recalculate voxel color with the new gradient voxelSpace.updateColorValue(gradientColor); //update instance color buffer to gpu voxelSpace.updateInstanceColorBuffer(); viewer3D.getJoglContext().refresh(); } }); colorPickerBackgroundColor.setValue(new javafx.scene.paint.Color(0.8, 0.8, 0.8, 1)); colorpickerLightingAmbientColor.setValue(new javafx.scene.paint.Color(1.0, 1.0, 1.0, 1)); colorpickerLightingDiffuseColor.setValue(new javafx.scene.paint.Color(1.0, 1.0, 1.0, 1)); colorpickerLightingSpecularColor.setValue(new javafx.scene.paint.Color(1.0, 1.0, 1.0, 1)); colorpickerLightingAmbientColor.valueProperty().addListener(new ChangeListener<javafx.scene.paint.Color>() { @Override public void changed(ObservableValue<? extends javafx.scene.paint.Color> observable, javafx.scene.paint.Color oldValue, javafx.scene.paint.Color newValue) { viewer3D.getJoglContext().getScene().setLightAmbientValue(new Vec3F((float) newValue.getRed(), (float) newValue.getGreen(), (float) newValue.getBlue())); viewer3D.getJoglContext().refresh(); } }); colorpickerLightingDiffuseColor.valueProperty().addListener(new ChangeListener<javafx.scene.paint.Color>() { @Override public void changed(ObservableValue<? extends javafx.scene.paint.Color> observable, javafx.scene.paint.Color oldValue, javafx.scene.paint.Color newValue) { viewer3D.getJoglContext().getScene().setLightDiffuseValue(new Vec3F((float) newValue.getRed(), (float) newValue.getGreen(), (float) newValue.getBlue())); viewer3D.getJoglContext().refresh(); } }); colorpickerLightingSpecularColor.valueProperty() .addListener(new ChangeListener<javafx.scene.paint.Color>() { @Override public void changed(ObservableValue<? extends javafx.scene.paint.Color> observable, javafx.scene.paint.Color oldValue, javafx.scene.paint.Color newValue) { viewer3D.getJoglContext().getScene() .setLightSpecularValue(new Vec3F((float) newValue.getRed(), (float) newValue.getGreen(), (float) newValue.getBlue())); viewer3D.getJoglContext().refresh(); } }); comboBoxAttributeToShow.getSelectionModel().selectedItemProperty() .addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { try { voxelSpace.resetAttributValueRange(); voxelSpace.changeCurrentAttribut(newValue); voxelSpace.updateVao(); voxelSpace.updateInstanceColorBuffer(); viewer3D.getJoglContext().refresh(); textFieldMinValue.getEditor() .setText(String.valueOf(voxelSpace.getRealAttributValueMin())); textFieldMaxValue.getEditor() .setText(String.valueOf(voxelSpace.getRealAttributValueMax())); } catch (Exception e) { } } }); final InstanceLightedShader ils = new InstanceLightedShader(); final InstanceShader is = new InstanceShader(); checkMenuItemEnableLighting.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue) { voxelSpace.setShader(ils); } else { voxelSpace.setShader(is); } viewer3D.getJoglContext().refresh(); } }); /*textFieldFilterValues.setOnKeyReleased(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if(event.getCode() == KeyCode.ENTER){ updateValuesFilter(); } } });*/ checkboxStretched.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue) { voxelSpace.setStretched(true); voxelSpace.updateValue(); voxelSpace.updateInstanceColorBuffer(); viewer3D.getJoglContext().refresh(); } else { voxelSpace.setStretched(false); voxelSpace.updateValue(); voxelSpace.updateInstanceColorBuffer(); viewer3D.getJoglContext().refresh(); } } }); /* textfieldCameraNear.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { try{ float near = Float.valueOf(newValue); TrackballCamera camera = joglContext.getScene().getCamera(); if(radiobuttonOrthographicCamera.isSelected()){ joglContext.getScene().getCamera().setOrthographic(camera.getLeft(), camera.getRight(), camera.getTop(), camera.getBottom(), near, camera.getFarOrtho()); joglContext.updateCamera(); joglContext.refresh(); }else{ joglContext.getScene().getCamera().setPerspective(camera.getFovy(), camera.getAspect(), near, camera.getFarPersp()); joglContext.updateCamera(); joglContext.refresh(); } joglContext.refresh(); }catch(Exception e){} } }); textfieldCameraFar.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { try{ float far = Float.valueOf(newValue); TrackballCamera camera = joglContext.getScene().getCamera(); if(radiobuttonOrthographicCamera.isSelected()){ camera.setOrthographic(camera.getLeft(), camera.getRight(), camera.getTop(), camera.getBottom(), camera.getNearOrtho(), far); joglContext.updateCamera(); joglContext.refresh(); }else{ camera.setPerspective(camera.getFovy(), camera.getAspect(), camera.getNearPersp(), far); joglContext.updateCamera(); joglContext.refresh(); } joglContext.refresh(); }catch(Exception e){} } }); */ comboBoxScalarField.setItems(comboBoxAttributeToShow.getItems()); comboBoxScalarField.getItems().addListener(new ListChangeListener<String>() { @Override public void onChanged(ListChangeListener.Change<? extends String> c) { if (c.getList().size() > 0) { comboBoxScalarField.getSelectionModel().selectFirst(); } } }); checkMenuItemShowColorScale.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { viewer3D.getScene().getSceneObject("color scale").setVisible(newValue); viewer3D.getJoglContext().refresh(); } }); ToggleGroup group = new ToggleGroup(); radiobuttonDisplay.setToggleGroup(group); radiobuttonDontDisplay.setToggleGroup(group); CombinedFilter combFilter1 = new CombinedFilter(new Filter("x", 0.0f, Filter.EQUAL), null, CombinedFilter.AND); CombinedFilter combFilter2 = new CombinedFilter(new Filter("x", Float.NaN, Filter.EQUAL), null, CombinedFilter.AND); listviewFilters.getItems().add(new CombinedFilterItem("PadBVTotal", false, combFilter1.getFilter1(), combFilter1.getFilter2(), combFilter1.getType())); listviewFilters.getItems().add(new CombinedFilterItem("PadBVTotal", false, combFilter2.getFilter1(), combFilter2.getFilter2(), combFilter2.getType())); }
From source file:jodtemplate.pptx.ImageService.java
License:Apache License
private Namespace getDrawingmlNamespace() { return Namespace.getNamespace(PPTXDocument.DRAWINGML_NAMESPACE); }
From source file:jodtemplate.pptx.ImageService.java
License:Apache License
private Namespace getPresentationmlNamespace() { return Namespace.getNamespace(PPTXDocument.PRESENTATIONML_NAMESPACE); }
From source file:jodtemplate.pptx.ImageService.java
License:Apache License
private Namespace getRelationshipsNamespace() { return Namespace.getNamespace(PPTXDocument.RELATIONSHIPS_NAMESPACE); }
From source file:jodtemplate.pptx.preprocessor.FormatTagsPreprocessor.java
License:Apache License
private Namespace getNamespace() { return Namespace.getNamespace(PPTXDocument.DRAWINGML_NAMESPACE); }
From source file:lu.list.itis.dkd.assess.cloze.template.Template.java
License:Apache License
private Element layer() { Element layerElement = new Element("layer"); Comment layerComment = new Comment( "this section represents an XML-QTI item with placeholders for variables"); layerElement.addContent(layerComment); Namespace xmlnsNamespace = Namespace.getNamespace("http://www.imsglobal.org/xsd/imsqti_v2p0"); Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); // Namespace schemaLocation = Namespace.getNamespace("xsi:schemaLocation", "http://www.imsglobal.org/xsd/imsqti_v2p0 imsqti_v2p0.xsd"); Element assessmentItem = new Element("assessmentItem", xmlnsNamespace); layerElement.addContent(assessmentItem); assessmentItem.addNamespaceDeclaration(xsi); // assessmentItem.addNamespaceDeclaration(schemaLocation); assessmentItem.setAttribute("identifier", "ModalFeedback"); assessmentItem.setAttribute("title", title); assessmentItem.setAttribute("adaptive", "false"); assessmentItem.setAttribute("timeDependent", "false"); assessmentItem.addContent(clozeItem.getCorrectResponseBlocks()); if (useFeedback) { outcomeDeclarationFeedback(doc, assessmentItem); }//from w ww . j a v a 2 s . c om //outcomeScoreDeclaration Score Element Element outcomeScoreDeclaration = new Element("outcomeDeclaration"); assessmentItem.addContent(outcomeScoreDeclaration); outcomeScoreDeclaration.setAttribute("identifier", "SCORE"); outcomeScoreDeclaration.setAttribute("cardinality", "single"); outcomeScoreDeclaration.setAttribute("baseType", "float"); //defaultScoreValue Element Element defaultScoreValue = new Element("defaultValue"); outcomeScoreDeclaration.addContent(defaultScoreValue); //scoreValue element Element scoreValue = new Element("value"); scoreValue.setText("0"); defaultScoreValue.addContent(scoreValue); Element itemBody = new Element("itemBody"); assessmentItem.addContent(itemBody); Element blockquote = new Element("blockquote"); itemBody.addContent(blockquote); //Add qti cloze text blockquote.addContent(clozeItem.getClozeBlock()); Element responseProcessing = new Element("responseProcessing"); assessmentItem.addContent(responseProcessing); //Add feedback if (useFeedback) { for (ClozeSentence clozeSentence : clozeItem.getClozeSentences()) { int keyIndex = 1; for (Key key : clozeSentence.getKeys()) { Element correctModalFeedback = new Element("modalFeedback"); correctModalFeedback.setAttribute("outcomeIdentifier", "FEEDBACK_CORRECT" + keyIndex); correctModalFeedback.setAttribute("showHide", "show"); correctModalFeedback.setAttribute("identifier", "correctFeedback"); correctModalFeedback.setText(key.getFeedback()); assessmentItem.addContent(correctModalFeedback); int distractorIndex = 2; for (Distractor distractor : key.getDistractors()) { Element incorrectModalFeedback = new Element("modalFeedback"); incorrectModalFeedback.setAttribute("outcomeIdentifier", "FEEDBACK_INCORRECT" + (distractorIndex)); incorrectModalFeedback.setAttribute("showHide", "show"); incorrectModalFeedback.setAttribute("identifier", "incorrectFeedback"); incorrectModalFeedback.setText(distractor.getFeedback()); assessmentItem.addContent(incorrectModalFeedback); distractorIndex++; } distractorIndex++; } } } return layerElement; }
From source file:msk.drugbank4.DrugBankParser.java
License:Apache License
public DrugBankParser() { nsDrugBank = Namespace.getNamespace("http://www.drugbank.ca"); }
From source file:neon.editor.SVGExporter.java
License:Open Source License
public static void exportToSVG(ZoneTreeNode node, FileSystem files, DataStore store) { if (node != null) { Namespace ns = Namespace.getNamespace("http://www.w3.org/2000/svg"); Element svg = new Element("svg", ns); Document doc = new Document(svg); doc.setDocType(new DocType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd")); svg.setAttribute("width", "100%"); svg.setAttribute("height", "100%"); svg.setAttribute("version", "1.1"); ArrayList<Renderable> regions = new ArrayList<Renderable>(node.getZone().getScene().getElements()); Collections.sort(regions, new ZComparator()); for (Renderable i : regions) { if (i instanceof IRegion) { IRegion ri = (IRegion) i; Element region = new Element("rect", ns); region.setAttribute("x", Integer.toString(ri.x)); region.setAttribute("y", Integer.toString(ri.y)); region.setAttribute("width", Integer.toString(ri.width)); region.setAttribute("height", Integer.toString(ri.height)); int red = ColorFactory.getColor(ri.resource.color).getRed(); int green = ColorFactory.getColor(ri.resource.color).getGreen(); int blue = ColorFactory.getColor(ri.resource.color).getBlue(); region.setAttribute("style", "fill:rgb(" + red + "," + green + "," + blue + ")"); svg.addContent(region);//from w ww . j a va2 s.c o m } } files.saveFile(doc, new XMLTranslator(), store.getActive().getPath()[0], "shots", node.getZone().map.id + ".svg"); } }