Beispiel #1
0
  @Override
  protected void onSetUp(SystemTestData testData) throws Exception {
    super.onSetUp(testData);

    // we need to add a wms store
    CatalogBuilder cb = new CatalogBuilder(catalog);
    cb.setWorkspace(catalog.getWorkspaceByName("sf"));
    WMSStoreInfo wms = cb.buildWMSStore("demo");
    wms.setCapabilitiesURL("http://demo.opengeo.org/geoserver/wms?");
    catalog.add(wms);

    // and a wms layer as well (cannot use the builder, would turn this test into an online one
    addStatesWmsLayer();
  }
  @Override
  protected void setUpInternal(SystemTestData data) throws Exception {
    // run all the tests against a store that can do native paging (h2) and one that
    // can't (property)
    Catalog cat = getCatalog();
    DataStoreInfo ds = cat.getFactory().createDataStore();
    ds.setName("foo");
    ds.setWorkspace(cat.getDefaultWorkspace());

    Map params = ds.getConnectionParameters();
    params.put("dbtype", "h2");
    params.put("database", getTestData().getDataDirectoryRoot().getAbsolutePath());
    cat.add(ds);

    FeatureSource fs1 = getFeatureSource(SystemTestData.FIFTEEN);
    FeatureSource fs2 = getFeatureSource(SystemTestData.SEVEN);

    DataStore store = (DataStore) ds.getDataStore(null);
    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();

    tb.init((SimpleFeatureType) fs1.getSchema());
    tb.add("num", Integer.class);
    tb.remove("boundedBy");
    store.createSchema(tb.buildFeatureType());

    tb.init((SimpleFeatureType) fs2.getSchema());
    tb.add("num", Integer.class);
    tb.remove("boundedBy");
    store.createSchema(tb.buildFeatureType());

    CatalogBuilder cb = new CatalogBuilder(cat);
    cb.setStore(ds);

    FeatureStore fs = (FeatureStore) store.getFeatureSource("Fifteen");
    addFeatures(fs, fs1.getFeatures());

    FeatureTypeInfo ft = cb.buildFeatureType(fs);
    cat.add(ft);

    fs = (FeatureStore) store.getFeatureSource("Seven");
    addFeatures(fs, fs2.getFeatures());

    ft = cb.buildFeatureType(fs);
    cat.add(ft);
  }
  @org.junit.Test
  public void testCascadingWMS() throws Exception {
    Catalog catalog = getCatalog();

    CatalogBuilder builder = new CatalogBuilder(catalog);
    WMSStoreInfo wmsStore = builder.buildWMSStore("cascadeWMS");
    wmsStore.setCapabilitiesURL(
        "http://wms.geonorge.no/skwms1/wms.toporaster2?service=WMS&version=1.1.1");
    catalog.add(wmsStore);

    builder.setStore(wmsStore);
    WMSLayerInfo wmsLayer = builder.buildWMSLayer("toporaster");
    catalog.add(wmsLayer);

    requiredParameters.put("LAYER", "toporaster");
    GetLegendGraphicRequest request =
        requestReader.read(new GetLegendGraphicRequest(), requiredParameters, requiredParameters);
    assertNotNull(request);
  }
  private void configureCoverageInfo(
      CatalogBuilder builder, CoverageStoreInfo storeInfo, GridCoverage2DReader reader)
      throws Exception, IOException {
    // coverage read params
    final Map customParameters = new HashMap();

    CoverageInfo cinfo = builder.buildCoverage(reader, customParameters);

    // get the coverage name
    String name = reader.getGridCoverageNames()[0];
    cinfo.setName(name);
    cinfo.setNativeCoverageName(name);

    // add the store
    getCatalog().add(cinfo);
  }
  public MockCatalogBuilder coverage(QName qName, String fileName, String srs, Class scope) {
    scope = scope != null ? scope : getClass();

    String cId = newId();
    final CoverageStoreInfo cs = coverageStores.peekLast();
    NamespaceInfo ns = namespaces.peekLast();

    final String name = qName.getLocalPart();
    File dir = new File(dataDirRoot, name);
    dir.mkdir();

    try {
      IOUtils.copy(scope.getResourceAsStream(fileName), new File(dir, fileName));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    // initialize the mock by actually building a real one first
    CatalogBuilder cb = new CatalogBuilder(new CatalogImpl());
    cb.setStore(cs);

    GridCoverage2DReader reader = cs.getFormat().getReader(cs.getURL());
    if (reader == null) {
      throw new RuntimeException("No reader for " + cs.getURL());
    }

    CoverageInfo real = null;
    try {
      real = cb.buildCoverage(reader, null);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    final CoverageInfo c = createNiceMock(CoverageInfo.class);
    coverages.add(c);
    final List<CoverageInfo> coverageList = coverages;

    if (srs == null) {
      srs = real.getSRS();
    }
    initResource(
        c,
        CoverageInfo.class,
        cId,
        name,
        cs,
        ns,
        srs,
        real.getProjectionPolicy(),
        real.getNativeBoundingBox(),
        real.getLatLonBoundingBox());

    expect(c.getDefaultInterpolationMethod())
        .andReturn(real.getDefaultInterpolationMethod())
        .anyTimes();
    expect(c.getDimensions()).andReturn(real.getDimensions()).anyTimes();
    expect(c.getGrid()).andReturn(real.getGrid()).anyTimes();

    expect(c.getInterpolationMethods()).andReturn(real.getInterpolationMethods()).anyTimes();
    expect(c.getRequestSRS()).andReturn(real.getRequestSRS()).anyTimes();
    expect(c.getResponseSRS()).andReturn(real.getResponseSRS()).anyTimes();

    try {
      expect(c.getGridCoverageReader(null, null)).andReturn(reader).anyTimes();
    } catch (IOException e) {
    }

    expect(catalog.getCoverageByName(or(eq(name), eq(ns.getPrefix() + ":" + name))))
        .andReturn(c)
        .anyTimes();
    expect(
            catalog.getCoverageByName(
                or(eq(new NameImpl(ns.getPrefix(), name)), eq(new NameImpl(ns.getURI(), name)))))
        .andReturn(c)
        .anyTimes();
    expect(catalog.getCoverageByName(ns, name)).andReturn(c).anyTimes();

    expect(catalog.getCoverageByName(ns.getPrefix(), name)).andReturn(c).anyTimes();
    // expect(catalog.getFeatureTypeByName(or(eq(ns.getPrefix()), eq(ns.getURI())), name))
    //    .andReturn(ft).anyTimes();

    // expect(catalog.getCoverageByStore(cs, name)).andReturn(c).anyTimes();
    expect(catalog.getCoveragesByStore(cs)).andReturn(coverageList).anyTimes();
    expect(catalog.getCoverageByCoverageStore(cs, name)).andReturn(c).anyTimes();

    c.accept((CatalogVisitor) anyObject());
    expectLastCall()
        .andAnswer(
            new VisitAnswer() {
              @Override
              protected void doVisit(CatalogVisitor visitor) {
                visitor.visit(c);
              }
            })
        .anyTimes();

    callback.onResource(name, c, cs, this);
    replay(c, createLayer(c, name, ns));
    return this;
  }
  @Test
  public void testHarvestExternalImageMosaic() throws Exception {
    // Check if an already existing directory called "mosaic" is present
    URL resource = getClass().getResource("test-data/mosaic");
    if (resource != null) {
      File oldDir = DataUtilities.urlToFile(resource);
      if (oldDir.exists()) {
        FileUtils.deleteDirectory(oldDir);
      }
    }
    // reading of the mosaic directory
    File mosaic = readMosaic();
    // Creation of the builder for building a new CoverageStore
    CatalogBuilder builder = new CatalogBuilder(getCatalog());
    // Definition of the workspace associated to the coverage
    WorkspaceInfo ws = getCatalog().getWorkspaceByName("gs");
    // Creation of a CoverageStore
    CoverageStoreInfo store = builder.buildCoverageStore("watertemp4");
    store.setURL(DataUtilities.fileToURL(mosaic).toExternalForm());
    store.setWorkspace(ws);
    ImageMosaicFormat imageMosaicFormat = new ImageMosaicFormat();
    store.setType((imageMosaicFormat.getName()));
    // Addition to the catalog
    getCatalog().add(store);
    builder.setStore(store);
    // Input reader used for reading the mosaic folder
    GridCoverage2DReader reader = null;
    // Reader used for checking if the mosaic has been configured correctly
    StructuredGridCoverage2DReader reader2 = null;

    try {
      // Selection of the reader to use for the mosaic
      reader = (GridCoverage2DReader) imageMosaicFormat.getReader(DataUtilities.fileToURL(mosaic));

      // configure the coverage
      configureCoverageInfo(builder, store, reader);

      // check the coverage is actually there
      CoverageStoreInfo storeInfo = getCatalog().getCoverageStoreByName("watertemp4");
      assertNotNull(storeInfo);
      CoverageInfo ci = getCatalog().getCoverageByName("mosaic");
      assertNotNull(ci);
      assertEquals(storeInfo, ci.getStore());

      // Harvesting of the Mosaic
      URL zipHarvest = getClass().getResource("test-data/harvesting.zip");
      // Extract a Byte array from the zip file
      InputStream is = null;
      byte[] bytes;
      try {
        is = zipHarvest.openStream();
        bytes = IOUtils.toByteArray(is);
      } finally {
        IOUtils.closeQuietly(is);
      }
      // Create the POST request
      MockHttpServletRequest request =
          createRequest("/rest/workspaces/gs/coveragestores/watertemp4/file.imagemosaic");
      request.setMethod("POST");
      request.setContentType("application/zip");
      request.setBodyContent(bytes);
      request.setHeader("Content-type", "application/zip");
      // Get The response
      MockHttpServletResponse response = dispatch(request);
      // Get the Mosaic Reader
      reader2 =
          (StructuredGridCoverage2DReader)
              storeInfo.getGridCoverageReader(null, GeoTools.getDefaultHints());
      // Test if all the TIME DOMAINS are present
      String[] metadataNames = reader2.getMetadataNames();
      assertNotNull(metadataNames);
      assertEquals("true", reader2.getMetadataValue("HAS_TIME_DOMAIN"));
      assertEquals(
          "2008-10-31T00:00:00.000Z,2008-11-01T00:00:00.000Z,2008-11-02T00:00:00.000Z",
          reader2.getMetadataValue(metadataNames[0]));
      // Removal of all the data associated to the mosaic
      reader2.delete(true);
    } finally {
      // Reader disposal
      if (reader != null) {
        try {
          reader.dispose();
        } catch (Throwable t) {
          // Does nothing
        }
      }
      if (reader2 != null) {
        try {
          reader2.dispose();
        } catch (Throwable t) {
          // Does nothing
        }
      }
    }
  }
  @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace")
  public String execute(
      @DescribeParameter(name = "features", min = 0, description = "Input feature collection")
          SimpleFeatureCollection features,
      @DescribeParameter(name = "coverage", min = 0, description = "Input raster")
          GridCoverage2D coverage,
      @DescribeParameter(
              name = "workspace",
              min = 0,
              description = "Target workspace (default is the system default)")
          String workspace,
      @DescribeParameter(
              name = "store",
              min = 0,
              description = "Target store (default is the workspace default)")
          String store,
      @DescribeParameter(
              name = "name",
              min = 0,
              description =
                  "Name of the new featuretype/coverage (default is the name of the features in the collection)")
          String name,
      @DescribeParameter(
              name = "srs",
              min = 0,
              description =
                  "Target coordinate reference system (default is based on source when possible)")
          CoordinateReferenceSystem srs,
      @DescribeParameter(
              name = "srsHandling",
              min = 0,
              description =
                  "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)")
          ProjectionPolicy srsHandling,
      @DescribeParameter(
              name = "styleName",
              min = 0,
              description =
                  "Name of the style to be associated with the layer (default is a standard geometry-specific style)")
          String styleName)
      throws ProcessException {

    // first off, decide what is the target store
    WorkspaceInfo ws;
    if (workspace != null) {
      ws = catalog.getWorkspaceByName(workspace);
      if (ws == null) {
        throw new ProcessException("Could not find workspace " + workspace);
      }
    } else {
      ws = catalog.getDefaultWorkspace();
      if (ws == null) {
        throw new ProcessException("The catalog is empty, could not find a default workspace");
      }
    }

    // create a builder to help build catalog objects
    CatalogBuilder cb = new CatalogBuilder(catalog);
    cb.setWorkspace(ws);

    // ok, find the target store
    StoreInfo storeInfo = null;
    boolean add = false;
    if (store != null) {
      if (features != null) {
        storeInfo = catalog.getDataStoreByName(ws.getName(), store);
      } else if (coverage != null) {
        storeInfo = catalog.getCoverageStoreByName(ws.getName(), store);
      }
      if (storeInfo == null) {
        throw new ProcessException("Could not find store " + store + " in workspace " + workspace);
        // TODO: support store creation
      }
    } else if (features != null) {
      storeInfo = catalog.getDefaultDataStore(ws);
      if (storeInfo == null) {
        throw new ProcessException("Could not find a default store in workspace " + ws.getName());
      }
    } else if (coverage != null) {
      // create a new coverage store
      LOGGER.info(
          "Auto-configuring coverage store: "
              + (name != null ? name : coverage.getName().toString()));

      storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString()));
      add = true;
      store = (name != null ? name : coverage.getName().toString());

      if (storeInfo == null) {
        throw new ProcessException("Could not find a default store in workspace " + ws.getName());
      }
    }

    // check the target style if any
    StyleInfo targetStyle = null;
    if (styleName != null) {
      targetStyle = catalog.getStyleByName(styleName);
      if (targetStyle == null) {
        throw new ProcessException("Could not find style " + styleName);
      }
    }

    if (features != null) {
      // check if the target layer and the target feature type are not
      // already there (this is a half-assed attempt as we don't have
      // an API telling us how the feature type name will be changed
      // by DataStore.createSchema(...), but better than fully importing
      // the data into the target store to find out we cannot create the layer...)
      String tentativeTargetName = null;
      if (name != null) {
        tentativeTargetName = ws.getName() + ":" + name;
      } else {
        tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName();
      }
      if (catalog.getLayer(tentativeTargetName) != null) {
        throw new ProcessException("Target layer " + tentativeTargetName + " already exists");
      }

      // check the target crs
      String targetSRSCode = null;
      if (srs != null) {
        try {
          Integer code = CRS.lookupEpsgCode(srs, true);
          if (code == null) {
            throw new WPSException("Could not find a EPSG code for " + srs);
          }
          targetSRSCode = "EPSG:" + code;
        } catch (Exception e) {
          throw new ProcessException("Could not lookup the EPSG code for the provided srs", e);
        }
      } else {
        // check we can extract a code from the original data
        GeometryDescriptor gd = features.getSchema().getGeometryDescriptor();
        if (gd == null) {
          // data is geometryless, we need a fake SRS
          targetSRSCode = "EPSG:4326";
          srsHandling = ProjectionPolicy.FORCE_DECLARED;
        } else {
          CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem();
          if (nativeCrs == null) {
            throw new ProcessException(
                "The original data has no native CRS, " + "you need to specify the srs parameter");
          } else {
            try {
              Integer code = CRS.lookupEpsgCode(nativeCrs, true);
              if (code == null) {
                throw new ProcessException(
                    "Could not find an EPSG code for data "
                        + "native spatial reference system: "
                        + nativeCrs);
              } else {
                targetSRSCode = "EPSG:" + code;
              }
            } catch (Exception e) {
              throw new ProcessException(
                  "Failed to loookup an official EPSG code for "
                      + "the source data native "
                      + "spatial reference system",
                  e);
            }
          }
        }
      }

      // import the data into the target store
      SimpleFeatureType targetType;
      try {
        targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo);
      } catch (IOException e) {
        throw new ProcessException("Failed to import data into the target store", e);
      }

      // now import the newly created layer into GeoServer
      try {
        cb.setStore(storeInfo);

        // build the typeInfo and set CRS if necessary
        FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName());
        if (targetSRSCode != null) {
          typeInfo.setSRS(targetSRSCode);
        }
        if (srsHandling != null) {
          typeInfo.setProjectionPolicy(srsHandling);
        }
        // compute the bounds
        cb.setupBounds(typeInfo);

        // build the layer and set a style
        LayerInfo layerInfo = cb.buildLayer(typeInfo);
        if (targetStyle != null) {
          layerInfo.setDefaultStyle(targetStyle);
        }

        catalog.add(typeInfo);
        catalog.add(layerInfo);

        return layerInfo.prefixedName();
      } catch (Exception e) {
        throw new ProcessException("Failed to complete the import inside the GeoServer catalog", e);
      }
    } else if (coverage != null) {
      try {
        final File directory =
            catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store);
        final File file = File.createTempFile(store, ".tif", directory);
        ((CoverageStoreInfo) storeInfo).setURL(file.toURL().toExternalForm());
        ((CoverageStoreInfo) storeInfo).setType("GeoTIFF");

        // check the target crs
        CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem();
        String targetSRSCode = null;
        if (srs != null) {
          try {
            Integer code = CRS.lookupEpsgCode(srs, true);
            if (code == null) {
              throw new WPSException("Could not find a EPSG code for " + srs);
            }
            targetSRSCode = "EPSG:" + code;
          } catch (Exception e) {
            throw new ProcessException("Could not lookup the EPSG code for the provided srs", e);
          }
        } else {
          // check we can extract a code from the original data
          if (cvCrs == null) {
            // data is geometryless, we need a fake SRS
            targetSRSCode = "EPSG:4326";
            srsHandling = ProjectionPolicy.FORCE_DECLARED;
            srs = DefaultGeographicCRS.WGS84;
          } else {
            CoordinateReferenceSystem nativeCrs = cvCrs;
            if (nativeCrs == null) {
              throw new ProcessException(
                  "The original data has no native CRS, "
                      + "you need to specify the srs parameter");
            } else {
              try {
                Integer code = CRS.lookupEpsgCode(nativeCrs, true);
                if (code == null) {
                  throw new ProcessException(
                      "Could not find an EPSG code for data "
                          + "native spatial reference system: "
                          + nativeCrs);
                } else {
                  targetSRSCode = "EPSG:" + code;
                  srs = CRS.decode(targetSRSCode, true);
                }
              } catch (Exception e) {
                throw new ProcessException(
                    "Failed to loookup an official EPSG code for "
                        + "the source data native "
                        + "spatial reference system",
                    e);
              }
            }
          }
        }

        MathTransform tx = CRS.findMathTransform(cvCrs, srs);

        if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) {
          coverage =
              WCSUtils.resample(
                  coverage,
                  cvCrs,
                  srs,
                  null,
                  Interpolation.getInstance(Interpolation.INTERP_NEAREST));
        }

        GeoTiffWriter writer = new GeoTiffWriter(file);

        // setting the write parameters for this geotiff
        final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters();
        params
            .parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString())
            .setValue(DEFAULT_WRITE_PARAMS);
        final GeneralParameterValue[] wps =
            (GeneralParameterValue[]) params.values().toArray(new GeneralParameterValue[1]);

        try {
          writer.write(coverage, wps);
        } finally {
          try {
            writer.dispose();
          } catch (Exception e) {
            // we tried, no need to fuss around this one
          }
        }

        // add or update the datastore info
        if (add) {
          catalog.add((CoverageStoreInfo) storeInfo);
        } else {
          catalog.save((CoverageStoreInfo) storeInfo);
        }

        cb.setStore((CoverageStoreInfo) storeInfo);

        AbstractGridCoverage2DReader reader = new GeoTiffReader(file);
        if (reader == null) {
          throw new ProcessException("Could not aquire reader for coverage.");
        }

        // coverage read params
        final Map customParameters = new HashMap();
        /*String useJAIImageReadParam = "USE_JAI_IMAGEREAD";
        if (useJAIImageReadParam != null) {
        	customParameters.put(AbstractGridFormat.USE_JAI_IMAGEREAD.getName().toString(), Boolean.valueOf(useJAIImageReadParam));
        }*/

        CoverageInfo cinfo = cb.buildCoverage(reader, customParameters);

        // check if the name of the coverage was specified
        if (name != null) {
          cinfo.setName(name);
        }

        if (!add) {
          // update the existing
          CoverageInfo existing =
              catalog.getCoverageByCoverageStore(
                  (CoverageStoreInfo) storeInfo,
                  name != null ? name : coverage.getName().toString());
          if (existing == null) {
            // grab the first if there is only one
            List<CoverageInfo> coverages =
                catalog.getCoveragesByCoverageStore((CoverageStoreInfo) storeInfo);
            if (coverages.size() == 1) {
              existing = coverages.get(0);
            }
            if (coverages.size() == 0) {
              // no coverages yet configured, change add flag and continue on
              add = true;
            } else {
              // multiple coverages, and one to configure not specified
              throw new ProcessException("Unable to determine coverage to configure.");
            }
          }

          if (existing != null) {
            cb.updateCoverage(existing, cinfo);
            catalog.save(existing);
            cinfo = existing;
          }
        }

        // do some post configuration, if srs is not known or unset, transform to 4326
        if ("UNKNOWN".equals(cinfo.getSRS())) {
          // CoordinateReferenceSystem sourceCRS =
          // cinfo.getBoundingBox().getCoordinateReferenceSystem();
          // CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326", true);
          // ReferencedEnvelope re = cinfo.getBoundingBox().transform(targetCRS, true);
          cinfo.setSRS("EPSG:4326");
          // cinfo.setCRS( targetCRS );
          // cinfo.setBoundingBox( re );
        }

        // add/save
        if (add) {
          catalog.add(cinfo);

          LayerInfo layerInfo = cb.buildLayer(cinfo);
          if (styleName != null && targetStyle != null) {
            layerInfo.setDefaultStyle(targetStyle);
          }
          // JD: commenting this out, these sorts of edits should be handled
          // with a second PUT request on the created coverage
          /*
          String styleName = form.getFirstValue("style");
          if ( styleName != null ) {
              StyleInfo style = catalog.getStyleByName( styleName );
              if ( style != null ) {
                  layerInfo.setDefaultStyle( style );
                  if ( !layerInfo.getStyles().contains( style ) ) {
                      layerInfo.getStyles().add( style );
                  }
              }
              else {
                  LOGGER.warning( "Client specified style '" + styleName + "'but no such style exists.");
              }
          }

          String path = form.getFirstValue( "path");
          if ( path != null ) {
              layerInfo.setPath( path );
          }
          */

          boolean valid = true;
          try {
            if (!catalog.validate(layerInfo, true).isEmpty()) {
              valid = false;
            }
          } catch (Exception e) {
            valid = false;
          }

          layerInfo.setEnabled(valid);
          catalog.add(layerInfo);

          return layerInfo.prefixedName();
        } else {
          catalog.save(cinfo);

          LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName());
          if (styleName != null && targetStyle != null) {
            layerInfo.setDefaultStyle(targetStyle);
          }

          return layerInfo.prefixedName();
        }

      } catch (MalformedURLException e) {
        throw new ProcessException("URL Error", e);
      } catch (IOException e) {
        throw new ProcessException("I/O Exception", e);
      } catch (Exception e) {
        e.printStackTrace();
        throw new ProcessException("Exception", e);
      }
    }

    return null;
  }
Beispiel #8
0
  /**
   * Adds a raster layer to the setup.
   *
   * <p>This method configures a raster layer with the name <code>qName.getLocalPart()</code>. A
   * coverage store is created (if it doesn't already exist) with the same name. The workspace of
   * the resulting store and layer is determined by <code>qName.getPrefix()</code>.
   *
   * <p>The <tt>filename</tt> parameter defines the raster file to be loaded from the classpath and
   * copied into the data directory. The <tt>scope</tt> is used as the class from which to load the
   * file from.
   *
   * <p>In the case of adding a zipped archive that contains multiple file the <tt>filename</tt>
   * paramter should have a ".zip" extension and the <tt>extension</tt> parameter must define the
   * extension of the main raster file. The parameter is not necessary and may be null if the
   * <tt>filename</tt> does not refer to a zip file.
   *
   * <p>The <tt>props</tt> parameter is used to define custom properties for the layer. See the
   * {@link LayerProperty} class for supported properties.
   *
   * @param qName The name of the raster layer.
   * @param filename The name of the file containing the raster, to be loaded from the classpath.
   * @param extension The file extension (without a ".") of the main raster file. This parameter my
   *     be <code>null</code> only if <tt>filename</tt> does not refer to a zip file.
   * @param props Custom properties to assign to the created raster layer.
   * @param scope The class from which to load the <tt>filename</tt> resource from.
   */
  public void addRasterLayer(
      QName qName,
      String filename,
      String extension,
      Map<LayerProperty, Object> props,
      Class scope,
      Catalog catalog)
      throws IOException {

    String prefix = qName.getPrefix();
    String name = qName.getLocalPart();

    // setup the data
    File dir = new File(data, name);
    dir.mkdirs();

    File file = new File(dir, filename);
    catalog.getResourceLoader().copyFromClassPath(filename, file, scope);

    String ext = FilenameUtils.getExtension(filename);
    if ("zip".equalsIgnoreCase(ext)) {

      // unpack the archive
      IOUtils.decompress(file, dir);

      // delete archive
      file.delete();

      if (extension == null) {
        // zip with no extension, we just the directory as the file
        file = dir;
      } else {
        // files may have been top level, or one directory level deep
        file = new File(dir, FilenameUtils.getBaseName(filename) + "." + extension);
        if (!file.exists()) {
          File file2 = new File(new File(dir, dir.getName()), file.getName());
          if (file2.exists()) {
            file = file2;
          }
        }
      }

      if (!file.exists()) {
        throw new FileNotFoundException(file.getPath());
      }
    }

    // load the format/reader
    AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(file);
    if (format == null) {
      throw new RuntimeException("No format for " + file.getCanonicalPath());
    }
    AbstractGridCoverage2DReader reader = null;
    try {
      reader = (AbstractGridCoverage2DReader) format.getReader(file);
      if (reader == null) {
        throw new RuntimeException(
            "No reader for " + file.getCanonicalPath() + " with format " + format.getName());
      }

      // configure workspace if it doesn;t already exist
      if (catalog.getWorkspaceByName(prefix) == null) {
        addWorkspace(prefix, qName.getNamespaceURI(), catalog);
      }
      // create the store
      CoverageStoreInfo store = catalog.getCoverageStoreByName(prefix, name);
      if (store == null) {
        store = catalog.getFactory().createCoverageStore();
      }

      store.setName(name);
      store.setWorkspace(catalog.getWorkspaceByName(prefix));
      store.setEnabled(true);
      store.setURL(DataUtilities.fileToURL(file).toString());
      store.setType(format.getName());

      if (store.getId() == null) {
        catalog.add(store);
      } else {
        catalog.save(store);
      }

      // create the coverage
      CatalogBuilder builder = new CatalogBuilder(catalog);
      builder.setStore(store);

      CoverageInfo coverage = null;

      try {

        coverage = builder.buildCoverage(reader, null);
        // coverage read params
        if (format instanceof ImageMosaicFormat) {
          //  make sure we work in immediate mode
          coverage
              .getParameters()
              .put(AbstractGridFormat.USE_JAI_IMAGEREAD.getName().getCode(), Boolean.FALSE);
        }
      } catch (Exception e) {
        throw new IOException(e);
      }

      coverage.setName(name);
      coverage.setTitle(name);
      coverage.setDescription(name);
      coverage.setEnabled(true);

      CoverageInfo cov = catalog.getCoverageByCoverageStore(store, name);
      if (cov == null) {
        catalog.add(coverage);
      } else {
        builder.updateCoverage(cov, coverage);
        catalog.save(cov);
        coverage = cov;
      }

      LayerInfo layer = catalog.getLayerByName(new NameImpl(qName));
      if (layer == null) {
        layer = catalog.getFactory().createLayer();
      }
      layer.setResource(coverage);

      layer.setDefaultStyle(
          catalog.getStyleByName(LayerProperty.STYLE.get(props, DEFAULT_RASTER_STYLE)));
      layer.setType(LayerInfo.Type.RASTER);
      layer.setEnabled(true);

      if (layer.getId() == null) {
        catalog.add(layer);
      } else {
        catalog.save(layer);
      }
    } finally {
      if (reader != null) {
        reader.dispose();
      }
    }
  }