Example usage for javax.imageio ImageReader getOriginatingProvider

List of usage examples for javax.imageio ImageReader getOriginatingProvider

Introduction

In this page you can find the example usage for javax.imageio ImageReader getOriginatingProvider.

Prototype

public ImageReaderSpi getOriginatingProvider() 

Source Link

Document

Returns the ImageReaderSpi that was passed in on the constructor.

Usage

From source file:it.tidalwave.imageio.test.ImageReaderTestSupport.java

/*******************************************************************************************************************
 *
 *
 ******************************************************************************************************************/
protected void assertMIMETypes(final String extension, final String... mimeTypes) {
    final Iterator<ImageReader> i = ImageIO.getImageReadersBySuffix(extension);
    assertTrue(i.hasNext());/* w w  w  .  j  av a  2 s .c om*/
    final ImageReader ir = i.next();
    assertNotNull(ir);
    assertFalse(i.hasNext());
    final ImageReaderSpi provider = ir.getOriginatingProvider();
    assertEquals(mimeTypes, provider.getMIMETypes());
}

From source file:org.apache.xmlgraphics.image.loader.impl.imageio.ImageLoaderImageIO.java

/** {@inheritDoc} */
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session)
        throws ImageException, IOException {
    RenderedImage imageData = null;
    IIOException firstException = null;

    IIOMetadata iiometa = (IIOMetadata) info.getCustomObjects().get(ImageIOUtil.IMAGEIO_METADATA);
    boolean ignoreMetadata = (iiometa != null);
    boolean providerIgnoresICC = false;

    Source src = session.needSource(info.getOriginalURI());
    ImageInputStream imgStream = ImageUtil.needImageInputStream(src);
    try {/* w  w  w. ja va  2 s.  c  o  m*/
        Iterator iter = ImageIO.getImageReaders(imgStream);
        while (iter.hasNext()) {
            ImageReader reader = (ImageReader) iter.next();
            try {
                imgStream.mark();
                ImageReadParam param = reader.getDefaultReadParam();
                reader.setInput(imgStream, false, ignoreMetadata);
                final int pageIndex = ImageUtil.needPageIndexFromURI(info.getOriginalURI());
                try {
                    if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
                        imageData = reader.read(pageIndex, param);
                    } else {
                        imageData = reader.read(pageIndex, param);
                        //imageData = reader.readAsRenderedImage(pageIndex, param);
                        //TODO Reenable the above when proper listeners are implemented
                        //to react to late pixel population (so the stream can be closed
                        //properly).
                    }
                    if (iiometa == null) {
                        iiometa = reader.getImageMetadata(pageIndex);
                    }
                    providerIgnoresICC = checkProviderIgnoresICC(reader.getOriginatingProvider());
                    break; //Quit early, we have the image
                } catch (IndexOutOfBoundsException indexe) {
                    throw new ImageException("Page does not exist. Invalid image index: " + pageIndex);
                } catch (IllegalArgumentException iae) {
                    //Some codecs like com.sun.imageio.plugins.wbmp.WBMPImageReader throw
                    //IllegalArgumentExceptions when they have trouble parsing the image.
                    throw new ImageException("Error loading image using ImageIO codec", iae);
                } catch (IIOException iioe) {
                    if (firstException == null) {
                        firstException = iioe;
                    } else {
                        log.debug("non-first error loading image: " + iioe.getMessage());
                    }
                }
                try {
                    //Try fallback for CMYK images
                    BufferedImage bi = getFallbackBufferedImage(reader, pageIndex, param);
                    imageData = bi;
                    firstException = null; //Clear exception after successful fallback attempt
                    break;
                } catch (IIOException iioe) {
                    //ignore
                }
                imgStream.reset();
            } finally {
                reader.dispose();
            }
        }
    } finally {
        ImageUtil.closeQuietly(src);
        //TODO Some codecs may do late reading.
    }
    if (firstException != null) {
        throw new ImageException("Error while loading image: " + firstException.getMessage(), firstException);
    }
    if (imageData == null) {
        throw new ImageException("No ImageIO ImageReader found .");
    }

    ColorModel cm = imageData.getColorModel();

    Color transparentColor = null;
    if (cm instanceof IndexColorModel) {
        //transparent color will be extracted later from the image
    } else {
        if (providerIgnoresICC && cm instanceof ComponentColorModel) {
            // Apply ICC Profile to Image by creating a new image with a new
            // color model.
            ICC_Profile iccProf = tryToExctractICCProfile(iiometa);
            if (iccProf != null) {
                ColorModel cm2 = new ComponentColorModel(new ICC_ColorSpace(iccProf), cm.hasAlpha(),
                        cm.isAlphaPremultiplied(), cm.getTransparency(), cm.getTransferType());
                WritableRaster wr = Raster.createWritableRaster(imageData.getSampleModel(), null);
                imageData.copyData(wr);
                BufferedImage bi = new BufferedImage(cm2, wr, cm2.isAlphaPremultiplied(), null);
                imageData = bi;
                cm = cm2;
            }
        }
        // ImageIOUtil.dumpMetadataToSystemOut(iiometa);
        // Retrieve the transparent color from the metadata
        if (iiometa != null && iiometa.isStandardMetadataFormatSupported()) {
            Element metanode = (Element) iiometa.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
            Element dim = ImageIOUtil.getChild(metanode, "Transparency");
            if (dim != null) {
                Element child;
                child = ImageIOUtil.getChild(dim, "TransparentColor");
                if (child != null) {
                    String value = child.getAttribute("value");
                    if (value == null || value.length() == 0) {
                        //ignore
                    } else if (cm.getNumColorComponents() == 1) {
                        int gray = Integer.parseInt(value);
                        transparentColor = new Color(gray, gray, gray);
                    } else {
                        StringTokenizer st = new StringTokenizer(value);
                        transparentColor = new Color(Integer.parseInt(st.nextToken()),
                                Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
                    }
                }
            }
        }
    }

    if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
        return new ImageBuffered(info, (BufferedImage) imageData, transparentColor);
    } else {
        return new ImageRendered(info, imageData, transparentColor);
    }
}

From source file:org.geoserver.opensearch.rest.CollectionsController.java

private void configureSeparateBandsMosaic(String collection, CollectionLayer layerConfiguration,
        String relativePath, Resource mosaicDirectory) throws Exception {
    // get the namespace URI for the store
    final FeatureSource<FeatureType, Feature> collectionSource = getOpenSearchAccess().getCollectionSource();
    final FeatureType schema = collectionSource.getSchema();
    final String nsURI = schema.getName().getNamespaceURI();

    // image mosaic won't automatically create the mosaic config for us in this case,
    // we have to setup both the mosaic property file and sample image for all bands
    for (int band : layerConfiguration.getBands()) {
        final String mosaicName = collection + OpenSearchAccess.BAND_LAYER_SEPARATOR + band;

        // get the sample granule
        File file = getSampleGranule(collection, nsURI, band, mosaicName);
        AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(file,
                EXCLUDE_MOSAIC_HINTS);/* w  w w.  j a  v a2 s  .  c o  m*/
        if (format == null) {
            throw new RestException(
                    "Could not find a coverage reader able to process " + file.getAbsolutePath(),
                    HttpStatus.PRECONDITION_FAILED);
        }
        ImageLayout imageLayout;
        double[] nativeResolution;
        AbstractGridCoverage2DReader reader = null;
        try {
            reader = format.getReader(file);
            if (reader == null) {
                throw new RestException(
                        "Could not find a coverage reader able to process " + file.getAbsolutePath(),
                        HttpStatus.PRECONDITION_FAILED);
            }
            imageLayout = reader.getImageLayout();
            nativeResolution = reader.getResolutionLevels()[0];
        } finally {
            if (reader != null) {
                reader.dispose();
            }
        }
        ImageReaderSpi spi = null;
        try (FileImageInputStream fis = new FileImageInputStream(file)) {
            ImageReader imageReader = ImageIOExt.getImageioReader(fis);
            if (imageReader != null) {
                spi = imageReader.getOriginatingProvider();
            }
        }

        // the mosaic configuration
        Properties mosaicConfig = new Properties();
        mosaicConfig.put("Levels", nativeResolution[0] + "," + nativeResolution[1]);
        mosaicConfig.put("Heterogeneous", "true");
        mosaicConfig.put("AbsolutePath", "true");
        mosaicConfig.put("Name", "" + band);
        mosaicConfig.put("TypeName", mosaicName);
        mosaicConfig.put("TypeNames", "false"); // disable typename scanning
        mosaicConfig.put("Caching", "false");
        mosaicConfig.put("LocationAttribute", "location");
        mosaicConfig.put("TimeAttribute", TIME_START);
        mosaicConfig.put("CanBeEmpty", "true");
        if (spi != null) {
            mosaicConfig.put("SuggestedSPI", spi.getClass().getName());
        }
        // TODO: the index is now always in 4326, so the mosaic has to be heterogeneous
        // in general, unless we know the data is uniformly in something else, in that
        // case we could reproject the view reporting the footprints...
        //            if (layerConfiguration.isHeterogeneousCRS()) {
        mosaicConfig.put("HeterogeneousCRS", "true");
        mosaicConfig.put("MosaicCRS", "EPSG:4326" /* layerConfiguration.getMosaicCRS() */);
        mosaicConfig.put("CrsAttribute", "crs");
        //            }
        Resource propertyResource = mosaicDirectory.get(band + ".properties");
        try (OutputStream os = propertyResource.out()) {
            mosaicConfig.store(os,
                    "DataStore configuration for collection '" + collection + "' and band '" + band + "'");
        }

        // create the sample image
        Resource sampleImageResource = mosaicDirectory.get(band + Utils.SAMPLE_IMAGE_NAME);
        Utils.storeSampleImage(sampleImageResource.file(), imageLayout.getSampleModel(null),
                imageLayout.getColorModel(null));
    }

    // this is ridicolous, but for the moment, multi-crs mosaics won't work if there
    // is no indexer.properties around, even if no collection is actually done
    buildIndexer(collection, mosaicDirectory);

    // mosaic datastore connection
    createDataStoreProperties(collection, mosaicDirectory);

    // the mosaic datastore itself
    CatalogBuilder cb = new CatalogBuilder(catalog);
    CoverageStoreInfo mosaicStoreInfo = createMosaicStore(cb, collection, layerConfiguration, relativePath);

    // and finally the layer, with a coverage view associated to it
    List<CoverageBand> coverageBands = buildCoverageBands(layerConfiguration);
    final String coverageName = layerConfiguration.getLayer();
    final CoverageView coverageView = new CoverageView(coverageName, coverageBands);
    CoverageInfo coverageInfo = coverageView.createCoverageInfo(coverageName, mosaicStoreInfo, cb);
    timeEnableResource(coverageInfo);
    final LayerInfo layerInfo = cb.buildLayer(coverageInfo);

    catalog.add(coverageInfo);
    catalog.add(layerInfo);

    // configure the style if needed
    createStyle(layerConfiguration, layerInfo);
}

From source file:org.geotools.gce.imagemosaic.GranuleDescriptor.java

private void init(final BoundingBox granuleBBOX, final URL granuleUrl, final ImageReaderSpi suggestedSPI,
        final MultiLevelROI roiProvider, final boolean heterogeneousGranules,
        final boolean handleArtifactsFiltering, final Hints hints) {
    this.granuleBBOX = ReferencedEnvelope.reference(granuleBBOX);
    this.granuleUrl = granuleUrl;
    this.roiProvider = roiProvider;
    this.handleArtifactsFiltering = handleArtifactsFiltering;
    filterMe = handleArtifactsFiltering && roiProvider != null;

    // create the base grid to world transformation
    ImageInputStream inStream = null;
    ImageReader reader = null;
    try {// ww  w  .j a  va 2  s . c o  m
        //
        //get info about the raster we have to read
        //

        // get a stream
        if (cachedStreamSPI == null) {
            cachedStreamSPI = ImageIOExt.getImageInputStreamSPI(granuleUrl, true);
            if (cachedStreamSPI == null) {
                final File file = DataUtilities.urlToFile(granuleUrl);
                if (file != null) {
                    if (LOGGER.isLoggable(Level.WARNING)) {
                        LOGGER.log(Level.WARNING, Utils.getFileInfo(file));
                    }
                }
                throw new IllegalArgumentException(
                        "Unable to get an input stream for the provided granule " + granuleUrl.toString());
            }
        }
        assert cachedStreamSPI != null : "no cachedStreamSPI available!";
        inStream = cachedStreamSPI.createInputStreamInstance(granuleUrl, ImageIO.getUseCache(),
                ImageIO.getCacheDirectory());
        if (inStream == null) {
            final File file = DataUtilities.urlToFile(granuleUrl);
            if (file != null) {
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.log(Level.WARNING, Utils.getFileInfo(file));
                }
            }
            throw new IllegalArgumentException(
                    "Unable to get an input stream for the provided file " + granuleUrl.toString());
        }

        // get a reader and try to cache the suggested SPI first
        if (cachedReaderSPI == null) {
            inStream.mark();
            if (suggestedSPI != null && suggestedSPI.canDecodeInput(inStream)) {
                cachedReaderSPI = suggestedSPI;
                inStream.reset();
            } else {
                inStream.mark();
                reader = ImageIOExt.getImageioReader(inStream);
                if (reader != null)
                    cachedReaderSPI = reader.getOriginatingProvider();
                inStream.reset();
            }

        }
        if (reader == null) {
            if (cachedReaderSPI == null) {
                throw new IllegalArgumentException(
                        "Unable to get a ReaderSPI for the provided input: " + granuleUrl.toString());
            }
            reader = cachedReaderSPI.createReaderInstance();
        }

        if (reader == null)
            throw new IllegalArgumentException(
                    "Unable to get an ImageReader for the provided file " + granuleUrl.toString());
        boolean ignoreMetadata = customizeReaderInitialization(reader, hints);
        reader.setInput(inStream, false, ignoreMetadata);
        //get selected level and base level dimensions
        final Rectangle originalDimension = Utils.getDimension(0, reader);

        // build the g2W for this tile, in principle we should get it
        // somehow from the tile itself or from the index, but at the moment
        // we do not have such info, hence we assume that it is a simple
        // scale and translate
        this.geMapper = new GridToEnvelopeMapper(new GridEnvelope2D(originalDimension), granuleBBOX);
        geMapper.setPixelAnchor(PixelInCell.CELL_CENTER);//this is the default behavior but it is nice to write it down anyway
        this.baseGridToWorld = geMapper.createAffineTransform();

        // add the base level
        this.granuleLevels.put(Integer.valueOf(0),
                new GranuleOverviewLevelDescriptor(1, 1, originalDimension.width, originalDimension.height));

        ////////////////////// Setting overviewController ///////////////////////
        if (heterogeneousGranules) {
            // //
            //
            // Right now we are setting up overviewsController by assuming that
            // overviews are internal images as happens in TIFF images
            // We can improve this by leveraging on coverageReaders  
            //
            // //

            // Getting the first level descriptor
            final GranuleOverviewLevelDescriptor baseOverviewLevelDescriptor = granuleLevels.get(0);

            // Variables initialization
            final int numberOfOvervies = reader.getNumImages(true) - 1;
            final AffineTransform2D baseG2W = baseOverviewLevelDescriptor.getGridToWorldTransform();
            final int width = baseOverviewLevelDescriptor.getWidth();
            final int height = baseOverviewLevelDescriptor.getHeight();
            final double resX = AffineTransform2D.getScaleX0(baseG2W);
            final double resY = AffineTransform2D.getScaleY0(baseG2W);
            final double[] highestRes = new double[] { resX, resY };
            final double[][] overviewsResolution = new double[numberOfOvervies][2];

            // Populating overviews and initializing overviewsController
            for (int i = 0; i < numberOfOvervies; i++) {
                overviewsResolution[i][0] = (highestRes[0] * width) / reader.getWidth(i + 1);
                overviewsResolution[i][1] = (highestRes[1] * height) / reader.getHeight(i + 1);
            }
            overviewsController = new OverviewsController(highestRes, numberOfOvervies, overviewsResolution);
        }
        //////////////////////////////////////////////////////////////////////////

        if (hints != null && hints.containsKey(Utils.CHECK_AUXILIARY_METADATA)) {
            boolean checkAuxiliaryMetadata = (Boolean) hints.get(Utils.CHECK_AUXILIARY_METADATA);
            if (checkAuxiliaryMetadata) {
                checkPamDataset();
            }
        }

    } catch (IllegalStateException e) {
        throw new IllegalArgumentException(e);

    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } finally {
        // close/dispose stream and readers
        try {
            if (inStream != null) {
                inStream.close();
            }
        } catch (Throwable e) {
            throw new IllegalArgumentException(e);
        } finally {
            if (reader != null) {
                reader.dispose();
            }
        }
    }
}

From source file:org.geotools.gce.imagemosaic.GranuleDescriptor.java

/**
* Load a specified a raster as a portion of the granule describe by this {@link GranuleDescriptor}.
* 
* @param imageReadParameters the {@link ImageReadParam} to use for reading.
* @param index the index to use for the {@link ImageReader}.
* @param cropBBox the bbox to use for cropping. 
* @param mosaicWorldToGrid the cropping grid to world transform.
* @param request the incoming request to satisfy.
* @param hints {@link Hints} to be used for creating this raster.
* @return a specified a raster as a portion of the granule describe by this {@link GranuleDescriptor}.
* @throws IOException in case an error occurs.
*//*from w ww  . j av  a  2s.c om*/
public GranuleLoadingResult loadRaster(final ImageReadParam imageReadParameters, final int index,
        final ReferencedEnvelope cropBBox, final MathTransform2D mosaicWorldToGrid,
        final RasterLayerRequest request, final Hints hints) throws IOException {

    if (LOGGER.isLoggable(java.util.logging.Level.FINER)) {
        final String name = Thread.currentThread().getName();
        LOGGER.finer("Thread:" + name + " Loading raster data for granuleDescriptor " + this.toString());
    }
    ImageReadParam readParameters = null;
    int imageIndex;
    final boolean useFootprint = roiProvider != null
            && request.getFootprintBehavior() != FootprintBehavior.None;
    Geometry inclusionGeometry = useFootprint ? roiProvider.getFootprint() : null;
    final ReferencedEnvelope bbox = useFootprint
            ? new ReferencedEnvelope(granuleBBOX.intersection(inclusionGeometry.getEnvelopeInternal()),
                    granuleBBOX.getCoordinateReferenceSystem())
            : granuleBBOX;
    boolean doFiltering = false;
    if (filterMe && useFootprint) {
        doFiltering = Utils.areaIsDifferent(inclusionGeometry, baseGridToWorld, granuleBBOX);
    }

    // intersection of this tile bound with the current crop bbox
    final ReferencedEnvelope intersection = new ReferencedEnvelope(bbox.intersection(cropBBox),
            cropBBox.getCoordinateReferenceSystem());
    if (intersection.isEmpty()) {
        if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
            LOGGER.fine(new StringBuilder("Got empty intersection for granule ").append(this.toString())
                    .append(" with request ").append(request.toString())
                    .append(" Resulting in no granule loaded: Empty result").toString());
        }
        return null;
    }

    // check if the requested bbox intersects or overlaps the requested area 
    if (useFootprint && inclusionGeometry != null && !JTS.toGeometry(cropBBox).intersects(inclusionGeometry)) {
        if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
            LOGGER.fine(new StringBuilder("Got empty intersection for granule ").append(this.toString())
                    .append(" with request ").append(request.toString())
                    .append(" Resulting in no granule loaded: Empty result").toString());
        }
        return null;
    }

    ImageInputStream inStream = null;
    ImageReader reader = null;
    try {
        //
        //get info about the raster we have to read
        //

        // get a stream
        assert cachedStreamSPI != null : "no cachedStreamSPI available!";
        inStream = cachedStreamSPI.createInputStreamInstance(granuleUrl, ImageIO.getUseCache(),
                ImageIO.getCacheDirectory());
        if (inStream == null)
            return null;

        // get a reader and try to cache the relevant SPI
        if (cachedReaderSPI == null) {
            reader = ImageIOExt.getImageioReader(inStream);
            if (reader != null)
                cachedReaderSPI = reader.getOriginatingProvider();
        } else
            reader = cachedReaderSPI.createReaderInstance();
        if (reader == null) {
            if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
                LOGGER.warning(new StringBuilder("Unable to get s reader for granuleDescriptor ")
                        .append(this.toString()).append(" with request ").append(request.toString())
                        .append(" Resulting in no granule loaded: Empty result").toString());
            }
            return null;
        }
        // set input
        customizeReaderInitialization(reader, hints);
        reader.setInput(inStream);

        // Checking for heterogeneous granules
        if (request.isHeterogeneousGranules()) {
            // create read parameters
            readParameters = new ImageReadParam();

            //override the overviews controller for the base layer
            imageIndex = ReadParamsController.setReadParams(
                    request.spatialRequestHelper.getRequestedResolution(), request.getOverviewPolicy(),
                    request.getDecimationPolicy(), readParameters, request.rasterManager, overviewsController);
        } else {
            imageIndex = index;
            readParameters = imageReadParameters;
        }

        //get selected level and base level dimensions
        final GranuleOverviewLevelDescriptor selectedlevel = getLevel(imageIndex, reader);

        // now create the crop grid to world which can be used to decide
        // which source area we need to crop in the selected level taking
        // into account the scale factors imposed by the selection of this
        // level together with the base level grid to world transformation
        AffineTransform2D cropWorldToGrid = new AffineTransform2D(selectedlevel.gridToWorldTransformCorner);
        cropWorldToGrid = (AffineTransform2D) cropWorldToGrid.inverse();
        // computing the crop source area which lives into the
        // selected level raster space, NOTICE that at the end we need to
        // take into account the fact that we might also decimate therefore
        // we cannot just use the crop grid to world but we need to correct
        // it.
        final Rectangle sourceArea = CRS.transform(cropWorldToGrid, intersection).toRectangle2D().getBounds();
        //gutter
        if (selectedlevel.baseToLevelTransform.isIdentity()) {
            sourceArea.grow(2, 2);
        }
        XRectangle2D.intersect(sourceArea, selectedlevel.rasterDimensions, sourceArea);//make sure roundings don't bother us
        // is it empty??
        if (sourceArea.isEmpty()) {
            if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
                LOGGER.fine("Got empty area for granuleDescriptor " + this.toString() + " with request "
                        + request.toString() + " Resulting in no granule loaded: Empty result");

            }
            return null;

        } else if (LOGGER.isLoggable(java.util.logging.Level.FINER)) {
            LOGGER.finer("Loading level " + imageIndex + " with source region: " + sourceArea + " subsampling: "
                    + readParameters.getSourceXSubsampling() + "," + readParameters.getSourceYSubsampling()
                    + " for granule:" + granuleUrl);
        }

        // Setting subsampling 
        int newSubSamplingFactor = 0;
        final String pluginName = cachedReaderSPI.getPluginClassName();
        if (pluginName != null && pluginName.equals(ImageUtilities.DIRECT_KAKADU_PLUGIN)) {
            final int ssx = readParameters.getSourceXSubsampling();
            final int ssy = readParameters.getSourceYSubsampling();
            newSubSamplingFactor = ImageIOUtilities.getSubSamplingFactor2(ssx, ssy);
            if (newSubSamplingFactor != 0) {
                if (newSubSamplingFactor > maxDecimationFactor && maxDecimationFactor != -1) {
                    newSubSamplingFactor = maxDecimationFactor;
                }
                readParameters.setSourceSubsampling(newSubSamplingFactor, newSubSamplingFactor, 0, 0);
            }
        }

        // set the source region
        readParameters.setSourceRegion(sourceArea);
        RenderedImage raster;
        try {
            // read
            raster = request.getReadType().read(readParameters, imageIndex, granuleUrl,
                    selectedlevel.rasterDimensions, reader, hints, false);

        } catch (Throwable e) {
            if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
                LOGGER.log(java.util.logging.Level.FINE,
                        "Unable to load raster for granuleDescriptor " + this.toString() + " with request "
                                + request.toString() + " Resulting in no granule loaded: Empty result",
                        e);
            }
            return null;
        }

        // use fixed source area
        sourceArea.setRect(readParameters.getSourceRegion());

        //
        // setting new coefficients to define a new affineTransformation
        // to be applied to the grid to world transformation
        // -----------------------------------------------------------------------------------
        //
        // With respect to the original envelope, the obtained planarImage
        // needs to be rescaled. The scaling factors are computed as the
        // ratio between the cropped source region sizes and the read
        // image sizes.
        //
        // place it in the mosaic using the coords created above;
        double decimationScaleX = ((1.0 * sourceArea.width) / raster.getWidth());
        double decimationScaleY = ((1.0 * sourceArea.height) / raster.getHeight());
        final AffineTransform decimationScaleTranform = XAffineTransform.getScaleInstance(decimationScaleX,
                decimationScaleY);

        // keep into account translation  to work into the selected level raster space
        final AffineTransform afterDecimationTranslateTranform = XAffineTransform
                .getTranslateInstance(sourceArea.x, sourceArea.y);

        // now we need to go back to the base level raster space
        final AffineTransform backToBaseLevelScaleTransform = selectedlevel.baseToLevelTransform;

        // now create the overall transform
        final AffineTransform finalRaster2Model = new AffineTransform(baseGridToWorld);
        finalRaster2Model.concatenate(CoverageUtilities.CENTER_TO_CORNER);

        if (!XAffineTransform.isIdentity(backToBaseLevelScaleTransform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(backToBaseLevelScaleTransform);
        if (!XAffineTransform.isIdentity(afterDecimationTranslateTranform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(afterDecimationTranslateTranform);
        if (!XAffineTransform.isIdentity(decimationScaleTranform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(decimationScaleTranform);

        // adjust roi
        if (useFootprint) {

            ROIGeometry transformed;
            try {
                transformed = roiProvider.getTransformedROI(finalRaster2Model.createInverse());
                if (transformed.getAsGeometry().isEmpty()) {
                    // inset might have killed the geometry fully
                    return null;
                }

                PlanarImage pi = PlanarImage.wrapRenderedImage(raster);
                if (!transformed.intersects(pi.getBounds())) {
                    return null;
                }
                pi.setProperty("ROI", transformed);
                raster = pi;

            } catch (NoninvertibleTransformException e) {
                if (LOGGER.isLoggable(java.util.logging.Level.INFO))
                    LOGGER.info("Unable to create a granuleDescriptor " + this.toString()
                            + " due to a problem when managing the ROI");
                return null;
            }

        }
        // keep into account translation factors to place this tile
        finalRaster2Model.preConcatenate((AffineTransform) mosaicWorldToGrid);
        final Interpolation interpolation = request.getInterpolation();

        //paranoiac check to avoid that JAI freaks out when computing its internal layouT on images that are too small
        Rectangle2D finalLayout = ImageUtilities.layoutHelper(raster, (float) finalRaster2Model.getScaleX(),
                (float) finalRaster2Model.getScaleY(), (float) finalRaster2Model.getTranslateX(),
                (float) finalRaster2Model.getTranslateY(), interpolation);
        if (finalLayout.isEmpty()) {
            if (LOGGER.isLoggable(java.util.logging.Level.INFO))
                LOGGER.info("Unable to create a granuleDescriptor " + this.toString()
                        + " due to jai scale bug creating a null source area");
            return null;
        }

        // apply the affine transform  conserving indexed color model
        final RenderingHints localHints = new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL,
                interpolation instanceof InterpolationNearest ? Boolean.FALSE : Boolean.TRUE);
        if (XAffineTransform.isIdentity(finalRaster2Model, Utils.AFFINE_IDENTITY_EPS)) {
            return new GranuleLoadingResult(raster, null, granuleUrl, doFiltering, pamDataset);
        } else {
            //
            // In case we are asked to use certain tile dimensions we tile
            // also at this stage in case the read type is Direct since
            // buffered images comes up untiled and this can affect the
            // performances of the subsequent affine operation.
            //
            final Dimension tileDimensions = request.getTileDimensions();
            if (tileDimensions != null && request.getReadType().equals(ReadType.DIRECT_READ)) {
                final ImageLayout layout = new ImageLayout();
                layout.setTileHeight(tileDimensions.width).setTileWidth(tileDimensions.height);
                localHints.add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout));
            } else {
                if (hints != null && hints.containsKey(JAI.KEY_IMAGE_LAYOUT)) {
                    final Object layout = hints.get(JAI.KEY_IMAGE_LAYOUT);
                    if (layout != null && layout instanceof ImageLayout) {
                        localHints
                                .add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, ((ImageLayout) layout).clone()));
                    }
                }
            }
            if (hints != null && hints.containsKey(JAI.KEY_TILE_CACHE)) {
                final Object cache = hints.get(JAI.KEY_TILE_CACHE);
                if (cache != null && cache instanceof TileCache)
                    localHints.add(new RenderingHints(JAI.KEY_TILE_CACHE, (TileCache) cache));
            }
            if (hints != null && hints.containsKey(JAI.KEY_TILE_SCHEDULER)) {
                final Object scheduler = hints.get(JAI.KEY_TILE_SCHEDULER);
                if (scheduler != null && scheduler instanceof TileScheduler)
                    localHints.add(new RenderingHints(JAI.KEY_TILE_SCHEDULER, (TileScheduler) scheduler));
            }
            boolean addBorderExtender = true;
            if (hints != null && hints.containsKey(JAI.KEY_BORDER_EXTENDER)) {
                final Object extender = hints.get(JAI.KEY_BORDER_EXTENDER);
                if (extender != null && extender instanceof BorderExtender) {
                    localHints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, (BorderExtender) extender));
                    addBorderExtender = false;
                }
            }
            // BORDER extender
            if (addBorderExtender) {
                localHints.add(ImageUtilities.BORDER_EXTENDER_HINTS);
            }

            ImageWorker iw = new ImageWorker(raster);
            iw.setRenderingHints(localHints);
            iw.affine(finalRaster2Model, interpolation, request.getBackgroundValues());
            return new GranuleLoadingResult(iw.getRenderedImage(), null, granuleUrl, doFiltering, pamDataset);
        }

    } catch (IllegalStateException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;
    } catch (org.opengis.referencing.operation.NoninvertibleTransformException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;
    } catch (TransformException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;

    } finally {
        try {
            if (request.getReadType() != ReadType.JAI_IMAGEREAD && inStream != null) {
                inStream.close();
            }
        } finally {
            if (request.getReadType() != ReadType.JAI_IMAGEREAD && reader != null) {
                reader.dispose();
            }
        }
    }
}

From source file:org.geotools.gce.imagemosaic.GranuleDescriptor.java

GranuleOverviewLevelDescriptor getLevel(final int index) {

    //load level/*from   w w w .j a va  2 s.c o m*/
    // create the base grid to world transformation
    ImageInputStream inStream = null;
    ImageReader reader = null;
    try {

        // get a stream
        assert cachedStreamSPI != null : "no cachedStreamSPI available!";
        inStream = cachedStreamSPI.createInputStreamInstance(granuleUrl, ImageIO.getUseCache(),
                ImageIO.getCacheDirectory());
        if (inStream == null)
            throw new IllegalArgumentException("Unable to create an inputstream for the granuleurl:"
                    + (granuleUrl != null ? granuleUrl : "null"));

        // get a reader and try to cache the relevant SPI
        if (cachedReaderSPI == null) {
            reader = ImageIOExt.getImageioReader(inStream);
            if (reader != null)
                cachedReaderSPI = reader.getOriginatingProvider();
        } else
            reader = cachedReaderSPI.createReaderInstance();
        if (reader == null)
            throw new IllegalArgumentException(
                    "Unable to get an ImageReader for the provided file " + granuleUrl.toString());
        final boolean ignoreMetadata = customizeReaderInitialization(reader, null);
        reader.setInput(inStream, false, ignoreMetadata);

        // call internal method which will close everything
        return getLevel(index, reader);

    } catch (IllegalStateException e) {

        // clean up
        try {
            if (inStream != null)
                inStream.close();
        } catch (Throwable ee) {

        } finally {
            if (reader != null)
                reader.dispose();
        }

        throw new IllegalArgumentException(e);

    } catch (IOException e) {

        // clean up
        try {
            if (inStream != null)
                inStream.close();
        } catch (Throwable ee) {
        } finally {
            if (reader != null)
                reader.dispose();
        }

        throw new IllegalArgumentException(e);
    }
}

From source file:pl.edu.icm.visnow.system.main.VisNow.java

private static void startupInfo() {
    LOGGER.info("");
    LOGGER.info("");
    LOGGER.info("-------- VisNow startup info --------");

    if (debug) {//from   w  w  w.  j  a  v a 2  s . com
        RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
        List<String> aList = RuntimemxBean.getInputArguments();
        LOGGER.info(" * JVM startup flags:");
        for (int i = 0; i < aList.size(); i++) {
            LOGGER.info("    " + aList.get(i));
        }
        LOGGER.info("");
        Set<String> p = System.getProperties().stringPropertyNames();
        Iterator<String> ip = p.iterator();
        LOGGER.info(" * System properties:");
        String key;
        while (ip.hasNext()) {
            key = ip.next();
            LOGGER.info("    " + key + " = " + System.getProperty(key));
        }
        LOGGER.info("");

        Map<String, String> env = System.getenv();
        Set<String> envKeys = env.keySet();
        Iterator<String> envKeysI = envKeys.iterator();

        LOGGER.info(" * Environment variables:");
        while (envKeysI.hasNext()) {
            key = envKeysI.next();
            LOGGER.info("    " + key + " = " + env.get(key));
        }
        LOGGER.info("  ");
        LOGGER.info("------ Java Advanced Imaging info -------");
        String[] formats = ImageIO.getReaderFormatNames();
        String readerDescription, readerVendorName, readerVersion;
        ImageReader reader;
        ImageReaderSpi spi;
        for (int i = 0; i < formats.length; i++) {
            Iterator<ImageReader> tmpReaders = ImageIO.getImageReadersByFormatName(formats[i]);
            while (tmpReaders.hasNext()) {
                reader = tmpReaders.next();
                spi = reader.getOriginatingProvider();
                readerDescription = spi.getDescription(Locale.US);
                readerVendorName = spi.getVendorName();
                readerVersion = spi.getVersion();
                LOGGER.info("    " + formats[i] + ": " + readerDescription + " " + readerVendorName + " "
                        + readerVersion);
            }
        }
        LOGGER.info("-----------------------------------------");

    } else {

        LOGGER.info(" * System properties:");
        LOGGER.info("    java.runtime.name = " + System.getProperty("java.runtime.name"));
        LOGGER.info("    java.vm.version = " + System.getProperty("java.vm.version"));
        LOGGER.info("    java.vm.vendor = " + System.getProperty("java.vm.vendor"));
        LOGGER.info("    java.vm.name = " + System.getProperty("java.vm.name"));
        LOGGER.info("    java.specification.version = " + System.getProperty("java.specification.version"));
        LOGGER.info("    java.runtime.version = " + System.getProperty("java.runtime.version"));
        LOGGER.info("    os.arch = " + System.getProperty("os.arch"));
        LOGGER.info("    os.name = " + System.getProperty("os.name"));
        LOGGER.info("    os.version = " + System.getProperty("os.version"));
        LOGGER.info("    java.library.path = " + System.getProperty("java.library.path"));
        LOGGER.info("    java.class.path = " + System.getProperty("java.class.path"));
        LOGGER.info("    java.ext.dirs = " + System.getProperty("java.ext.dirs"));
        LOGGER.info("");
        LOGGER.info(" * Environment variables:");
        LOGGER.info("    JAVA_HOME = " + System.getenv("JAVA_HOME"));
        LOGGER.info("    PATH = " + System.getenv("PATH"));
        LOGGER.info("    LD_LIBRARY_PATH = " + System.getenv("LD_LIBRARY_PATH"));
        LOGGER.info("    CLASSPATH = " + System.getenv("CLASSPATH"));
        LOGGER.info("-------------------------------------");

    }
    LOGGER.info("");
    LOGGER.info("");

}