/** @see org.geotools.data.FeatureStore#setFeatures(org.geotools.data.FeatureReader) */ public void setFeatures(FeatureReader<SimpleFeatureType, SimpleFeature> reader) throws IOException { WFSTransactionState ts = null; if (trans == Transaction.AUTO_COMMIT) { ts = new WFSTransactionState(ds); } else { ts = (WFSTransactionState) trans.getState(ds); } ts.addAction( getSchema().getTypeName(), new DeleteAction(getSchema().getTypeName(), Filter.INCLUDE)); ReferencedEnvelope bounds = null; while (reader.hasNext()) { try { SimpleFeature f = reader.next(); List<AttributeDescriptor> atrs = f.getFeatureType().getAttributeDescriptors(); for (int i = 0; i < atrs.size(); i++) { if (atrs.get(i) instanceof GeometryDescriptor) { Geometry g = (Geometry) f.getAttribute(i); CoordinateReferenceSystem cs = ((GeometryDescriptor) atrs.get(i)).getCoordinateReferenceSystem(); if (cs != null && !cs.getIdentifiers().isEmpty()) g.setUserData(cs.getIdentifiers().iterator().next().toString()); if (g == null) continue; if (bounds == null) { bounds = new ReferencedEnvelope(g.getEnvelopeInternal(), cs); } else { bounds.expandToInclude(g.getEnvelopeInternal()); } } } ts.addAction(getSchema().getTypeName(), new InsertAction(f)); } catch (NoSuchElementException e) { WFS_1_0_0_DataStore.LOGGER.warning(e.toString()); } catch (IllegalAttributeException e) { WFS_1_0_0_DataStore.LOGGER.warning(e.toString()); } } // Fire a notification. // JE if (bounds == null) { // if bounds are null then send an envelope to say that features were added but // at an unknown location. bounds = new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem()); ((WFS_1_0_0_DataStore) getDataStore()) .listenerManager.fireFeaturesRemoved( getSchema().getTypeName(), getTransaction(), bounds, false); } else { ((WFS_1_0_0_DataStore) getDataStore()) .listenerManager.fireFeaturesRemoved( getSchema().getTypeName(), getTransaction(), bounds, false); } if (trans == Transaction.AUTO_COMMIT) { ts.commit(); } }
@Test public void NetCDFProjectedEnvelopeTest() throws NoSuchAuthorityCodeException, FactoryException, IOException, ParseException { File mosaic = new File(TestData.file(this, "."), "NetCDFProjection"); if (mosaic.exists()) { FileUtils.deleteDirectory(mosaic); } assertTrue(mosaic.mkdirs()); File file = TestData.file(this, "wind.nc"); FileUtils.copyFileToDirectory(file, mosaic); file = new File(mosaic, "wind.nc"); // Get format final NetCDFReader reader = new NetCDFReader(file, null); try { String[] names = reader.getGridCoverageNames(); String coverageName = names[0]; // subsetting the envelope final ParameterValue<GridGeometry2D> gg = AbstractGridFormat.READ_GRIDGEOMETRY2D.createValue(); final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope(coverageName); final CoordinateReferenceSystem epsg3857 = CRS.decode("EPSG:3857", true); final GeneralEnvelope projectedEnvelope = CRS.transform(originalEnvelope, epsg3857); gg.setValue( new GridGeometry2D(new GridEnvelope2D(new Rectangle(0, 0, 30, 30)), projectedEnvelope)); GeneralParameterValue[] values = new GeneralParameterValue[] {gg}; GridCoverage2D coverage = reader.read(coverageName, values); // reader doesn't perform reprojection. It simply transforms reprojected envelope // to native envelope so BBOX and CRS should be wgs84 CoordinateReferenceSystem coverageCRS = coverage.getCoordinateReferenceSystem(); final int code = CRS.lookupEpsgCode(coverageCRS, false); assertEquals(4326, code); Extent extent = coverageCRS.getDomainOfValidity(); Collection<? extends GeographicExtent> geoElements = extent.getGeographicElements(); GeographicExtent geographicExtent = geoElements.iterator().next(); GeographicBoundingBoxImpl impl = (GeographicBoundingBoxImpl) geographicExtent; // Getting the coverage Envelope for coordinates check Envelope coverageEnvelope = coverage.getEnvelope(); assertTrue(impl.getEastBoundLongitude() >= coverageEnvelope.getMaximum(0)); assertTrue(impl.getWestBoundLongitude() <= coverageEnvelope.getMinimum(0)); assertTrue(impl.getNorthBoundLatitude() >= coverageEnvelope.getMaximum(1)); assertTrue(impl.getSouthBoundLatitude() <= coverageEnvelope.getMinimum(1)); } catch (Throwable t) { throw new RuntimeException(t); } finally { if (reader != null) { try { reader.dispose(); } catch (Throwable t) { // Does nothing } } } }
/** {@inheritDoc} */ @Override public CoordinateReferenceSystem getResponseCRS() throws FactoryException { if (output == null || output.getGridCRS() == null || output.getGridCRS().getSrsName() == null || output.getGridCRS().getSrsName().getValue() == null) { return null; } final CoordinateReferenceSystem objCrs = CRS.forCode(output.getGridCRS().getSrsName().getValue()); final BoundingBoxType boundingBox = domainSubset.getBoundingBox().getValue(); /* * If the bounding box contains at least 3 dimensions and the CRS specified is just * a 2D one, then we have to add a VerticalCRS to the one gotten by the crs decoding step. * Otherwise the CRS decoded is already fine, and we just return it. */ if (boundingBox.getDimensions().intValue() > 2 && objCrs.getCoordinateSystem().getDimension() < 3) { final VerticalCRS verticalCRS = CommonCRS.Vertical.ELLIPSOIDAL.crs(); return new GeodeticObjectBuilder() .addName(objCrs.getName().getCode() + " (3D)") .createCompoundCRS(objCrs, verticalCRS); } else { return objCrs; } }
MultiPolygon reprojectRoiArea( CoordinateReferenceSystem maskCrs, CoordinateReferenceSystem resourceCrs, MultiPolygon roiArea) { try { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Mask layer CRS: " + maskCrs.getName()); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Resource CRS: " + resourceCrs.getName()); } if ((resourceCrs != null) && !CRS.equalsIgnoreMetadata(maskCrs, resourceCrs)) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Mask and Resource CRS differ, ROI area will be reprojected"); } MathTransform mt = CRS.findMathTransform(maskCrs, resourceCrs, true); return (MultiPolygon) JTS.transform(roiArea, mt); } else { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Mask and Resource CRS coincide, no reprojection is necessary"); } } } catch (Exception e) { throw new RuntimeException( "Failed to reproject the restricted area to the layer's native SRS", e); } return roiArea; }
/** {@inheritDoc} */ @Override public CoordinateReferenceSystem getCRS() throws FactoryException { if (domainSubset == null || domainSubset.getBoundingBox() == null) { return null; } final BoundingBoxType boundingBox = domainSubset.getBoundingBox().getValue(); final CoordinateReferenceSystem objCrs = AbstractCRS.castOrCopy(CRS.forCode(boundingBox.getCrs())) .forConvention(AxesConvention.RIGHT_HANDED); // final List<DirectPositionType> positions = // domainSubset.getSpatialSubSet().getEnvelope().getPos(); /* * If the bounding box contains at least 3 dimensions and the CRS specified is just * a 2D one, then we have to add a VerticalCRS to the one gotten by the crs decoding step. * Otherwise the CRS decoded is already fine, and we just return it. */ if (boundingBox.getUpperCorner().size() > 2 && objCrs.getCoordinateSystem().getDimension() < 3) { final VerticalCRS verticalCRS = CommonCRS.Vertical.ELLIPSOIDAL.crs(); return new GeodeticObjectBuilder() .addName(objCrs.getName().getCode() + " (3D)") .createCompoundCRS(objCrs, verticalCRS); } else { return objCrs; } }
/** * @param dataStore A ShapeFileDataStore containing geometries to convert. * @param keyAttributes The names of attributes to be concatenated to generate record keys. * @throws Exception */ public static void convertFeatures( GeometryStreamConverter converter, ShapefileDataStore dataStore, List<String> keyAttributes) throws Exception { SimpleFeatureType schema = dataStore.getSchema(); int numFeatures = dataStore.getCount(Query.ALL); FeatureReader<SimpleFeatureType, SimpleFeature> reader = null; try { List<AttributeDescriptor> attrDesc = schema.getAttributeDescriptors(); String header = "\"the_geom_id\", \"the_geom_key\""; for (int i = 1; i < attrDesc.size(); i++) { String colName = attrDesc.get(i).getLocalName(); if (GeometryStreamConverter.debugDBF) header += ", \"" + colName + '"'; // if any specified attribute matches colName, case insensitive, overwrite specified // attribute name with name having correct case for (int j = 0; j < keyAttributes.size(); j++) if (keyAttributes.get(j).equalsIgnoreCase(colName)) keyAttributes.set(j, colName); } // debug: read schema and print it out if (GeometryStreamConverter.debugDBF) System.out.println(header); // loop through features and parse them long startTime = System.currentTimeMillis(), endTime = startTime, debugInterval = 60000, nextDebugTime = startTime + debugInterval; int featureCount = 0; reader = dataStore.getFeatureReader(); CoordinateReferenceSystem projection = schema.getCoordinateReferenceSystem(); // may be null String projectionWKT = projection == null ? null : projection.toWKT(); while (reader.hasNext()) { endTime = System.currentTimeMillis(); if (GeometryStreamConverter.debugTime && endTime > nextDebugTime) { System.out.println( String.format( "Processing %s/%s features, %s minutes elapsed", featureCount, numFeatures, (endTime - startTime) / 60000.0)); while (endTime > nextDebugTime) nextDebugTime += debugInterval; } convertFeature(converter, reader.next(), keyAttributes, projectionWKT); featureCount++; } if (GeometryStreamConverter.debugTime && endTime - startTime > debugInterval) System.out.println( String.format( "Processing %s features completed in %s minutes", numFeatures, (endTime - startTime) / 60000.0)); } catch (OutOfMemoryError e) { e.printStackTrace(); throw e; } finally { try { if (reader != null) reader.close(); } catch (IOException e) { } } }
/** TODO: Test me ! And move me to CRS utility class */ private static String srs(CoordinateReferenceSystem crs) { if (crs != null && crs.getIdentifiers() != null) for (Identifier id : crs.getIdentifiers()) { String srs = id.toString(); if (srs.startsWith("EPSG")) return srs; // $NON-NLS-1$ } return "EPSG:4326"; //$NON-NLS-1$ }
public void testCRSEquals() throws Exception { CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84; CoordinateReferenceSystem crs2 = CRS.parseWKT(crs.toWKT()); assertTrue(CRS.equalsIgnoreMetadata(crs, crs2)); }
/** * Determine the number of dimensions based on the CRS metadata. * * @return Number of dimensions expected based on metadata, default of 2 */ int getD() { CoordinateReferenceSystem crs = (CoordinateReferenceSystem) parameter.metadata.get(Parameter.CRS); if (crs == null) { return 2; } else { return crs.getCoordinateSystem().getDimension(); } }
/** * Convenience method for checking coordinate reference system validity. * * @param crs The coordinate reference system to check. * @param expected the dimension expected. * @throws MismatchedDimensionException if the CRS dimension is not valid. */ static void checkCoordinateReferenceSystemDimension( final CoordinateReferenceSystem crs, final int expected) throws MismatchedDimensionException { if (crs != null) { final int dimension = crs.getCoordinateSystem().getDimension(); if (dimension != expected) { throw new MismatchedDimensionException( Errors.format( ErrorKeys.MISMATCHED_DIMENSION_$3, crs.getName().getCode(), dimension, expected)); } } }
/** * Transforms the geometry to the storage EPSG code * * @param geometry Geometry to transform * @return Transformed geometry * @throws OwsExceptionReport */ public Geometry transformToStorageEpsg(final Geometry geometry) throws OwsExceptionReport { if (geometry != null && !geometry.isEmpty()) { CoordinateReferenceSystem sourceCRS = getCRS(geometry.getSRID()); int targetSRID; if (sourceCRS.getCoordinateSystem().getDimension() == 3) { targetSRID = getStorage3DEPSG(); } else { targetSRID = getStorageEPSG(); } return transform(geometry, targetSRID, sourceCRS, getCRS(targetSRID)); } return geometry; }
/** * Provides a complete set of the known codes provided by this authority. The returned set * contains only numeric identifiers like {@code "84"}, {@code "27"}, <cite>etc</cite>. The * authority name ({@code "CRS"}) is not included. This is consistent with the {@linkplain * org.geotools.referencing.factory.epsg.DirectEpsgFactory#getAuthorityCodes codes returned by the * EPSG factory} and avoid duplication, since the authority is the same for every codes returned * by this factory. It also make it easier for clients to prepend whatever authority name they * wish, as for example in the {@linkplain * org.geotools.referencing.factory.AllAuthoritiesFactory#getAuthorityCodes all authorities * factory}. */ public Set getAuthorityCodes(final Class type) throws FactoryException { ensureInitialized(); final Set set = new LinkedHashSet(); for (final Iterator it = crsMap.entrySet().iterator(); it.hasNext(); ) { final Map.Entry entry = (Map.Entry) it.next(); final CoordinateReferenceSystem crs = (CoordinateReferenceSystem) entry.getValue(); if (type.isAssignableFrom(crs.getClass())) { final Integer code = (Integer) entry.getKey(); set.add(String.valueOf(code)); } } return set; }
/** Returns a hash value for the given coordinate. */ static int hashCode(final DirectPosition position) { final int dimension = position.getDimension(); int code = 1; for (int i = 0; i < dimension; i++) { final long bits = Double.doubleToLongBits(position.getOrdinate(i)); code = 31 * code + ((int) (bits) ^ (int) (bits >>> 32)); } final CoordinateReferenceSystem crs = position.getCoordinateReferenceSystem(); if (crs != null) { code += crs.hashCode(); } return code; }
/** * Transforms the referenced envelope to the specified coordinate reference system using the * specified amount of points. * * <p>This method can handle the case where the envelope contains the North or South pole, or when * it cross the ±180� longitude. * * @param targetCRS The target coordinate reference system. * @param lenient {@code true} if datum shift should be applied even if there is insuffisient * information. Otherwise (if {@code false}), an exception is thrown in such case. * @param numPointsForTransformation The number of points to use for sampling the envelope. * @return The transformed envelope. * @throws FactoryException if the math transform can't be determined. * @throws TransformException if at least one coordinate can't be transformed. * @see CRS#transform(CoordinateOperation, org.opengis.geometry.Envelope) * @since 2.3 */ public ReferencedEnvelope transform( final CoordinateReferenceSystem targetCRS, final boolean lenient, final int numPointsForTransformation) throws TransformException, FactoryException { if (crs == null) { if (isEmpty()) { // We don't have a CRS yet because we are still empty, being empty is // something we can represent in the targetCRS return new ReferencedEnvelope(targetCRS); } else { // really this is a the code that created this ReferencedEnvelope throw new NullPointerException( "Unable to transform referenced envelope, crs has not yet been provided."); } } if (getDimension() != targetCRS.getCoordinateSystem().getDimension()) { if (lenient) { return JTS.transformTo3D(this, targetCRS, lenient, numPointsForTransformation); } else { throw new MismatchedDimensionException( Errors.format( ErrorKeys.MISMATCHED_DIMENSION_$3, crs.getName().getCode(), new Integer(getDimension()), new Integer(targetCRS.getCoordinateSystem().getDimension()))); } } /* * Gets a first estimation using an algorithm capable to take singularity in account * (North pole, South pole, 180� longitude). We will expand this initial box later. */ CoordinateOperationFactory coordinateOperationFactory = CRS.getCoordinateOperationFactory(lenient); final CoordinateOperation operation = coordinateOperationFactory.createOperation(crs, targetCRS); final GeneralEnvelope transformed = CRS.transform(operation, this); transformed.setCoordinateReferenceSystem(targetCRS); /* * Now expands the box using the usual utility methods. */ final ReferencedEnvelope target = new ReferencedEnvelope(transformed); final MathTransform transform = operation.getMathTransform(); JTS.transform(this, target, transform, numPointsForTransformation); return target; }
private void createFeatureType(String typeName, String srs) throws DataSourceException { CoordinateReferenceSystem crs = null; try { crs = CRS.decode(srs); } catch (Exception e) { throw new DataSourceException("Error parsing CoordinateSystem srs: \"" + srs + "\""); } int SRID = -1; if (crs != null) { try { Set ident = crs.getIdentifiers(); if ((ident != null && !ident.isEmpty())) { String code = ((NamedIdentifier) ident.toArray()[0]).getCode(); SRID = Integer.parseInt(code); } } catch (Exception e) { log.error("SRID could not be determined from crs!"); } } log.info("SRID used by SimpleFeature reader: " + SRID); try { SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder(); ftb.setName(typeName); ftb.setSRS(srs); ftb.add("the_geom", Geometry.class); ftb.add("name", String.class); ftb.add("key", String.class); ftb.add("urlLink", String.class); ftb.add("lineType", String.class); ftb.add("color", String.class); ftb.add("layer", String.class); ftb.add("thickness", Double.class); ftb.add("rotation", Double.class); ftb.add("visible", Integer.class); ftb.add("entryLineNumber", Integer.class); ftb.add("parseError", Integer.class); ftb.add("error", String.class); ftb.add("extendedData", Map.class); ft = ftb.buildFeatureType(); } catch (Exception e) { throw new DataSourceException("Error creating SimpleFeatureType: " + typeName, e); } }
/** * Utility method to create a ReferencedEnvelope from an JTS Envelope class, supporting 2d as well * as 3d envelopes (returning the right class). * * @param env The JTS Envelope object * @return ReferencedEnvelope, ReferencedEnvelope3D if it is 3d,<br> * results in a null/an empty envelope, if input envelope was a null/an empty envelope */ public static ReferencedEnvelope create(Envelope env, CoordinateReferenceSystem crs) { if (env == null) { return null; } if (crs.getCoordinateSystem().getDimension() >= 3) { if (env.isNull()) { return new ReferencedEnvelope3D(crs); } else { return new ReferencedEnvelope3D( env.getMinX(), env.getMaxX(), env.getMinY(), env.getMaxY(), Double.NaN, Double.NaN, crs); } } if (env.isNull()) { return new ReferencedEnvelope(crs); } else { return new ReferencedEnvelope(env, crs); } }
/** * Display the name of the coordinate reference system * * @param crs the CRS to display */ public void displayCRS(CoordinateReferenceSystem crs) { if (crs == null) { crsBtn.setText(stringRes.getString("crs_undefined")); } else { crsBtn.setText(crs.getName().toString()); } }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((crs == null) ? 0 : crs.hashCode()); return result; }
/** {@inheritDoc } */ @Override public double[] getResolution(final CoordinateReferenceSystem crs) { if (CRS.equalsIgnoreMetadata(objectiveCRS, crs)) { return getResolution(); } else { final double[] res = new double[crs.getCoordinateSystem().getDimension()]; final Envelope env; try { env = CRS.transform(canvasObjectiveBBox2D, crs); final Rectangle2D canvasCRSBounds = new Rectangle2D.Double(0, 0, env.getSpan(0), env.getSpan(1)); res[0] = Math.abs(canvasCRSBounds.getWidth() / canvasDisplaybounds.getWidth()); res[1] = Math.abs(canvasCRSBounds.getHeight() / canvasDisplaybounds.getHeight()); for (int i = 2; i < res.length; i++) { // other dimension are likely to be the temporal and elevation one. // we set a hug resolution to ensure that only one slice of data will be retrived. res[i] = Double.MAX_VALUE; } } catch (TransformException ex) { LOGGER.log(Level.WARNING, null, ex); } catch (IllegalArgumentException ex) { LOGGER.log(Level.WARNING, null, ex); } catch (Exception ex) { LOGGER.log(Level.WARNING, null, ex); } return adjustResolutionWithDPI(res); } }
/** * Transform geometry * * @param geometry Geometry to transform * @param targetSRID TargetEPSG code * @param sourceCRS Source CRS * @param targetCRS Target CRS * @return Transformed geometry * @throws OwsExceptionReport */ private Geometry transform( final Geometry geometry, final int targetSRID, final CoordinateReferenceSystem sourceCRS, final CoordinateReferenceSystem targetCRS) throws OwsExceptionReport { if (sourceCRS.equals(targetCRS)) { return geometry; } Geometry switchedCoordiantes = switchCoordinateAxisIfNeeded(geometry, targetSRID); try { MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS); Geometry transformed = JTS.transform(switchedCoordiantes, transform); transformed.setSRID(targetSRID); return transformed; } catch (FactoryException fe) { throw new NoApplicableCodeException() .causedBy(fe) .withMessage("The EPSG code '%s' is not supported!", switchedCoordiantes.getSRID()); } catch (MismatchedDimensionException mde) { throw new NoApplicableCodeException() .causedBy(mde) .withMessage("The EPSG code '%s' is not supported!", switchedCoordiantes.getSRID()); } catch (TransformException te) { throw new NoApplicableCodeException() .causedBy(te) .withMessage("The EPSG code '%s' is not supported!", switchedCoordiantes.getSRID()); } }
/** * Convenience method for checking coordinate reference system validity. * * @throws IllegalArgumentException if the CRS dimension is not valid. */ protected void checkCoordinateReferenceSystemDimension() throws MismatchedDimensionException { if (crs != null) { final int expected = getDimension(); final int dimension = crs.getCoordinateSystem().getDimension(); if (dimension > expected) { // check dimensions and choose ReferencedEnvelope or ReferencedEnvelope3D // or the factory method ReferencedEnvelope.reference( CoordinateReferenceSystem ) throw new MismatchedDimensionException( Errors.format( ErrorKeys.MISMATCHED_DIMENSION_$3, crs.getName().getCode(), new Integer(dimension), new Integer(expected))); } } }
/** * Fill the prj file with the actual map projection. * * @param filePath the path to the regarding data or prj file. * @param extention the extention of the data file. If <code>null</code>, the crs is written to * filePath directly. * @param crs the {@link CoordinateReferenceSystem} to write. * @throws IOException */ @SuppressWarnings("nls") public static void writeProjectionFile( String filePath, String extention, CoordinateReferenceSystem crs) throws IOException { /* * fill a prj file */ String prjPath = null; if (extention != null && filePath.toLowerCase().endsWith("." + extention)) { int dotLoc = filePath.lastIndexOf("."); prjPath = filePath.substring(0, dotLoc); prjPath = prjPath + ".prj"; } else { if (!filePath.endsWith(".prj")) { prjPath = filePath + ".prj"; } else { prjPath = filePath; } } BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new FileWriter(prjPath)); bufferedWriter.write(crs.toWKT()); } finally { if (bufferedWriter != null) bufferedWriter.close(); } }
void transformCoverage( final File sourceFile, final File file, final WcsReaderRequest targetRequest, final WcsReaderRequest executedRequest, final boolean handleFormatTranform) throws IOException { final CoordinateReferenceSystem original = targetRequest.responseCRS; CoordinateReferenceSystem actual = executedRequest.responseCRS; if (!CRS.equalsIgnoreMetadata(original, actual)) { try { LOG.info( "Need to reproject coverage from " + CRS.lookupIdentifier(actual, false) + " to " + CRS.lookupIdentifier(original, false)); } catch (FactoryException e) { LOG.info( "Need to reproject coverage from " + actual.getName() + " to " + original.getName()); } if (targetRequest.useCommandLineGDAL) { GDALCommandLine.gdalTransformation(sourceFile, file, executedRequest, targetRequest); } else { geotoolsTranformation(sourceFile, file, targetRequest, original); } LOG.info("Coverage reprojection/transformation complete"); } else if (handleFormatTranform) { if (targetRequest.useCommandLineGDAL) { GDALCommandLine.gdalTransformation(sourceFile, file, executedRequest, targetRequest); } else { // we need to re-implement convertFormat so it can handle non-world+image outputformats throw new UnsupportedOperationException( "We do not convert format from geotiff to another format yet in localReproject mode. Should be pretty easy to implement though"); } } else if (!sourceFile.equals(file)) { FileUtils.moveFile(sourceFile, file); } String name = file.getName().toLowerCase(); if (name.endsWith(".tif") || name.endsWith("tiff")) { // writeWorldImageExt(targetRequest, file); } }
/** * Returns a hash value for this envelope. This value need not remain consistent between different * implementations of the same class. */ @Override public int hashCode() { int code = super.hashCode() ^ (int) serialVersionUID; if (crs != null) { code ^= crs.hashCode(); } return code; }
/** * This test is currently broken. It's a placeholder for some logic that sfarber wrote which tries * to guess the SRS of a featureclass, based on connecting to it via an SeLayer. * * @throws Throwable */ @Test @Ignore public void testAutoFillSRS() throws Throwable { ArcSDEDataStore ds = testData.getDataStore(); CoordinateReferenceSystem sdeCRS = ds.getSchema("GISDATA.TOWNS_POLY").getGeometryDescriptor().getCoordinateReferenceSystem(); LOGGER.info(sdeCRS.toWKT().replaceAll(" ", "").replaceAll("\n", "").replaceAll("\"", "\\\"")); // CoordinateReferenceSystem epsgCRS = CRS.decode("EPSG:26986"); // LOGGER.info("are these two CRS's equal? " + // CRS.equalsIgnoreMetadata(sdeCRS, epsgCRS)); if (1 == 1) return; int epsgCode = -1; int[] projcs = PeFactory.projcsCodelist(); LOGGER.info(projcs.length + " projections available."); for (int i = 0; i < projcs.length; i++) { try { PeProjectedCS candidate = PeFactory.projcs(projcs[i]); // in ArcSDE 9.2, if the PeFactory doesn't support a projection // it claimed // to support, it returns 'null'. So check for it. if (candidate != null && candidate.getName().indexOf("Massachusetts") != -1) { // LOGGER.info("\n\n" + projcs[i] + " has name " + // candidate.getName() + "\ntried to match " + wktName + // "\n\n"); epsgCode = projcs[i]; } else if (candidate == null) { // LOGGER.info(projcs[i] + " was null"); } else if (candidate != null) { // LOGGER.info(projcs[i] + " wasn't null"); } } catch (PeProjectionException pe) { // Strangely SDE includes codes in the projcsCodeList() that // it doesn't actually support. // Catch the exception and skip them here. } } }
private void createPrjFile(CoordinateReferenceSystem crs, String baseFilename) throws FileNotFoundException { LOG.debug("Writing PRJ file: " + baseFilename + ".prj"); PrintWriter out = new PrintWriter(new FileOutputStream(baseFilename + ".prj")); try { out.write(crs.toWKT()); out.flush(); } finally { out.close(); } }
/** * Compara las proyecciones de la vista y la capa. En caso de ser diferentes pregunta por las * opciones a realizar. * * @param lyr * @param mapControl */ private void compareProjections(FLyrRasterSE lyr) { CoordinateReferenceSystem viewCrs = getMapControl().getCrs(); CoordinateReferenceSystem lyrCrs = lyr.readProjection(); if (lyrCrs == null) { lyr.setCrs(viewCrs); actionList.add(new Integer(defaultActionLayer)); return; } if (viewCrs == null) { getMapControl().setCrs(lyrCrs); actionList.add(new Integer(defaultActionLayer)); return; } /* * Si las proyecciones de vista y raster son distintas se lanza el * dialogo de selección de opciones. Este dialogo solo se lanza en caso * de que el checkbox de aplicar a todos los ficheros no haya sido * marcado. En este caso para el resto de ficheros de esa selección se * hará la misma acción que se hizo para el primero. */ if (!viewCrs.getName().equals(lyrCrs.getName())) { boolean showDialog = false; if (!RasterProjectionActionsPanel.selectAllFiles) showDialog = true; if (showDialog) { dialog = new RasterProjectionActionsDialog(lyr); } else { if (defaultActionLayer == FileOpenRaster.REPROJECT && !lyr.isReproyectable()) dialog = new RasterProjectionActionsDialog(lyr); } int select = defaultActionLayer; if (dialog != null) select = dialog.getRasterProjectionActionsPanel().getSelection(); actionList.add(new Integer(select)); return; } actionList.add(new Integer(defaultActionLayer)); }
public void updatePixelUnit(CoordinateReferenceSystem crs) { final CoordinateSystem coordinateSystem = crs.getCoordinateSystem(); final String unitX = coordinateSystem.getAxis(0).getUnit().toString(); if (!unitX.equals(pixelXUnit.getText())) { pixelXUnit.setText(unitX); pixelSizeXField.setValue(unitMap.get(unitX)); } final String unitY = coordinateSystem.getAxis(1).getUnit().toString(); if (!unitY.equals(pixelYUnit.getText())) { pixelYUnit.setText(unitY); pixelSizeYField.setValue(unitMap.get(unitY)); } }
public void fixPrjFile() throws IOException { CoordinateReferenceSystem crs = readPrjToCRS(); if (crs == null) { return; } try { CoordinateReferenceSystem epsgCrs = null; Integer epsgCode = EPSG_LOOKUP_CACHE.lookupEPSGCode(crs); if (epsgCode != null) { epsgCrs = CRS.decode("EPSG:" + epsgCode); } if (epsgCrs != null) { String epsgWKT = epsgCrs.toWKT(); try (PrintStream printStream = new PrintStream(getPrjFile().out())) { printStream.print(epsgWKT); } } } catch (FactoryException e) { throw (IOException) new IOException().initCause(e); } }
public void testPrimFactCRS() throws UnsupportedOperationException, FactoryException { CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84; GeometryBuilder builder = new GeometryBuilder(crs); CoordinateReferenceSystem crs2 = CRS.parseWKT(crs.toWKT()); GeometryBuilder builder2 = new GeometryBuilder(crs2); // create a list of connected positions List<Position> dps = new ArrayList<Position>(); dps.add(builder.createDirectPosition(new double[] {20, 10})); dps.add(builder.createDirectPosition(new double[] {40, 10})); dps.add(builder.createDirectPosition(new double[] {50, 40})); dps.add(builder.createDirectPosition(new double[] {30, 50})); dps.add(builder.createDirectPosition(new double[] {10, 30})); dps.add(builder.createDirectPosition(new double[] {20, 10})); // create linestring from directpositions LineString line = builder.createLineString(dps); // create curvesegments from line ArrayList<CurveSegment> segs = new ArrayList<CurveSegment>(); segs.add(line); // Create list of OrientableCurves that make up the surface OrientableCurve curve = builder.createCurve(segs); List<OrientableCurve> orientableCurves = new ArrayList<OrientableCurve>(); orientableCurves.add(curve); // create the interior ring and a list of empty interior rings (holes) Ring extRing = builder2.createRing(orientableCurves); List<Ring> intRings = new ArrayList<Ring>(); // create the surfaceboundary from the rings SurfaceBoundary sb = builder2.createSurfaceBoundary(extRing, intRings); // create the surface Surface surface = builder2.createSurface(sb); }