@Test
  public void testMin() throws NoSuchIdentifierException, ProcessException {

    // Inputs first
    final Double[] set = {
      new Double(15.5),
      new Double(10.02),
      new Double(1.43),
      new Double(-3.03),
      new Double(4.53),
      new Double(-6.21)
    };

    // Process
    final ProcessDescriptor desc = ProcessFinder.getProcessDescriptor("math", "min");

    final ParameterValueGroup in = desc.getInputDescriptor().createValue();
    in.parameter("set").setValue(set);
    final org.geotoolkit.process.Process proc = desc.createProcess(in);

    // result
    final Double result = (Double) proc.call().parameter("result").getValue();

    assertEquals(new Double(-6.21), result);
  }
  public static void main(String[] args) throws Exception {
    URL imageURL = RasterTutorial.class.getResource("image.png");

    BufferedImage image = ImageIO.read(imageURL);

    // coordinates of our raster image, in lat/lon
    double minx = -92.36918018580701;
    double miny = -49.043520894708884;

    double maxx = -42.25153935511384;
    double maxy = 2.1002762835725868;

    CoordinateReferenceSystem crs = CRS.decode("EPSG:4326");
    ReferencedEnvelope envelope = new ReferencedEnvelope(minx, maxx, miny, maxy, crs);

    String name = "GridCoverage";

    GridCoverageFactory factory = new GridCoverageFactory();
    GridCoverage2D gridCoverage = (GridCoverage2D) factory.create(name, image, envelope);

    CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:24882");

    RenderingHints hints = new RenderingHints(Hints.LENIENT_DATUM_SHIFT, Boolean.TRUE);
    CoverageProcessor processor = new CoverageProcessor(hints);

    ParameterValueGroup param = processor.getOperation("Resample").getParameters();
    param.parameter("Source").setValue(gridCoverage);
    param.parameter("CoordinateReferenceSystem").setValue(targetCRS);
    param.parameter("InterpolationType").setValue("NearestNeighbor");

    GridCoverage2D reprojected = (GridCoverage2D) processor.doOperation(param);

    ViewerOld.show(gridCoverage, "Normal Grid Coverage");
    ViewerOld.show(reprojected, "Reprojected Grid Coverage");
  }
Beispiel #3
0
  @Test
  public void testLenght() throws NoSuchIdentifierException, ProcessException {

    GeometryFactory fact = new GeometryFactory();

    // Inputs first
    final LinearRing ring =
        fact.createLinearRing(
            new Coordinate[] {
              new Coordinate(0.0, 0.0),
              new Coordinate(0.0, 10.0),
              new Coordinate(5.0, 10.0),
              new Coordinate(5.0, 0.0),
              new Coordinate(0.0, 0.0)
            });

    final Geometry geom1 = fact.createPolygon(ring, null);

    // Process
    final ProcessDescriptor desc = ProcessFinder.getProcessDescriptor("jts", "lenght");

    final ParameterValueGroup in = desc.getInputDescriptor().createValue();
    in.parameter("geom").setValue(geom1);
    final org.geotoolkit.process.Process proc = desc.createProcess(in);

    // result
    final Double result = (Double) proc.call().parameter("result").getValue();

    final Double expected = geom1.getLength();

    assertTrue(expected.equals(result));
  }
  @Test
  public void testIntersection() throws ProcessException, NoSuchIdentifierException {

    // Inputs
    final FeatureCollection<?> featureList = buildFeatureList();
    final FeatureCollection<?> featureUnionList = buildFeatureUnionList();

    // Process
    ProcessDescriptor desc = ProcessFinder.getProcessDescriptor("vector", "union");

    ParameterValueGroup in = desc.getInputDescriptor().createValue();
    in.parameter("feature_in").setValue(featureList);
    in.parameter("feature_union").setValue(featureUnionList);
    in.parameter("input_geometry_name").setValue("geom1");
    org.geotoolkit.process.Process proc = desc.createProcess(in);

    // Features out
    final FeatureCollection<?> featureListOut =
        (FeatureCollection<?>) proc.call().parameter("feature_out").getValue();

    // Expected Features out
    final FeatureCollection<?> featureListResult = buildResultList();

    assertEquals(featureListOut.getFeatureType(), featureListResult.getFeatureType());
    assertEquals(featureListOut.getID(), featureListResult.getID());
    assertEquals(featureListOut.size(), featureListResult.size());
    assertTrue(featureListOut.containsAll(featureListResult));
  }
  /**
   * Test coverageToFeature process with a PixelInCell.CELL_CENTER coverage
   *
   * @throws NoSuchAuthorityCodeException
   * @throws FactoryException
   */
  @Test
  public void coverageToFeatureTestPixelCenter()
      throws NoSuchAuthorityCodeException, FactoryException, ProcessException {

    Hints.putSystemDefault(Hints.LENIENT_DATUM_SHIFT, Boolean.TRUE);

    PixelInCell pixPos = PixelInCell.CELL_CENTER;
    GridCoverageReader reader = buildReader(pixPos);
    // Process
    ProcessDescriptor desc = ProcessFinder.getProcessDescriptor("coverage", "coveragetofeatures");
    ParameterValueGroup in = desc.getInputDescriptor().createValue();
    in.parameter("reader_in").setValue(reader);
    org.geotoolkit.process.Process proc = desc.createProcess(in);

    // Features out
    final Collection<Feature> featureListOut =
        (Collection<Feature>) proc.call().parameter("feature_out").getValue();

    final List<Feature> featureListResult = (List<Feature>) buildFCResultPixelCenter();

    assertEquals(featureListResult.get(0).getType(), featureListOut.iterator().next().getType());
    assertEquals(featureListOut.size(), featureListResult.size());

    Iterator<Feature> iteratorOut = featureListOut.iterator();
    Iterator<Feature> iteratorResult = featureListResult.iterator();

    ArrayList<Geometry> geomsOut = new ArrayList<Geometry>();
    int itOut = 0;
    while (iteratorOut.hasNext()) {
      Feature featureOut = iteratorOut.next();

      for (Property propertyOut : featureOut.getProperties()) {
        if (propertyOut.getDescriptor() instanceof GeometryDescriptor) {
          geomsOut.add(itOut++, (Geometry) propertyOut.getValue());
        }
      }
    }
    ArrayList<Geometry> geomsResult = new ArrayList<Geometry>();
    int itResult = 0;
    while (iteratorResult.hasNext()) {
      Feature featureResult = iteratorResult.next();

      for (Property propertyResult : featureResult.getProperties()) {
        if (propertyResult.getDescriptor() instanceof GeometryDescriptor) {
          geomsResult.add(itResult++, (Geometry) propertyResult.getValue());
        }
      }
    }
    assertEquals(geomsResult.size(), geomsOut.size());
    for (int i = 0; i < geomsResult.size(); i++) {
      Geometry gOut = geomsOut.get(i);
      Geometry gResult = geomsResult.get(i);
      assertArrayEquals(gResult.getCoordinates(), gOut.getCoordinates());
    }
  }
Beispiel #6
0
  @Test
  public void NetCDFNoDataOperation()
      throws NoSuchAuthorityCodeException, FactoryException, IOException, ParseException {
    File mosaic = new File(TestData.file(this, "."), "NetCDFGOME2");
    if (mosaic.exists()) {
      FileUtils.deleteDirectory(mosaic);
    }
    assertTrue(mosaic.mkdirs());
    File file = TestData.file(this, "DUMMY.GOME2.NO2.PGL.nc");
    FileUtils.copyFileToDirectory(file, mosaic);
    file = new File(mosaic, "DUMMY.GOME2.NO2.PGL.nc");

    final Hints hints =
        new Hints(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, CRS.decode("EPSG:4326", true));
    // Get format
    final AbstractGridFormat format =
        (AbstractGridFormat) GridFormatFinder.findFormat(file.toURI().toURL(), hints);
    final NetCDFReader reader = (NetCDFReader) format.getReader(file.toURI().toURL(), hints);

    assertNotNull(format);
    GridCoverage2D gc = null;
    try {
      String[] names = reader.getGridCoverageNames();
      names = new String[] {names[0]};
      gc = reader.read(null);
    } catch (Throwable t) {
      throw new RuntimeException(t);
    } finally {
      if (reader != null) {
        try {
          reader.dispose();
        } catch (Throwable t) {
          // Does nothing
        }
      }
    }
    // Checking NoData
    Object noData = CoverageUtilities.getNoDataProperty(gc);
    assertNotNull(noData);
    assertTrue(noData instanceof NoDataContainer);
    Double d = ((NoDataContainer) noData).getAsSingleValue();
    assertEquals(d, -999d, DELTA);
    // Try to execute an operation on the NoData and check if the result contains also NoData
    CoverageProcessor instance = CoverageProcessor.getInstance();
    Operation scale = instance.getOperation("Scale");
    ParameterValueGroup params = scale.getParameters();
    params.parameter("Source0").setValue(gc);
    params.parameter("backgroundValues").setValue(new double[] {0});
    GridCoverage2D result = (GridCoverage2D) instance.doOperation(params);
    noData = CoverageUtilities.getNoDataProperty(result);
    assertNotNull(noData);
    assertTrue(noData instanceof NoDataContainer);
    d = ((NoDataContainer) noData).getAsSingleValue();
    assertEquals(d, 0d, DELTA);
  }
 /**
  * Tests all map projection creation.
  *
  * @throws FactoryException If a CRS can not be created.
  */
 @Test
 public void testMapProjections() throws FactoryException {
   out.println();
   out.println("Testing classification names");
   out.println("----------------------------");
   final CRSFactory crsFactory = ReferencingFactoryFinder.getCRSFactory(null);
   final MathTransformFactory mtFactory = ReferencingFactoryFinder.getMathTransformFactory(null);
   final Collection<OperationMethod> methods = mtFactory.getAvailableMethods(Projection.class);
   final Map<String, ?> dummyName = Collections.singletonMap("name", "Test");
   for (final OperationMethod method : methods) {
     final String classification = method.getName().getCode();
     final ParameterValueGroup param = mtFactory.getDefaultParameters(classification);
     try {
       param.parameter("semi_major").setValue(6377563.396);
       param.parameter("semi_minor").setValue(6356256.909237285);
     } catch (IllegalArgumentException e) {
       // Above parameters do not exists. Ignore.
     }
     final MathTransform mt;
     try {
       mt = mtFactory.createParameterizedTransform(param);
     } catch (FactoryException e) {
       // Probably not a map projection. This test is mostly about projection, so ignore.
       continue;
     } catch (UnsupportedOperationException e) {
       continue;
     }
     if (mt instanceof MapProjection) {
       /*
        * Tests map projection properties. Some tests are ommitted for south-oriented
        * map projections, since they are implemented as a concatenation of their North-
        * oriented variants with an affine transform.
        */
       out.println(classification);
       final boolean skip =
           classification.equalsIgnoreCase("Transverse Mercator (South Orientated)")
               || classification.equalsIgnoreCase("Equidistant_Cylindrical");
       if (!skip) {
         assertEquals(
             classification, ((MapProjection) mt).getParameterDescriptors().getName().getCode());
       }
       final ProjectedCRS projCRS =
           crsFactory.createProjectedCRS(
               dummyName,
               DefaultGeographicCRS.WGS84,
               new DefiningConversion(dummyName, method, mt),
               DefaultCartesianCS.PROJECTED);
       final Conversion conversion = projCRS.getConversionFromBase();
       assertSame(mt, conversion.getMathTransform());
       final OperationMethod projMethod = conversion.getMethod();
       assertEquals(classification, projMethod.getName().getCode());
     }
   }
 }
  /**
   * Applies the specified operation to the given coverages.
   *
   * @param coverage0 The coverage to scale.
   * @param interp The interpolation to use.
   * @throws IOException
   */
  private GridCoverage2D doOp(
      final String operationName, final GridCoverage2D coverage0, final GridCoverage2D coverage1)
      throws IOException {

    // Getting parameters for doing a scale.
    final ParameterValueGroup param = processor.getOperation(operationName).getParameters();
    param.parameter("Source0").setValue(coverage0);
    param.parameter("Source1").setValue(coverage1);

    // Doing a first scale.
    GridCoverage2D result = (GridCoverage2D) processor.doOperation(param);
    assertEnvelopeEquals(coverage0, result);
    return result;
  }
  /**
   * <strong>Cropping</strong><br>
   * The crop operation is responsible for selecting geographic subareas of the source coverage.
   *
   * @param coverage Coverage
   * @param sourceEnvelope GeneralEnvelope
   * @param sourceCRS CoordinateReferenceSystem
   * @param destinationEnvelopeInSourceCRS GeneralEnvelope
   * @return GridCoverage2D
   * @throws WcsException
   */
  public static GridCoverage2D crop(
      final Coverage coverage,
      final GeneralEnvelope sourceEnvelope,
      final CoordinateReferenceSystem sourceCRS,
      final GeneralEnvelope destinationEnvelopeInSourceCRS,
      final Boolean conserveEnvelope)
      throws WcsException {
    // ///////////////////////////////////////////////////////////////////
    //
    // CROP
    //
    //
    // ///////////////////////////////////////////////////////////////////
    final GridCoverage2D croppedGridCoverage;

    // intersect the envelopes
    final GeneralEnvelope intersectionEnvelope =
        new GeneralEnvelope(destinationEnvelopeInSourceCRS);
    intersectionEnvelope.setCoordinateReferenceSystem(sourceCRS);
    intersectionEnvelope.intersect((GeneralEnvelope) sourceEnvelope);

    // dow we have something to show?
    if (intersectionEnvelope.isEmpty()) {
      throw new WcsException("The Intersection is null. Check the requested BBOX!");
    }

    if (!intersectionEnvelope.equals((GeneralEnvelope) sourceEnvelope)) {
      // get the cropped grid geometry
      // final GridGeometry2D cropGridGeometry = getCroppedGridGeometry(
      // intersectionEnvelope, gridCoverage);

      /* Operations.DEFAULT.crop(coverage, intersectionEnvelope) */
      final ParameterValueGroup param = (ParameterValueGroup) cropParams.clone();
      param.parameter("Source").setValue(coverage);
      param.parameter("Envelope").setValue(intersectionEnvelope);
      // param.parameter("ConserveEnvelope").setValue(conserveEnvelope);

      croppedGridCoverage = (GridCoverage2D) cropFactory.doOperation(param, hints);
    } else {
      croppedGridCoverage = (GridCoverage2D) coverage;
    }

    // prefetch to be faster afterwards.
    // This step is important since at this stage we might be loading tiles
    // from disk
    croppedGridCoverage.prefetch(intersectionEnvelope.toRectangle2D());

    return croppedGridCoverage;
  }
  @Override
  public GridCoverage2D read(GeneralParameterValue[] parameters)
      throws IllegalArgumentException, IOException {
    File baseDir = FileUtils.createTempDirectory();

    try {
      File file = readToFile(baseDir, "WcsCoverageReader", parameters);

      // since the requested format may be one of several we need to look
      // up the format object
      // for reading the coverage from the file
      Format format = GridFormatFinder.findFormat(file);

      if (format instanceof AbstractGridFormat && UnknownFormat.class != format.getClass()) {
        AbstractGridFormat gridFormat = (AbstractGridFormat) format;

        // Now we need to find the parameters provided by the caller for
        // reading the coverage from the file
        // See the format API for details
        GeneralParameterValue[] readParams = new GeneralParameterValue[0];
        try {
          ParameterValueGroup group = format.getReadParameters();
          List<GeneralParameterValue> list = new ArrayList<GeneralParameterValue>();
          for (GeneralParameterValue paramValue : group.values()) {
            list.addAll(find(paramValue, parameters));
          }
          LOG.debug("Reading coverage from file using parameters: " + list);
          readParams = list.toArray(new GeneralParameterValue[list.size()]);
        } catch (Exception e) {
          // if can't configure the parameters then try to read with
          // what we have been able to configure
          LOG.warn("Exception occurred while getting request params for reading coverage", e);
        }
        AbstractGridCoverage2DReader reader = gridFormat.getReader(file);
        GridCoverage2D coverage = reader.read(readParams);
        return coverage;
      }
      throw new IllegalArgumentException(
          "Current configuration is unable to read coverage of "
              + file.getName()
              + " format.  "
              + "Check that you have the correct geotools plugins");

    } finally {
      FileUtils.delete(baseDir);
    }
  }
 private static ParameterValueGroup getSourceConfiguration(final ParameterValueGroup params) {
   final List<ParameterValueGroup> groups =
       params.groups(SOURCE_CONFIG_DESCRIPTOR.getName().getCode());
   if (!groups.isEmpty()) {
     return groups.get(0);
   }
   return null;
 }
 /**
  * Constructs a conversion from a set of parameters. The properties given in argument follow the
  * same rules than for the {@link AbstractCoordinateOperation} constructor.
  *
  * @param properties Set of properties. Should contains at least {@code "name"}.
  * @param method The operation method.
  * @param parameters The parameter values.
  */
 public DefiningConversion(
     final Map<String, ?> properties,
     final OperationMethod method,
     final ParameterValueGroup parameters) {
   super(properties, null, null, null, method);
   ensureNonNull("parameters", parameters);
   this.parameters = parameters.clone();
 }
  @Test
  public void testFailStop() throws NoSuchIdentifierException, ProcessException {
    final ProcessDescriptor desc =
        ProcessFinder.getProcessDescriptor(
            ConstellationProcessFactory.NAME, StopServiceDescriptor.NAME);

    final ParameterValueGroup in = desc.getInputDescriptor().createValue();
    in.parameter(StopServiceDescriptor.SERVICE_TYPE_NAME).setValue(serviceName);
    in.parameter(StopServiceDescriptor.IDENTIFIER_NAME).setValue("stopInstance5");

    try {
      org.geotoolkit.process.Process proc = desc.createProcess(in);
      proc.call();
      fail();
    } catch (ProcessException ex) {
      // do nothing
    }
  }
Beispiel #14
0
 protected void handleJAIEXTParams(ParameterBlockJAI parameters, ParameterValueGroup parameters2) {
   if (JAIExt.isJAIExtOperation("algebric")) {
     parameters.set(Operator.LOG, 0);
     Collection<GridCoverage2D> sources =
         (Collection<GridCoverage2D>) parameters2.parameter("sources").getValue();
     for (GridCoverage2D source : sources) {
       handleROINoDataInternal(parameters, source, "algebric", 1, 2);
     }
   }
 }
  /**
   * <strong>Reprojecting</strong><br>
   * The new grid geometry can have a different coordinate reference system than the underlying grid
   * geometry. For example, a grid coverage can be reprojected from a geodetic coordinate reference
   * system to Universal Transverse Mercator CRS.
   *
   * @param coverage GridCoverage2D
   * @param sourceCRS CoordinateReferenceSystem
   * @param targetCRS CoordinateReferenceSystem
   * @return GridCoverage2D
   * @throws WcsException
   */
  public static GridCoverage2D reproject(
      GridCoverage2D coverage,
      final CoordinateReferenceSystem sourceCRS,
      final CoordinateReferenceSystem targetCRS,
      final Interpolation interpolation)
      throws WcsException {
    // ///////////////////////////////////////////////////////////////////
    //
    // REPROJECT
    //
    //
    // ///////////////////////////////////////////////////////////////////
    if (!CRS.equalsIgnoreMetadata(sourceCRS, targetCRS)) {
      /*
       * Operations.DEFAULT.resample( coverage, targetCRS, null,
       * Interpolation.getInstance(Interpolation.INTERP_NEAREST))
       */
      final ParameterValueGroup param = (ParameterValueGroup) resampleParams.clone();
      param.parameter("Source").setValue(coverage);
      param.parameter("CoordinateReferenceSystem").setValue(targetCRS);
      param.parameter("GridGeometry").setValue(null);
      param.parameter("InterpolationType").setValue(interpolation);

      coverage = (GridCoverage2D) resampleFactory.doOperation(param, hints);
    }

    return coverage;
  }
  /**
   * Test the {@link DefaultProjectedCRS#createLinearConversion} method. Note: this requires a
   * working {@link MathTransformFactory}.
   *
   * @throws FactoryException If the conversion can't be created.
   */
  @Test
  public void testCreateLinearConversion() throws FactoryException {
    final double EPS = 1E-12;
    final MathTransformFactory factory = new DefaultMathTransformFactory();
    final ParameterValueGroup parameters = factory.getDefaultParameters("Mercator_1SP");
    DefaultProjectedCRS sourceCRS, targetCRS;
    MathTransform transform;
    Matrix conversion;

    parameters.parameter("semi_major").setValue(DefaultEllipsoid.WGS84.getSemiMajorAxis());
    parameters.parameter("semi_minor").setValue(DefaultEllipsoid.WGS84.getSemiMinorAxis());
    transform = factory.createParameterizedTransform(parameters);
    sourceCRS = new DefaultProjectedCRS("source", WGS84, transform, PROJECTED);

    parameters.parameter("false_easting").setValue(1000);
    parameters.parameter("false_northing").setValue(2000);
    transform = factory.createParameterizedTransform(parameters);
    targetCRS = new DefaultProjectedCRS("source", WGS84, transform, PROJECTED);

    conversion = ProjectionAnalyzer.createLinearConversion(sourceCRS, targetCRS, EPS);
    assertEquals(new Matrix3(1, 0, 1000, 0, 1, 2000, 0, 0, 1), conversion);

    parameters.parameter("scale_factor").setValue(2);
    transform = factory.createParameterizedTransform(parameters);
    targetCRS = new DefaultProjectedCRS("source", WGS84, transform, PROJECTED);

    conversion = ProjectionAnalyzer.createLinearConversion(sourceCRS, targetCRS, EPS);
    assertEquals(new Matrix3(2, 0, 1000, 0, 2, 2000, 0, 0, 1), conversion);

    parameters.parameter("semi_minor").setValue(DefaultEllipsoid.WGS84.getSemiMajorAxis());
    transform = factory.createParameterizedTransform(parameters);
    targetCRS = new DefaultProjectedCRS("source", WGS84, transform, PROJECTED);
    conversion = ProjectionAnalyzer.createLinearConversion(sourceCRS, targetCRS, EPS);
    assertNull(conversion);
  }
  @Override
  public WebMapTileClient open(ParameterValueGroup params) throws DataStoreException {
    ensureCanProcess(params);
    final WebMapTileClient server = new WebMapTileClient(params);

    try {
      final ParameterValue val = params.parameter(NIO_QUERIES.getName().getCode());
      boolean useNIO = Boolean.TRUE.equals(val.getValue());
      server.setUserProperty(CachedPyramidSet.PROPERTY_NIO, useNIO);
    } catch (ParameterNotFoundException ex) {
    }

    return server;
  }
Beispiel #18
0
 /** Returns a projected CRS for test purpose. */
 private static CoordinateReferenceSystem getProjectedCRS(final GridCoverage2D coverage) {
   try {
     final GeographicCRS base = (GeographicCRS) coverage.getCoordinateReferenceSystem();
     final Ellipsoid ellipsoid = base.getDatum().getEllipsoid();
     final DefaultMathTransformFactory factory = new DefaultMathTransformFactory();
     final ParameterValueGroup parameters = factory.getDefaultParameters("Oblique_Stereographic");
     parameters.parameter("semi_major").setValue(ellipsoid.getSemiMajorAxis());
     parameters.parameter("semi_minor").setValue(ellipsoid.getSemiMinorAxis());
     parameters.parameter("central_meridian").setValue(5);
     parameters.parameter("latitude_of_origin").setValue(-5);
     final MathTransform mt;
     try {
       mt = factory.createParameterizedTransform(parameters);
     } catch (FactoryException exception) {
       fail(exception.getLocalizedMessage());
       return null;
     }
     return new DefaultProjectedCRS("Stereographic", base, mt, DefaultCartesianCS.PROJECTED);
   } catch (NoSuchIdentifierException exception) {
     fail(exception.getLocalizedMessage());
     return null;
   }
 }
  @Test
  public void testStop() throws NoSuchIdentifierException, ProcessException {

    createInstance("stopInstance1");
    startInstance("stopInstance1");

    try {
      final int initSize = WSEngine.getInstanceSize(serviceName);
      final ProcessDescriptor desc =
          ProcessFinder.getProcessDescriptor(
              ConstellationProcessFactory.NAME, StopServiceDescriptor.NAME);

      final ParameterValueGroup in = desc.getInputDescriptor().createValue();
      in.parameter(StopServiceDescriptor.SERVICE_TYPE_NAME).setValue(serviceName);
      in.parameter(StopServiceDescriptor.IDENTIFIER_NAME).setValue("stopInstance1");
      org.geotoolkit.process.Process proc = desc.createProcess(in);
      proc.call();

      assertTrue(WSEngine.getInstanceSize(serviceName) == initSize - 1);
      assertFalse(WSEngine.serviceInstanceExist(serviceName, "stopInstance1"));
    } finally {
      deleteInstance(serviceBusiness, "stopInstance1");
    }
  }
  private static MathTransform createLambertConformalConicMathTransform(
      LambertConformalConicDescriptor.LCCT t) throws FactoryException {
    final MathTransformFactory transformFactory =
        ReferencingFactoryFinder.getMathTransformFactory(null);
    final ParameterValueGroup parameters =
        transformFactory.getDefaultParameters("ESRI:Lambert_Conformal_Conic");

    parameters.parameter("semi_major").setValue(t.getSemiMajor());
    parameters.parameter("semi_minor").setValue(t.getSemiMinor());
    parameters.parameter("central_meridian").setValue(t.getCentralMeridian());
    parameters.parameter("latitude_of_origin").setValue(t.getLatitudeOfOrigin());
    parameters.parameter("standard_parallel_1").setValue(t.getStandardParallel1());
    parameters.parameter("standard_parallel_2").setValue(t.getStandardParallel2());
    parameters.parameter("scale_factor").setValue(t.getScaleFactor());
    parameters.parameter("false_easting").setValue(t.getFalseEasting());
    parameters.parameter("false_northing").setValue(t.getFalseNorthing());

    return transformFactory.createParameterizedTransform(parameters);
  }
  private static MathTransform createTransverseMercatorMathTransform(
      TransverseMercatorDescriptor.TMT t) throws FactoryException {

    final MathTransformFactory transformFactory =
        ReferencingFactoryFinder.getMathTransformFactory(null);
    final ParameterValueGroup parameters = transformFactory.getDefaultParameters("EPSG:9807");

    parameters.parameter("semi_major").setValue(t.getSemiMajor());
    parameters.parameter("semi_minor").setValue(t.getSemiMinor());
    parameters.parameter("central_meridian").setValue(t.getCentralMeridian());
    parameters.parameter("latitude_of_origin").setValue(t.getLatitudeOfOrigin());
    parameters.parameter("scale_factor").setValue(t.getScaleFactor());
    parameters.parameter("false_easting").setValue(t.getFalseEasting());
    parameters.parameter("false_northing").setValue(t.getFalseNorthing());

    return transformFactory.createParameterizedTransform(parameters);
  }
  /**
   * <strong>Scaling</strong><br>
   * Let user to scale down to the EXACT needed resolution. This step does not prevent from having
   * loaded an overview of the original image based on the requested scale.
   *
   * @param coverage GridCoverage2D
   * @param newGridRange GridRange
   * @param sourceCoverage GridCoverage
   * @param sourceCRS CoordinateReferenceSystem
   * @param destinationEnvelopeInSourceCRS
   * @return GridCoverage2D
   */
  public static GridCoverage2D scale(
      final GridCoverage2D coverage,
      final GridEnvelope newGridRange,
      final GridCoverage sourceCoverage,
      final CoordinateReferenceSystem sourceCRS,
      final GeneralEnvelope destinationEnvelopeInSourceCRS) {
    // ///////////////////////////////////////////////////////////////////
    //
    // SCALE to the needed resolution
    // Let me now scale down to the EXACT needed resolution. This step does
    // not prevent from having loaded an overview of the original image
    // based on the requested scale.
    //
    // ///////////////////////////////////////////////////////////////////
    GridGeometry2D scaledGridGeometry =
        new GridGeometry2D(
            newGridRange,
            (destinationEnvelopeInSourceCRS != null)
                ? destinationEnvelopeInSourceCRS
                : sourceCoverage.getEnvelope());

    /*
     * Operations.DEFAULT.resample( coverage, sourceCRS, scaledGridGeometry,
     * Interpolation.getInstance(Interpolation.INTERP_NEAREST));
     */
    final ParameterValueGroup param = (ParameterValueGroup) resampleParams.clone();
    param.parameter("Source").setValue(coverage);
    param.parameter("CoordinateReferenceSystem").setValue(sourceCRS);
    param.parameter("GridGeometry").setValue(scaledGridGeometry);
    param
        .parameter("InterpolationType")
        .setValue(Interpolation.getInstance(Interpolation.INTERP_NEAREST));

    final GridCoverage2D scaledGridCoverage =
        (GridCoverage2D) resampleFactory.doOperation(param, hints);

    return scaledGridCoverage;
  }
  @Test
  public void testOverlapsCRS() throws NoSuchIdentifierException, ProcessException {

    GeometryFactory fact = new GeometryFactory();

    // Inputs first
    final LinearRing ring =
        fact.createLinearRing(
            new Coordinate[] {
              new Coordinate(0.0, 0.0),
              new Coordinate(0.0, 10.0),
              new Coordinate(5.0, 10.0),
              new Coordinate(5.0, 0.0),
              new Coordinate(0.0, 0.0)
            });

    final Geometry geom1 = fact.createPolygon(ring, null);

    final LinearRing ring2 =
        fact.createLinearRing(
            new Coordinate[] {
              new Coordinate(-5.0, 0.0),
              new Coordinate(-5.0, 10.0),
              new Coordinate(2.0, 10.0),
              new Coordinate(2.0, 0.0),
              new Coordinate(-5.0, 0.0)
            });

    Geometry geom2 = fact.createPolygon(ring2, null);

    CoordinateReferenceSystem crs1 = null;
    try {
      crs1 = CRS.decode("EPSG:4326");
      JTS.setCRS(geom1, crs1);
    } catch (FactoryException ex) {
      Logger.getLogger(UnionProcess.class.getName()).log(Level.SEVERE, null, ex);
    }

    CoordinateReferenceSystem crs2 = null;
    try {
      crs2 = CRS.decode("EPSG:4326");
      JTS.setCRS(geom2, crs2);
    } catch (FactoryException ex) {
      Logger.getLogger(UnionProcess.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Process
    final ProcessDescriptor desc = ProcessFinder.getProcessDescriptor("jts", "overlaps");

    final ParameterValueGroup in = desc.getInputDescriptor().createValue();
    in.parameter("geom1").setValue(geom1);
    in.parameter("geom2").setValue(geom2);
    final org.geotoolkit.process.Process proc = desc.createProcess(in);

    // result
    final Boolean result = (Boolean) proc.call().parameter("result").getValue();

    MathTransform mt = null;
    try {
      mt = CRS.findMathTransform(crs2, crs1);
      geom2 = JTS.transform(geom2, mt);
    } catch (FactoryException ex) {
      Logger.getLogger(UnionProcess.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TransformException ex) {
      Logger.getLogger(UnionProcess.class.getName()).log(Level.SEVERE, null, ex);
    }

    final Boolean expected = geom1.overlaps(geom2);

    assertTrue(expected.equals(result));
  }
Beispiel #24
0
  /** {@inheritDoc} */
  protected void setProjectionParameters(final ParameterValueGroup parameters, final Code code) {
    final double centralMeridian = code.longitude;

    parameters.parameter("central_meridian").setValue(centralMeridian);
  }
  public static void attachGeoCoding(
      Product p,
      double upperLeftLon,
      double upperLeftLat,
      double lowerRightLon,
      double lowerRightLat,
      String projection,
      double[] projectionParameter) {
    double pixelSizeX = (lowerRightLon - upperLeftLon) / p.getSceneRasterWidth();
    double pixelSizeY = (upperLeftLat - lowerRightLat) / p.getSceneRasterHeight();

    AffineTransform transform = new AffineTransform();
    transform.translate(upperLeftLon, upperLeftLat);
    transform.scale(pixelSizeX, -pixelSizeY);
    transform.translate(PIXEL_CENTER, PIXEL_CENTER);
    Rectangle imageBounds = new Rectangle(p.getSceneRasterWidth(), p.getSceneRasterHeight());

    if (projection.equals("GCTP_GEO")) {
      if ((upperLeftLon >= -180 && upperLeftLon <= 180)
          && (upperLeftLat >= -90 && upperLeftLat <= 90)
          && (lowerRightLon >= -180 && lowerRightLon <= 180)
          && (lowerRightLat >= -90 && lowerRightLat <= 90)) {
        try {
          p.setGeoCoding(new CrsGeoCoding(DefaultGeographicCRS.WGS84, imageBounds, transform));
        } catch (FactoryException | TransformException ignore) {
        }
      }
    } else {
      if (projection.equals("GCTP_SNSOID")) {
        final MathTransformFactory transformFactory =
            ReferencingFactoryFinder.getMathTransformFactory(null);
        ParameterValueGroup parameters;
        try {
          parameters = transformFactory.getDefaultParameters("OGC:Sinusoidal");
        } catch (NoSuchIdentifierException ignore) {
          return;
        }
        double semi_major;
        double semi_minor;
        if (projectionParameter != null) {
          semi_major = projectionParameter[0];
          semi_minor = projectionParameter[1];
          if (semi_minor == 0) {
            semi_minor = semi_major;
          }
        } else {
          Ellipsoid ellipsoid = DefaultGeographicCRS.WGS84.getDatum().getEllipsoid();
          semi_major = ellipsoid.getSemiMajorAxis();
          semi_minor = ellipsoid.getSemiMinorAxis();
        }
        parameters.parameter("semi_major").setValue(semi_major);
        parameters.parameter("semi_minor").setValue(semi_minor);

        MathTransform mathTransform;
        try {
          mathTransform = transformFactory.createParameterizedTransform(parameters);
        } catch (Exception ignore) {
          return;
        }

        DefaultGeographicCRS base = DefaultGeographicCRS.WGS84;
        CoordinateReferenceSystem modelCrs =
            new DefaultProjectedCRS(
                "Sinusoidal", base, mathTransform, DefaultCartesianCS.PROJECTED);
        try {
          CrsGeoCoding geoCoding = new CrsGeoCoding(modelCrs, imageBounds, transform);

          p.setGeoCoding(geoCoding);
        } catch (Exception ignore) {
        }
      }
    }
  }
  public static void storeGeoTIFFSampleImage(
      List<CUDABean> beans, int w, int h, Object data, int dataType, String name)
      throws IOException {
    /** create the final coverage using final envelope */
    // Definition of the SampleModel
    final SampleModel sm = new PixelInterleavedSampleModel(dataType, w, h, 1, w, new int[] {0});
    // DataBuffer containing input data

    DataBuffer db1 = null;
    if (dataType == DataBuffer.TYPE_INT) {
      db1 = new DataBufferInt((int[]) data, w * h);
    } else if (dataType == DataBuffer.TYPE_BYTE) {
      db1 = new DataBufferByte((byte[]) data, w * h);
    } else if (dataType == DataBuffer.TYPE_DOUBLE) {
      db1 = new DataBufferDouble((double[]) data, w * h);
    }
    // Writable Raster used for creating the BufferedImage
    final WritableRaster wr =
        com.sun.media.jai.codecimpl.util.RasterFactory.createWritableRaster(
            sm, db1, new Point(0, 0));
    final BufferedImage image = new BufferedImage(ImageUtil.createColorModel(sm), wr, false, null);

    // hints for tiling
    final Hints hints = GeoTools.getDefaultHints().clone();

    // build the output sample dimensions, use the default value ( 0 ) as
    // the no data
    final GridSampleDimension outSampleDimension =
        new GridSampleDimension("classification", new Category[] {Category.NODATA}, null)
            .geophysics(true);

    final GridCoverage2D retValue =
        new GridCoverageFactory(hints)
            .create(
                name,
                image,
                beans.get(0).getReferenceCoverage().getEnvelope(),
                new GridSampleDimension[] {outSampleDimension},
                new GridCoverage[] {beans.get(0).getReferenceCoverage()},
                new HashMap<String, Double>() {
                  {
                    put("GC_NODATA", 0d);
                  }
                });

    final File file =
        new File(UrbanGridCUDAProcess.TESTING_DIR, name /*+(System.nanoTime())*/ + ".tif");
    GeoTiffWriter writer = new GeoTiffWriter(file);

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

    try {
      writer.write(retValue, wps);
    } finally {
      try {
        writer.dispose();
      } catch (Exception e) {
        throw new IOException("Unable to write the output raster.", e);
      }
    }
  }
Beispiel #27
0
  /**
   * Applies a crop operation to a coverage.
   *
   * @see
   *     org.geotools.coverage.processing.AbstractOperation#doOperation(org.opengis.parameter.ParameterValueGroup,
   *     org.geotools.factory.Hints)
   */
  @SuppressWarnings("unchecked")
  public Coverage doOperation(ParameterValueGroup parameters, Hints hints) {

    final Geometry cropRoi; // extracted from parameters
    GeneralEnvelope cropEnvelope = null; // extracted from parameters
    final GridCoverage2D source; // extracted from parameters
    final double roiTolerance = parameters.parameter(Crop.PARAMNAME_ROITOLERANCE).doubleValue();
    final boolean forceMosaic = parameters.parameter(Crop.PARAMNAME_FORCEMOSAIC).booleanValue();

    // /////////////////////////////////////////////////////////////////////
    //
    // Assigning and checking input parameters
    //
    // ///////////////////////////////////////////////////////////////////

    // source coverage
    final ParameterValue sourceParameter = parameters.parameter("Source");
    if (sourceParameter == null || !(sourceParameter.getValue() instanceof GridCoverage2D)) {
      throw new CannotCropException(
          Errors.format(ErrorKeys.NULL_PARAMETER_$2, "Source", GridCoverage2D.class.toString()));
    }
    source = (GridCoverage2D) sourceParameter.getValue();

    // Check Envelope and ROI existence - we need at least one of them
    final ParameterValue envelopeParameter = parameters.parameter(PARAMNAME_ENVELOPE);
    final ParameterValue roiParameter = parameters.parameter(PARAMNAME_ROI);

    if ((envelopeParameter == null || envelopeParameter.getValue() == null)
        && (roiParameter == null || roiParameter.getValue() == null))
      throw new CannotCropException(
          Errors.format(
              ErrorKeys.NULL_PARAMETER_$2, PARAMNAME_ENVELOPE, GeneralEnvelope.class.toString()));

    Object envelope = envelopeParameter.getValue();
    if (envelope != null) {
      if (envelope instanceof GeneralEnvelope) {
        cropEnvelope = (GeneralEnvelope) envelope;
      } else if (envelope instanceof Envelope) {
        cropEnvelope = new GeneralEnvelope((Envelope) envelope);
      }
    }
    // may be null

    // Check crop ROI
    try {
      cropRoi =
          IntersectUtils.unrollGeometries(
              (Geometry) roiParameter.getValue()); // may throw if format not correct
    } catch (IllegalArgumentException ex) {
      throw new CannotCropException(
          Errors.format(ErrorKeys.ILLEGAL_ARGUMENT_$2, PARAMNAME_ROI, ex.getMessage()), ex);
    }

    // Setting a GeneralEnvelope from ROI if needed
    if (cropRoi != null && cropEnvelope == null) {
      Envelope e2d =
          JTS.getEnvelope2D(cropRoi.getEnvelopeInternal(), source.getCoordinateReferenceSystem());
      cropEnvelope = new GeneralEnvelope(e2d);
    }

    // /////////////////////////////////////////////////////////////////////
    //
    // Initialization
    //
    // We take the crop envelope and the source envelope then we check their
    // crs and we also check if they ever overlap.
    //
    // /////////////////////////////////////////////////////////////////////
    // envelope of the source coverage
    final Envelope2D sourceEnvelope = source.getEnvelope2D();
    // crop envelope
    Envelope2D destinationEnvelope = new Envelope2D(cropEnvelope);
    CoordinateReferenceSystem sourceCRS = sourceEnvelope.getCoordinateReferenceSystem();
    CoordinateReferenceSystem destinationCRS = destinationEnvelope.getCoordinateReferenceSystem();
    if (destinationCRS == null) {
      // Do not change the user provided object - clone it first.
      final Envelope2D ge = new Envelope2D(destinationEnvelope);
      destinationCRS = source.getCoordinateReferenceSystem2D();
      ge.setCoordinateReferenceSystem(destinationCRS);
      destinationEnvelope = ge;
    }

    // //
    //
    // Source and destination crs must be equals
    //
    // //
    if (!CRS.equalsIgnoreMetadata(sourceCRS, destinationCRS)) {
      throw new CannotCropException(
          Errors.format(
              ErrorKeys.MISMATCHED_ENVELOPE_CRS_$2,
              sourceCRS.getName().getCode(),
              destinationCRS.getName().getCode()));
    }

    if (cropRoi != null) {
      // TODO: check ROI SRID
    }

    // //
    //
    // Check the intersection and, if needed, do the crop operation.
    //
    // //
    final GeneralEnvelope intersectionEnvelope =
        new GeneralEnvelope((Envelope) destinationEnvelope);
    intersectionEnvelope.setCoordinateReferenceSystem(source.getCoordinateReferenceSystem());
    // intersect the envelopes
    intersectionEnvelope.intersect(sourceEnvelope);
    if (intersectionEnvelope.isEmpty())
      throw new CannotCropException(Errors.format(ErrorKeys.CANT_CROP));

    // intersect the ROI with the intersection envelope and throw an error if they do not intersect
    if (cropRoi != null) {
      final Geometry jis =
          JTS.toGeometry(
              (com.vividsolutions.jts.geom.Envelope) new ReferencedEnvelope(intersectionEnvelope));
      if (!IntersectUtils.intersects(cropRoi, jis))
        throw new CannotCropException(Errors.format(ErrorKeys.CANT_CROP));
    }

    // //
    //
    // Get the grid-to-world transform by keeping into account translation
    // of grid geometry constructor for respecting OGC PIXEL-IS-CENTER
    // ImageDatum assumption.
    //
    // //
    final AffineTransform sourceCornerGridToWorld =
        (AffineTransform)
            ((GridGeometry2D) source.getGridGeometry()).getGridToCRS(PixelInCell.CELL_CORNER);

    // //
    //
    // I set the tolerance as half the scale factor of the grid-to-world
    // transform. This should more or less means in most cases "don't bother
    // to crop if the new envelope is as close to the old one that we go
    // deep under pixel size."
    //
    // //
    final double tolerance = XAffineTransform.getScale(sourceCornerGridToWorld);
    if (cropRoi != null || !intersectionEnvelope.equals(sourceEnvelope, tolerance / 2.0, false)) {
      cropEnvelope = intersectionEnvelope.clone();
      return buildResult(
          cropEnvelope,
          cropRoi,
          roiTolerance,
          forceMosaic,
          (hints instanceof Hints) ? (Hints) hints : new Hints(hints),
          source,
          sourceCornerGridToWorld);
    } else {
      // //
      //
      // Note that in case we don't crop at all, WE DO NOT UPDATE the
      // envelope. If we did we might end up doing multiple successive
      // crop without actually cropping the image but, still, we would
      // shrink the envelope each time. Just think about having a loop
      // that crops recursively the same coverage specifying each time an
      // envelope whose URC is only a a scale quarter close to the LLC of
      // the old one. We would never crop the raster but we would modify
      // the grid-to-world transform each time.
      //
      // //
      return source;
    }
  }
Beispiel #28
0
  @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;
  }
 /**
  * Work around for RFE #4093999 in Sun's bug database ("Relax constraint on placement of
  * this()/super() call in constructors").
  */
 private static OperationMethod getOperationMethod(final ParameterValueGroup parameters) {
   ensureNonNull("parameters", parameters);
   final ParameterDescriptorGroup descriptor = parameters.getDescriptor();
   return new DefaultOperationMethod(getProperties(descriptor, null), 2, 2, descriptor);
 }
 /** Returns the parameter values. */
 @Override
 public ParameterValueGroup getParameterValues() {
   return (parameters != null) ? parameters.clone() : super.getParameterValues();
 }