示例#1
0
  /**
   * 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();
    }
  }
  /**
   * @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) {
      }
    }
  }
  public void testCRSEquals() throws Exception {

    CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;

    CoordinateReferenceSystem crs2 = CRS.parseWKT(crs.toWKT());

    assertTrue(CRS.equalsIgnoreMetadata(crs, crs2));
  }
  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();
    }
  }
  /**
   * 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.
      }
    }
  }
示例#6
0
  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);
  }
  public static boolean createMapset(
      String locationPath, String mapset, CoordinateReferenceSystem crs, JGrassRegion window) {
    String path = locationPath + File.separator + mapset;

    /* Create mapset directory */
    if (!(new File(path).mkdirs())) return false;

    if (mapset.equals(JGrassConstants.PERMANENT_MAPSET)) {
      /* Create blank DEFAULT_WIND and WIND files */
      try {
        if (window != null) {
          JGrassRegion.writeWINDToMapset(path, window);
          JGrassRegion.writeDEFAULTWINDToLocation(locationPath, window);
        } else {
          // create blank windows
          BufferedWriter out =
              new BufferedWriter(
                  new FileWriter(path + File.separator + JGrassConstants.DEFAULT_WIND));
          out.write(JGrassRegion.BLACKBOARD_KEY);
          out.close();

          out = new BufferedWriter(new FileWriter(path + File.separator + JGrassConstants.WIND));
          out.write(JGrassRegion.BLANK_REGION);
          out.close();
        }

        /* Create projection files */
        if (crs != null) {
          // FIXME create GRASS proj files

          BufferedWriter prjOut =
              new BufferedWriter(new FileWriter(path + File.separator + JGrassConstants.PROJ_WKT));
          prjOut.write(crs.toWKT());
          prjOut.close();
        }
      } catch (IOException e) {
        JGrassPlugin.log(
            "JGrassPlugin problem: eu.hydrologis.udig.catalog.utils#JGrassCatalogUtilities#createMapset",
            e);
        e.printStackTrace();
        return false;
      }

    } else {
      /* Copy WIND file from PERMANENT mapset of this location */
      try {
        BufferedReader in =
            new BufferedReader(
                new FileReader(
                    locationPath
                        + File.separator
                        + JGrassConstants.PERMANENT_MAPSET
                        + File.separator
                        + JGrassConstants.DEFAULT_WIND));
        BufferedWriter out =
            new BufferedWriter(new FileWriter(path + File.separator + JGrassConstants.WIND));
        String line;
        while ((line = in.readLine()) != null) {
          out.write(line);
          out.write("\n");
        }
        out.close();
        in.close();
      } catch (IOException e) {
        JGrassPlugin.log(
            "JGrassPlugin problem: eu.hydrologis.udig.catalog.utils#JGrassCatalogUtilities#createMapset",
            e);
        e.printStackTrace();
        return false;
      }
    }

    /* Create point/site directories */
    if (!(new File(path + File.separator + JGrassConstants.SITE_LISTS).mkdirs())) return false;

    /* Create raster directories */
    if (!(new File(path + File.separator + JGrassConstants.FCELL).mkdirs())) return false;
    if (!(new File(path + File.separator + JGrassConstants.CELL).mkdirs())) return false;
    if (!(new File(path + File.separator + JGrassConstants.CELLHD).mkdirs())) return false;
    if (!(new File(path + File.separator + JGrassConstants.CATS).mkdirs())) return false;
    if (!(new File(path + File.separator + JGrassConstants.COLR).mkdirs())) return false;
    if (!(new File(path + File.separator + JGrassConstants.CELL_MISC).mkdirs())) return false;

    /* Create vector directories */
    if (!(new File(path + File.separator + JGrassConstants.DIG).mkdirs())) return false;
    if (!(new File(path + File.separator + JGrassConstants.DIG_ATTS).mkdirs())) return false;
    if (!(new File(path + File.separator + JGrassConstants.DIG_CATS).mkdirs())) return false;

    if (!createJGrassFolders(path)) return false;

    return true;
  }
示例#9
0
 @Override
 public void convertValueToDom(Object value, DomElement parentElement)
     throws ConversionException {
   CoordinateReferenceSystem crs = (CoordinateReferenceSystem) value;
   parentElement.setValue(crs.toWKT());
 }
 public String toWKT() throws UnsupportedOperationException {
   return base.toWKT();
 }