private void loadNeuralNet(File neuralNetFile) throws IOException, JnnException { Jnn.setOptimizing(true); neuralNet = Jnn.readNna(neuralNetFile); final Logger logger = BeamLogManager.getSystemLogger(); logger.info("Using JNN Neural Net Library, version " + Jnn.VERSION_STRING); logger.info(neuralNetFile + " loaded"); }
/** * Copies the given image to the system clipboard. * * @param image the image to copy */ public static void copyToClipboard(final Image image) { ImageSelection selection = new ImageSelection(image); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if (clipboard != null) { clipboard.setContents(selection, null); } else { BeamLogManager.getSystemLogger().severe("failed to obtain clipboard instance"); } }
/** * Copies the given text to the system clipboard. * * @param text the text to copy */ public static void copyToClipboard(final String text) { StringSelection selection = new StringSelection(text == null ? "" : text); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if (clipboard != null) { clipboard.setContents(selection, selection); } else { BeamLogManager.getSystemLogger().severe("failed to obtain clipboard instance"); } }
private static void initJAI(ClassLoader cl) { System.setProperty( "com.sun.media.jai.disableMediaLib", "true"); // disable native libraries for JAI // Must use a new operation registry in order to register JAI operators defined in Ceres and // BEAM OperationRegistry operationRegistry = OperationRegistry.getThreadSafeOperationRegistry(); InputStream is = SystemUtils.class.getResourceAsStream(JAI_REGISTRY_PATH); if (is != null) { // Suppress ugly (and harmless) JAI error messages saying that a descriptor is already // registered. final PrintStream oldErr = System.err; try { setSystemErr(new PrintStream(new ByteArrayOutputStream())); operationRegistry.updateFromStream(is); operationRegistry.registerServices(cl); JAI.getDefaultInstance().setOperationRegistry(operationRegistry); } catch (IOException e) { BeamLogManager.getSystemLogger() .log( Level.SEVERE, MessageFormat.format("Error loading {0}: {1}", JAI_REGISTRY_PATH, e.getMessage()), e); } finally { setSystemErr(oldErr); } } else { BeamLogManager.getSystemLogger() .warning(MessageFormat.format("{0} not found", JAI_REGISTRY_PATH)); } Integer parallelism = Integer.getInteger( BEAM_PARALLELISM_PROPERTY_NAME, Runtime.getRuntime().availableProcessors()); JAI.getDefaultInstance().getTileScheduler().setParallelism(parallelism); BeamLogManager.getSystemLogger() .info(MessageFormat.format("JAI tile scheduler parallelism set to {0}", parallelism)); }
@Override public void parseRecords(int offset, int numRecords) throws IOException { featureCollection = new ListFeatureCollection(simpleFeatureType); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(simpleFeatureType); skipToLine(offset); String line; long featureCount = offset; while ((numRecords == -1 || featureCount < offset + numRecords) && (line = stream.readLine()) != null) { String[] tokens = getTokens(line); if (tokens == null) { break; } int expectedTokenCount = simpleFeatureType.getAttributeCount(); expectedTokenCount += hasFeatureId ? 1 : 0; if (tokens.length != expectedTokenCount) { continue; } builder.reset(); String featureId = "" + featureCount++; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (i == 0 && hasFeatureId) { featureId = token; } else { try { Object value = null; int currentIndex = i; currentIndex -= hasFeatureId ? 1 : 0; if (!VectorDataNodeIO.NULL_TEXT.equals(token)) { value = converters[currentIndex].parse(token); } builder.set(simpleFeatureType.getDescriptor(currentIndex).getLocalName(), value); } catch (ConversionException e) { BeamLogManager.getSystemLogger() .warning(String.format("Problem in '%s': %s", csv.getPath(), e.getMessage())); } } } SimpleFeature simpleFeature = builder.buildFeature(featureId); featureCollection.add(simpleFeature); bytePositionForOffset.put(featureCount, stream.getStreamPosition()); } recordsParsed = true; }
public static void loadAvailableColorPalettes(File palettesDir) { cpdRasterList = new HashMap<>(); final ArrayList<ColorPaletteDef> newCpdList = new ArrayList<>(); final ArrayList<String> newCpdNames = new ArrayList<>(); final File[] files = palettesDir.listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".cpd"); } }); for (File file : files) { try { final ColorPaletteDef newCpd = ColorPaletteDef.loadColorPaletteDef(file); newCpdList.add(newCpd); newCpdNames.add(file.getName()); } catch (IOException e) { final Logger logger = BeamLogManager.getSystemLogger(); logger.warning( "Unable to load color palette definition from file '" + file.getAbsolutePath() + "'"); logger.log(Level.INFO, e.getMessage(), e); } } if (cpdList != null) { for (ColorPaletteDef oldCpd : cpdList) { if (newCpdList.contains(oldCpd)) { final int i = newCpdList.indexOf(oldCpd); final ColorPaletteDef newCpd = newCpdList.get(i); cpdRasterList.put(newCpd, cpdRasterList.remove(oldCpd)); } else { final List<RasterDataNode> nodes = cpdRasterList.remove(oldCpd); if (nodes != null) { nodes.clear(); } } } cpdNames.clear(); cpdList.clear(); } cpdNames = newCpdNames; cpdList = newCpdList; }
@Deprecated private static Class<?> loadClassWithNativeDependencies( Class<?> callerClass, String className, String warningPattern) { ClassLoader classLoader = callerClass.getClassLoader(); String classResourceName = "/" + className.replace('.', '/') + ".class"; SystemUtils.class.getResource(classResourceName); if (callerClass.getResource(classResourceName) != null) { try { return Class.forName(className, true, classLoader); } catch (Throwable error) { BeamLogManager.getSystemLogger() .warning( MessageFormat.format( warningPattern, callerClass, error.getClass(), error.getMessage())); return null; } } else { return null; } }
@Override public Object[] parseRecords(final int offset, final int numRecords, final String rowName) throws IOException { AttributeDescriptor attributeDescriptor = simpleFeatureType.getDescriptor(rowName); int expectedTokenCount = simpleFeatureType.getAttributeCount(); expectedTokenCount += hasFeatureId ? 1 : 0; int rowIndex = simpleFeatureType.getAttributeDescriptors().indexOf(attributeDescriptor); int tokenIndex = rowIndex + (hasFeatureId ? 1 : 0); List<Object> values = new ArrayList<>(numRecords); skipToLine(offset); String line; long featureCount = offset; while ((numRecords == -1 || featureCount < offset + numRecords) && (line = stream.readLine()) != null) { String[] tokens = getTokens(line); if (tokens == null) { break; } if (tokens.length != expectedTokenCount) { continue; } featureCount++; String token = tokens[tokenIndex]; try { Object value = null; if (!VectorDataNodeIO.NULL_TEXT.equals(token)) { value = converters[rowIndex].parse(token); } values.add(value); } catch (ConversionException e) { BeamLogManager.getSystemLogger() .warning(String.format("Problem in '%s': %s", csv.getPath(), e.getMessage())); } bytePositionForOffset.put(featureCount, stream.getStreamPosition()); } return values.toArray(); }
@Override protected Product readProductNodesImpl() throws IOException { final String s = getInput().toString(); final File file0 = new File(s); final File dir = file0.getParentFile(); final S2FilenameInfo fni0 = S2FilenameInfo.create(file0.getName()); if (fni0 == null) { throw new IOException(); } Header metadataHeader = null; final Map<Integer, BandInfo> fileMap = new HashMap<Integer, BandInfo>(); if (dir != null) { File[] files = dir.listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(Sentinel2ProductReaderPlugIn.JP2_EXT); } }); if (files != null) { for (File file : files) { int bandIndex = fni0.getBand(file.getName()); if (bandIndex >= 0 && bandIndex < WAVEBAND_INFOS.length) { final S2WavebandInfo wavebandInfo = WAVEBAND_INFOS[bandIndex]; BandInfo bandInfo = new BandInfo( file, bandIndex, wavebandInfo, imageLayouts[wavebandInfo.resolution.id]); fileMap.put(bandIndex, bandInfo); } } } File[] metadataFiles = dir.listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith("MTD_") && name.endsWith(".xml"); } }); if (metadataFiles != null && metadataFiles.length > 0) { File metadataFile = metadataFiles[0]; try { metadataHeader = Header.parseHeader(metadataFile); } catch (JDOMException e) { BeamLogManager.getSystemLogger() .warning("Failed to parse metadata file: " + metadataFile); } } else { BeamLogManager.getSystemLogger().warning("No metadata file found"); } } final ArrayList<Integer> bandIndexes = new ArrayList<Integer>(fileMap.keySet()); Collections.sort(bandIndexes); if (bandIndexes.isEmpty()) { throw new IOException("No valid bands found."); } String prodType = "S2_MSI_" + fni0.procLevel; final Product product = new Product( String.format("%s_%s_%s", prodType, fni0.orbitNo, fni0.tileId), prodType, imageLayouts[S2Resolution.R10M.id].width, imageLayouts[S2Resolution.R10M.id].height); try { product.setStartTime(ProductData.UTC.parse(fni0.start, "yyyyMMddHHmmss")); } catch (ParseException e) { // warn } try { product.setEndTime(ProductData.UTC.parse(fni0.stop, "yyyyMMddHHmmss")); } catch (ParseException e) { // warn } if (metadataHeader != null) { SceneDescription sceneDescription = SceneDescription.create(metadataHeader); int tileIndex = sceneDescription.getTileIndex(fni0.tileId); Envelope2D tileEnvelope = sceneDescription.getTileEnvelope(tileIndex); Header.Tile tile = metadataHeader.getTileList().get(tileIndex); try { product.setGeoCoding( new CrsGeoCoding( tileEnvelope.getCoordinateReferenceSystem(), imageLayouts[S2Resolution.R10M.id].width, imageLayouts[S2Resolution.R10M.id].height, tile.tileGeometry10M.upperLeftX, tile.tileGeometry10M.upperLeftY, tile.tileGeometry10M.xDim, -tile.tileGeometry10M.yDim, 0.0, 0.0)); } catch (FactoryException e) { // todo - handle e } catch (TransformException e) { // todo - handle e } } for (Integer bandIndex : bandIndexes) { final BandInfo bandInfo = fileMap.get(bandIndex); final Band band = product.addBand(bandInfo.wavebandInfo.bandName, ProductData.TYPE_UINT16); band.setSpectralWavelength((float) bandInfo.wavebandInfo.centralWavelength); band.setSpectralBandwidth((float) bandInfo.wavebandInfo.bandWidth); band.setSpectralBandIndex(bandIndex); band.setSourceImage(new DefaultMultiLevelImage(new Jp2MultiLevelSource(bandInfo))); } product.setNumResolutionLevels(imageLayouts[0].numResolutions); return product; }