Ejemplo n.º 1
0
  public static SimpleFeatureType toReShapeFeatureType(
      SimpleFeatureCollection delegate, List<Definition> definitionList) {

    SimpleFeature sample = null;
    SimpleFeatureIterator iterator = delegate.features();
    try {
      if (iterator.hasNext()) {
        sample = iterator.next();
      }
    } finally {
      iterator.close(); // good bye
    }

    SimpleFeatureTypeBuilder build = new SimpleFeatureTypeBuilder();
    SimpleFeatureType origional = delegate.getSchema();

    for (Definition def : definitionList) {
      String name = def.name;
      Expression expression = def.expression;

      Object value = null;
      if (sample != null) {
        value = expression.evaluate(sample);
      }
      Class<?> binding = def.binding; // make use of any default binding hint provided by user
      if (value == null) {
        if (expression instanceof PropertyName) {
          PropertyName propertyName = (PropertyName) expression;
          String path = propertyName.getPropertyName();
          AttributeDescriptor descriptor = origional.getDescriptor(name);
          AttributeType attributeType = descriptor.getType();
          binding = attributeType.getBinding();
        }
      } else {
        binding = value.getClass();
      }

      if (binding == null) {
        // note we could consider scanning through additional samples until we get a non null hit
        throw new IllegalArgumentException("Unable to determine type for " + name);
      }

      if (Geometry.class.isAssignableFrom(binding)) {
        CoordinateReferenceSystem crs;
        AttributeType originalAttributeType = origional.getType(name);
        if (originalAttributeType != null && originalAttributeType instanceof GeometryType) {
          GeometryType geometryType = (GeometryType) originalAttributeType;
          crs = geometryType.getCoordinateReferenceSystem();
        } else {
          crs = origional.getCoordinateReferenceSystem();
        }
        build.crs(crs);
        build.add(name, binding);
      } else {
        build.add(name, binding);
      }
    }
    build.setName(origional.getTypeName());
    return build.buildFeatureType();
  }
Ejemplo n.º 2
0
  /**
   * Creates a Query to be executed over a registered ArcSDE layer (whether it is from a table or a
   * spatial view).
   *
   * @param session the session the query works over. As its managed by the calling code its the
   *     calling code responsibility to close it when done.
   * @param fullSchema
   * @param query
   * @param isMultiversioned whether the table is versioned, if so, the default version and current
   *     state will be used for the SeQuery
   * @return
   * @throws IOException
   */
  public static ArcSDEQuery createQuery(
      final ISession session,
      final SimpleFeatureType fullSchema,
      final Query query,
      final FIDReader fidReader,
      final ArcSdeVersionHandler versioningHandler)
      throws IOException {

    Filter filter = query.getFilter();

    LOGGER.fine("Creating new ArcSDEQuery");

    final String typeName = fullSchema.getTypeName();
    final SeTable sdeTable = session.getTable(typeName);
    final SeLayer sdeLayer;
    if (fullSchema.getGeometryDescriptor() == null) {
      sdeLayer = null;
    } else {
      sdeLayer = session.getLayer(typeName);
    }
    // create the set of filters to work over
    final ArcSDEQuery.FilterSet filters =
        new ArcSDEQuery.FilterSet(sdeTable, sdeLayer, filter, fullSchema, null, null, fidReader);

    final Filter unsupportedFilter = filters.getUnsupportedFilter();
    final String[] queryProperties = query.getPropertyNames();
    final SimpleFeatureType querySchema =
        getQuerySchema(queryProperties, unsupportedFilter, fullSchema);

    final String sortByClause = buildSortByClause(fullSchema, query.getSortBy(), fidReader);
    final ArcSDEQuery sdeQuery;
    sdeQuery =
        new ArcSDEQuery(session, querySchema, filters, sortByClause, fidReader, versioningHandler);
    return sdeQuery;
  }
Ejemplo n.º 3
0
  private GeometryProjector makeGeometryProjecter(String projectionName)
      throws AlgorithmExecutionException {
    SimpleFeatureType featureSchema = featureCollection.getSchema();
    CoordinateReferenceSystem originalCRS = featureSchema.getCoordinateReferenceSystem();

    return new GeometryProjector(originalCRS, projectionName);
  }
  public FeatureCollection<SimpleFeatureType, SimpleFeature> getVersionedFeatures(Query query)
      throws IOException {
    final SimpleFeatureType ft = getSchema();

    // check the feature type is the right one
    final String typeName = ft.getTypeName();
    if (query.getTypeName() != null && !query.getTypeName().equals(typeName))
      throw new IOException("Incompatible type, this class can access only " + typeName);

    // make sure the view is around
    if (!Arrays.asList(store.wrapped.getTypeNames()).contains(store.getVFCViewName(typeName)))
      store.createVersionedFeatureCollectionView(typeName);

    // we have to hit the view
    DefaultQuery vq = new DefaultQuery(query);
    vq.setTypeName(VersionedPostgisDataStore.getVFCViewName(typeName));
    vq = store.buildVersionedQuery(vq);
    FeatureCollection<SimpleFeatureType, SimpleFeature> fc =
        store
            .wrapped
            .getFeatureSource(VersionedPostgisDataStore.getVFCViewName(typeName))
            .getFeatures(vq);
    final SimpleFeatureType fcSchema = fc.getSchema();
    // build a renamed feature type with the same attributes as the feature collection
    SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
    builder.init(ft);
    builder.setAttributes(fc.getSchema().getAttributeDescriptors());
    SimpleFeatureType renamedFt = builder.buildFeatureType();
    return new ReTypingFeatureCollection(fc, renamedFt);
  }
  @Override
  public void createSchema(SimpleFeatureType featureType) throws IOException {
    List<String> header = new ArrayList<String>();

    GeometryDescriptor geometryDescrptor = featureType.getGeometryDescriptor();
    if (geometryDescrptor != null
        && CRS.equalsIgnoreMetadata(
            DefaultGeographicCRS.WGS84, geometryDescrptor.getCoordinateReferenceSystem())
        && geometryDescrptor.getType().getBinding().isAssignableFrom(Point.class)) {
      header.add(this.latField);
      header.add(this.lngField);
    } else {
      throw new IOException(
          "Unable use '"
              + this.latField
              + "' / '"
              + this.lngField
              + "' to represent "
              + geometryDescrptor);
    }
    for (AttributeDescriptor descriptor : featureType.getAttributeDescriptors()) {
      if (descriptor instanceof GeometryDescriptor) continue;
      header.add(descriptor.getLocalName());
    }
    // Write out header, producing an empty file of the correct type
    CsvWriter writer = new CsvWriter(new FileWriter(this.csvFileState.getFile()), ',');
    try {
      writer.writeRecord(header.toArray(new String[header.size()]));
    } finally {
      writer.close();
    }
  }
 @Override
 public SimpleFeature decode(String recordId, String[] csvRecord) {
   SimpleFeatureType featureType = getFeatureType();
   SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType);
   GeometryDescriptor geometryDescriptor = featureType.getGeometryDescriptor();
   GeometryFactory geometryFactory = new GeometryFactory();
   Double lat = null, lng = null;
   String[] headers = csvFileState.getCSVHeaders();
   for (int i = 0; i < headers.length; i++) {
     String header = headers[i];
     if (i < csvRecord.length) {
       String value = csvRecord[i].trim();
       if (geometryDescriptor != null && header.equals(latField)) {
         lat = Double.valueOf(value);
       } else if (geometryDescriptor != null && header.equals(lngField)) {
         lng = Double.valueOf(value);
       } else {
         builder.set(header, value);
       }
     } else {
       builder.set(header, null);
     }
   }
   if (geometryDescriptor != null && lat != null && lng != null) {
     Coordinate coordinate = new Coordinate(lng, lat);
     Point point = geometryFactory.createPoint(coordinate);
     builder.set(geometryDescriptor.getLocalName(), point);
   }
   return builder.buildFeature(csvFileState.getTypeName() + "-" + recordId);
 }
  @Test
  public void testWFSTransactionInsert() throws Exception {
    TransactionType t = WfsFactory.eINSTANCE.createTransactionType();
    InsertElementType ie = WfsFactory.eINSTANCE.createInsertElementType();
    t.getInsert().add(ie);

    // ie.setSrsName(new URI("epsg:4326"));

    BoundingBox expected =
        new ReferencedEnvelope(53.73, 40, -60, -95.1193, CRS.decode("EPSG:4326"));

    SimpleFeatureType ft = createNiceMock(SimpleFeatureType.class);
    expect(ft.getTypeName()).andReturn("acme:foo").anyTimes();
    replay(ft);

    SimpleFeature f = createNiceMock(SimpleFeature.class);
    expect(f.getBounds()).andReturn(expected).anyTimes();
    expect(f.getType()).andReturn(ft).anyTimes();
    replay(f);

    ie.getFeature().add(f);

    Operation op = op("Transaction", "WFS", "1.1.0", t);
    callback.operationDispatched(new Request(), op);

    assertEquals("acme:foo", data.getResources().get(0));

    // xMin,yMin -95.1193,40 : xMax,yMax -60,53.73
    BBoxAsserts.assertEqualsBbox(expected, data.getBbox(), 0.01);
  }
  public IGeoResource createResource(Object param) throws IOException {
    SimpleFeatureType featureType = (SimpleFeatureType) param;

    IService service = getMemoryService();

    MemoryDataStore ds = service.resolve(MemoryDataStore.class, new NullProgressMonitor());
    if (Arrays.asList(ds.getTypeNames()).contains(featureType.getName().getLocalPart()))
      ds.updateSchema(featureType.getName().getLocalPart(), featureType);
    else ds.createSchema(featureType);

    IGeoResource resource = null;
    for (IResolve resolve : service.resources(new NullProgressMonitor())) {
      if (resolve instanceof IGeoResource) {
        IGeoResource r = (IGeoResource) resolve;
        if (r.resolve(SimpleFeatureType.class, new NullProgressMonitor())
            .getName()
            .getLocalPart()
            .equals(featureType.getName().getLocalPart())) {
          resource = r;
          break;
        }
      }
    }
    return resource;
  }
  /**
   * Next Feature from reader or new content.
   *
   * @see org.geotools.data.FeatureWriter#next()
   */
  public SimpleFeature next() throws IOException {
    SimpleFeatureType type = getFeatureType();
    if (hasNext()) {
      // hasNext() will take care recording
      // any modifications to current
      try {
        live = next; // update live value
        next = null; // hasNext will need to search again
        current = SimpleFeatureBuilder.copy(live);

        return current;
      } catch (IllegalAttributeException e) {
        throw (IOException) new IOException("Could not modify content").initCause(e);
      }
    } else {
      // Create new content
      // created with an empty ID
      // (The real writer will supply a FID later)
      try {
        live = null;
        next = null;
        current =
            SimpleFeatureBuilder.build(
                type, new Object[type.getAttributeCount()], "new" + diff.nextFID);
        diff.nextFID++;
        return current;
      } catch (IllegalAttributeException e) {
        throw new IOException("Could not create new content");
      }
    }
  }
  /**
   * This method joins the feature type with the types maintained by this object. Geometry attribute
   * is not added into the join geometry. It must be computed by the client and setted using the
   * setGeometry Method.
   *
   * @see setGeometry
   * @param featureType
   */
  public FeatureTypeUnionBuilder add(final SimpleFeatureType featureType) {

    // adds the attribute types of this feature type, if there are name
    // collisions
    // the method appends the number "2" at the name to avoid name
    // duplication.
    // The geometry attribute will be omitted.
    for (int i = 0; i < featureType.getAttributeCount(); i++) {

      AttributeDescriptor attributeType = featureType.getDescriptor(i);
      if (!(attributeType instanceof GeometryDescriptor)) {

        String attrUnionName = attributeType.getLocalName();
        if (this.mapUnionAttributes.containsKey(attrUnionName)) {
          StringBuffer duplicatedName = new StringBuffer(attrUnionName);
          duplicatedName.append("2");

          attrUnionName = duplicatedName.toString();
        }
        AttributeTypeBuilder builder = new AttributeTypeBuilder();
        builder.setBinding(attributeType.getType().getBinding());
        builder.setNillable(attributeType.isNillable());

        AttributeDescriptor newAttribute = builder.buildDescriptor(attrUnionName);

        mapUnionAttributes.put(attrUnionName, newAttribute);
        mapOriginalUnion.put(
            new UnionKey(featureType.getTypeName(), attributeType.getLocalName()), attrUnionName);
      }
    }
    return this;
  }
    private void collectAttributes(
        SimpleFeatureType schema, List<String> retainedAttributes, SimpleFeatureTypeBuilder tb) {
      for (AttributeDescriptor descriptor : schema.getAttributeDescriptors()) {
        // check whether descriptor has been selected in the attribute list
        boolean isInRetainList = true;
        if (retainedAttributes != null) {

          isInRetainList = retainedAttributes.contains(descriptor.getLocalName());
          logger.fine("Checking " + descriptor.getLocalName() + " --> " + isInRetainList);
        }
        if (!isInRetainList || schema.getGeometryDescriptor() == descriptor) {
          continue;
        }

        // build the attribute to return
        AttributeTypeBuilder builder = new AttributeTypeBuilder();
        builder.setName(schema.getName().getLocalPart() + "_" + descriptor.getName());
        builder.setNillable(descriptor.isNillable());
        builder.setBinding(descriptor.getType().getBinding());
        builder.setMinOccurs(descriptor.getMinOccurs());
        builder.setMaxOccurs(descriptor.getMaxOccurs());
        builder.setDefaultValue(descriptor.getDefaultValue());
        builder.setCRS(schema.getCoordinateReferenceSystem());
        AttributeDescriptor intersectionDescriptor =
            builder.buildDescriptor(
                schema.getName().getLocalPart() + "_" + descriptor.getName(), descriptor.getType());
        tb.add(intersectionDescriptor);
        tb.addBinding(descriptor.getType());
      }
    }
Ejemplo n.º 12
0
  @Override
  public void postCreateFeatureType(
      SimpleFeatureType featureType, DatabaseMetaData metadata, String schemaName, Connection cx)
      throws SQLException {
    // figure out if the table has a spatial index and mark the feature type as so
    for (AttributeDescriptor ad : featureType.getAttributeDescriptors()) {
      if (!(ad instanceof GeometryDescriptor)) {
        continue;
      }

      GeometryDescriptor gd = (GeometryDescriptor) ad;
      String idxTableName = "idx_" + featureType.getTypeName() + "_" + gd.getLocalName();

      ResultSet rs =
          metadata.getTables(
              null,
              dataStore.escapeNamePattern(metadata, schemaName),
              dataStore.escapeNamePattern(metadata, idxTableName),
              new String[] {"TABLE"});
      try {
        if (rs.next()) {
          gd.getUserData().put(SPATIALITE_SPATIAL_INDEX, idxTableName);
        }
      } finally {
        dataStore.closeSafe(rs);
      }
    }
  }
Ejemplo n.º 13
0
 private static Object[] copyAttributes(
     SimpleFeatureType destSchema,
     SimpleFeature source,
     Map<String, Iterator<? extends Geometry>> geometries,
     Map<String, String> attributeMap,
     MathTransform mt) {
   Object[] attributes = new Object[destSchema.getAttributeCount()];
   for (int i = 0; i < attributes.length; i++) {
     String sourceAttributeName = destSchema.getDescriptor(i).getName().getLocalPart();
     String name = attributeMap.get(sourceAttributeName);
     if (name != null) attributes[i] = source.getAttribute(name);
     else {
       attributes[i] = destSchema.getDescriptor(i).getDefaultValue();
     }
     if (attributes[i] instanceof Geometry) {
       Class<? extends Geometry> geomType =
           (Class<? extends Geometry>) destSchema.getDescriptor(i).getType().getBinding();
       if (!geomType.isAssignableFrom(attributes[i].getClass())) {
         Collection<? extends Geometry> geom =
             createCompatibleGeometry((Geometry) attributes[i], geomType);
         Iterator<? extends Geometry> giter = geom.iterator();
         attributes[i] = giter.next();
         if (giter.hasNext()) geometries.put(sourceAttributeName, giter);
       }
       attributes[i] = transformGeom((Geometry) attributes[i], mt);
     }
   }
   return attributes;
 }
 @Override
 public PlacemarkDescriptor getPlacemarkDescriptor(SimpleFeatureType simpleFeatureType) {
   PlacemarkDescriptorRegistry placemarkDescriptorRegistry =
       PlacemarkDescriptorRegistry.getInstance();
   if (simpleFeatureType
       .getUserData()
       .containsKey(PlacemarkDescriptorRegistry.PROPERTY_NAME_PLACEMARK_DESCRIPTOR)) {
     String placemarkDescriptorClass =
         simpleFeatureType
             .getUserData()
             .get(PlacemarkDescriptorRegistry.PROPERTY_NAME_PLACEMARK_DESCRIPTOR)
             .toString();
     PlacemarkDescriptor placemarkDescriptor =
         placemarkDescriptorRegistry.getPlacemarkDescriptor(placemarkDescriptorClass);
     if (placemarkDescriptor != null) {
       return placemarkDescriptor;
     }
   }
   final PlacemarkDescriptor placemarkDescriptor =
       placemarkDescriptorRegistry.getPlacemarkDescriptor(simpleFeatureType);
   if (placemarkDescriptor != null) {
     return placemarkDescriptor;
   } else {
     return placemarkDescriptorRegistry.getPlacemarkDescriptor(GeometryDescriptor.class);
   }
 }
Ejemplo n.º 15
0
  public void testImportCSV() throws Exception {
    File dir = unpack("csv/locations.zip");
    ImportContext context = importer.createContext(new SpatialFile(new File(dir, "locations.csv")));
    assertEquals(1, context.getTasks().size());

    ImportTask task = context.getTasks().get(0);
    assertEquals(ImportTask.State.NO_CRS, task.getState());

    LayerInfo layer = task.getLayer();
    ResourceInfo resource = layer.getResource();
    resource.setSRS("EPSG:4326");

    assertTrue("Item not ready", importer.prep(task));
    assertEquals(ImportTask.State.READY, task.getState());

    context.updated();
    assertEquals(ImportContext.State.PENDING, context.getState());
    importer.run(context);
    assertEquals(ImportContext.State.COMPLETE, context.getState());
    FeatureTypeInfo fti = (FeatureTypeInfo) resource;
    SimpleFeatureType featureType = (SimpleFeatureType) fti.getFeatureType();
    GeometryDescriptor geometryDescriptor = featureType.getGeometryDescriptor();
    assertNull("Expecting no geometry", geometryDescriptor);
    assertEquals(4, featureType.getAttributeCount());
  }
Ejemplo n.º 16
0
  /**
   * Creates the resultant features.
   *
   * @param splitGeometries List with the new geometries.
   * @param feature The old feature.
   * @throws OperationNotFoundException
   * @throws TransformException
   */
  private List<SimpleFeature> createSplitFeatures(
      final List<Geometry> splitGeometries, final SimpleFeature feature)
      throws OperationNotFoundException, TransformException {

    final SimpleFeatureType featureType = feature.getFeatureType();
    final CoordinateReferenceSystem featureCrs = featureType.getCoordinateReferenceSystem();

    Class<? extends Geometry> geometryType =
        (Class<? extends Geometry>) featureType.getGeometryDescriptor().getType().getBinding();

    List<SimpleFeature> splitFeatureList = new LinkedList<SimpleFeature>();
    for (Geometry splittedPart : splitGeometries) {

      splittedPart = GeoToolsUtils.reproject(splittedPart, desiredCRS, featureCrs);

      splittedPart = GeometryUtil.adapt(splittedPart, geometryType);
      SimpleFeature newFeature = DataUtilities.template(featureType);
      GeoToolsUtils.copyAttributes(feature, newFeature);
      newFeature.setDefaultGeometry(splittedPart);

      splitFeatureList.add(newFeature);
    }

    return splitFeatureList;
  }
  public SimpleFeature next() throws IOException {
    if (writer == null) {
      throw new IOException("Writer has been closed");
    }
    String fid = null;
    SimpleFeatureType type = reader.type;
    try {
      if (hasNext()) {
        reader.next(); // grab next line

        fid = reader.getFeatureID();
        Object values[] = new Object[reader.getAttributeCount()];
        for (int i = 0; i < reader.getAttributeCount(); i++) {
          values[i] = reader.read(i);
        }

        origional = SimpleFeatureBuilder.build(type, values, fid);
        live = SimpleFeatureBuilder.copy(origional);
        return live;
      } else {
        fid = type.getName() + "." + System.currentTimeMillis();
        Object values[] = DataUtilities.defaultValues(type);

        origional = null;
        live = SimpleFeatureBuilder.build(type, values, fid);
        return live;
      }
    } catch (IllegalAttributeException e) {
      String message = "Problem creating feature " + (fid != null ? fid : "");
      throw new DataSourceException(message, e);
    }
  }
Ejemplo n.º 18
0
  /**
   * @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) {
      }
    }
  }
Ejemplo n.º 19
0
  private SimpleFeatureType createForceFeatureType(SimpleFeatureType featureType, String path) {
    SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
    builder.setAttributes(featureType.getAttributeDescriptors());
    builder.setName(new NameImpl(featureType.getName().getNamespaceURI(), path));
    builder.setCRS(featureType.getCoordinateReferenceSystem());

    featureType = builder.buildFeatureType();
    return featureType;
  }
Ejemplo n.º 20
0
 public CoordinateReferenceSystem getCoordinateReferenceSystem() {
   if (layerInfo != null) {
     return layerInfo.getResource().getCRS();
   }
   if (remoteFeatureSource != null) {
     SimpleFeatureType schema = remoteFeatureSource.getSchema();
     return schema.getCoordinateReferenceSystem();
   }
   throw new IllegalStateException();
 }
Ejemplo n.º 21
0
  @Override
  public void postCreateTable(String schemaName, SimpleFeatureType featureType, Connection cx)
      throws SQLException, IOException {

    // create any geometry columns entries after the fact
    for (AttributeDescriptor ad : featureType.getAttributeDescriptors()) {
      if (ad instanceof GeometryDescriptor) {
        GeometryDescriptor gd = (GeometryDescriptor) ad;
        StringBuffer sql = new StringBuffer("INSERT INTO geometry_columns VALUES (");

        // table name
        sql.append("'").append(featureType.getTypeName()).append("',");

        // geometry name
        sql.append("'").append(gd.getLocalName()).append("',");

        // type
        String gType =
            Geometries.getForBinding((Class<? extends Geometry>) gd.getType().getBinding())
                .getName();
        if (gType == null) {
          throw new IOException("Unknown geometry type: " + gd.getType().getBinding());
        }
        sql.append("'").append(gType).append("',");

        // coord dimension
        sql.append(2).append(",");

        // srid
        Integer epsgCode = null;
        if (gd.getCoordinateReferenceSystem() != null) {
          CoordinateReferenceSystem crs = gd.getCoordinateReferenceSystem();
          try {
            epsgCode = CRS.lookupEpsgCode(crs, true);
          } catch (Exception e) {
          }
        }
        if (epsgCode == null) {
          throw new IOException("Unable to find epsg code code.");
        }
        sql.append(epsgCode).append(",");

        // spatial index enabled
        sql.append(0).append(")");

        LOGGER.fine(sql.toString());
        Statement st = cx.createStatement();
        try {
          st.executeUpdate(sql.toString());
        } finally {
          dataStore.closeSafe(st);
        }
      }
    }
  }
Ejemplo n.º 22
0
  /** This time we mix some conflicting and non conflicting changes */
  public void testConflicts() throws Exception {
    VersioningFeatureStore restricted =
        (VersioningFeatureStore) synchStore.getFeatureSource("restricted");
    SimpleFeatureType schema = restricted.getSchema();
    // modify the fourth feature, change its cat from 400 to 450
    Id updateFilter =
        ff.id(singleton(ff.featureId("restricted.1b99be2b-2480-4742-ad52-95c294efda3b")));
    restricted.modifyFeatures(schema.getDescriptor("cat"), 450, updateFilter);
    // a update that will generate a conflict
    updateFilter =
        ff.id(singleton(ff.featureId("restricted.d91fe390-bdc7-4b22-9316-2cd6c8737ef5")));
    restricted.modifyFeatures(schema.getDescriptor("cat"), 347, updateFilter);
    // an update that will generate a clean merge
    updateFilter =
        ff.id(singleton(ff.featureId("restricted.be7cafea-d0b7-4257-9b9c-1ed3de3f7ef4")));
    restricted.modifyFeatures(schema.getDescriptor("cat"), -48, updateFilter);

    // execute the postDiff
    MockHttpServletResponse response =
        postAsServletResponse(root(true), loadTextResource("PostDiffInitial.xml"));
    checkPostDiffSuccessResponse(response);

    // check there is one conflict and one clean merge
    assertEquals(1, gss.getActiveConflicts("restricted").size());
    assertEquals(1, gss.getCleanMerges("restricted", 7).size());

    // run GetDiff
    response = postAsServletResponse(root(true), loadTextResource("GetDiffInitial.xml"));
    validate(response);
    Document dom = dom(response);
    // print(dom);

    // check the document contents are the expected ones
    // ... check the main element
    assertXpathEvaluatesTo("-1", "/gss:GetDiffResponse/@fromVersion", dom);
    assertXpathEvaluatesTo("7", "/gss:GetDiffResponse/@toVersion", dom);
    assertXpathEvaluatesTo("sf:restricted", "/gss:GetDiffResponse/@typeName", dom);
    // ... check we get only one change, the non conflicting one
    assertXpathEvaluatesTo("1", "count(/gss:GetDiffResponse/gss:Changes)", dom);
    // check the update one
    assertXpathEvaluatesTo(
        "sf:restricted", "/gss:GetDiffResponse/gss:Changes/wfs:Update/@typeName", dom);
    assertXpathEvaluatesTo(
        "1", "count(/gss:GetDiffResponse/gss:Changes/wfs:Update/ogc:Filter/ogc:FeatureId)", dom);
    assertXpathEvaluatesTo(
        "restricted.1b99be2b-2480-4742-ad52-95c294efda3b",
        "/gss:GetDiffResponse/gss:Changes/wfs:Update/ogc:Filter/ogc:FeatureId/@fid",
        dom);
    assertXpathEvaluatesTo(
        "1", "count(/gss:GetDiffResponse/gss:Changes/wfs:Update/wfs:Property)", dom);
    assertXpathEvaluatesTo(
        "cat", "/gss:GetDiffResponse/gss:Changes/wfs:Update/wfs:Property/wfs:Name", dom);
    assertXpathEvaluatesTo(
        "450", "/gss:GetDiffResponse/gss:Changes/wfs:Update/wfs:Property/wfs:Value", dom);
  }
  /**
   * Given a feature id following the <typename>.<internalId> convention, the original type and the
   * destination type, this converts the id from <original>.<internalid> to <target>.<internalid>
   *
   * @param id
   * @param original
   * @param target
   * @return
   */
  public static FeatureId reTypeId(
      FeatureId sourceId, SimpleFeatureType original, SimpleFeatureType target) {
    final String originalTypeName = original.getName().getLocalPart();
    final String destTypeName = target.getName().getLocalPart();
    if (destTypeName.equals(originalTypeName)) return sourceId;

    final String prefix = originalTypeName + ".";
    if (sourceId.getID().startsWith(prefix)) {
      return new FeatureIdImpl(destTypeName + "." + sourceId.getID().substring(prefix.length()));
    } else return sourceId;
  }
Ejemplo n.º 24
0
  /**
   * Provides a wrapper on the provided writer that checks locks.
   *
   * @param writer FeatureWriter requiring access control
   * @param transaction Transaction being used
   * @return FeatureWriter with lock checking
   */
  public FeatureWriter<SimpleFeatureType, SimpleFeature> checkedWriter(
      final FeatureWriter<SimpleFeatureType, SimpleFeature> writer, final Transaction transaction) {
    SimpleFeatureType featureType = writer.getFeatureType();
    final String typeName = featureType.getTypeName();

    return new DelegatingFeatureWriter<SimpleFeatureType, SimpleFeature>() {
      SimpleFeature live = null;

      public FeatureWriter<SimpleFeatureType, SimpleFeature> getDelegate() {
        return writer;
      }

      public SimpleFeatureType getFeatureType() {
        return writer.getFeatureType();
      }

      public SimpleFeature next() throws IOException {
        live = writer.next();

        return live;
      }

      public void remove() throws IOException {
        if (live != null) {
          assertAccess(typeName, live.getID(), transaction);
        }

        writer.remove();
        live = null;
      }

      public void write() throws IOException {
        if (live != null) {
          assertAccess(typeName, live.getID(), transaction);
        }

        writer.write();
        live = null;
      }

      public boolean hasNext() throws IOException {
        live = null;

        return writer.hasNext();
      }

      public void close() throws IOException {
        live = null;
        if (writer != null) writer.close();
      }
    };
  }
Ejemplo n.º 25
0
  public void testImportCSVIndirect() throws Exception {
    File dir = unpack("csv/locations.zip");
    String wsName = getCatalog().getDefaultWorkspace().getName();

    DataStoreInfo h2DataStore = createH2DataStore(wsName, "csvindirecttest");
    SpatialFile importData = new SpatialFile(new File(dir, "locations.csv"));

    ImportContext context = importer.createContext(importData, h2DataStore);
    assertEquals(1, context.getTasks().size());
    ImportTask task = context.getTasks().get(0);

    TransformChain transformChain = task.getTransform();
    transformChain.add(new AttributesToPointGeometryTransform("LAT", "LON"));
    assertEquals(ImportTask.State.NO_CRS, task.getState());

    LayerInfo layer = task.getLayer();
    ResourceInfo resource = layer.getResource();
    resource.setSRS("EPSG:4326");

    assertTrue("Item not ready", importer.prep(task));
    assertEquals(ImportTask.State.READY, task.getState());

    context.updated();
    assertEquals(ImportContext.State.PENDING, context.getState());
    importer.run(context);

    assertEquals(ImportContext.State.COMPLETE, context.getState());
    FeatureTypeInfo fti = (FeatureTypeInfo) resource;
    SimpleFeatureType featureType = (SimpleFeatureType) fti.getFeatureType();
    GeometryDescriptor geometryDescriptor = featureType.getGeometryDescriptor();
    assertNotNull("Expecting geometry", geometryDescriptor);
    assertEquals("Invalid geometry name", "location", geometryDescriptor.getLocalName());
    assertEquals(3, featureType.getAttributeCount());
    FeatureSource<? extends FeatureType, ? extends Feature> featureSource =
        fti.getFeatureSource(null, null);
    FeatureCollection<? extends FeatureType, ? extends Feature> features =
        featureSource.getFeatures();
    assertEquals(9, features.size());
    FeatureIterator<? extends Feature> featureIterator = features.features();
    assertTrue("Expected features", featureIterator.hasNext());
    SimpleFeature feature = (SimpleFeature) featureIterator.next();
    assertNotNull(feature);
    assertEquals("Invalid city attribute", "Trento", feature.getAttribute("CITY"));
    assertEquals("Invalid number attribute", 140, feature.getAttribute("NUMBER"));
    Object geomAttribute = feature.getAttribute("location");
    assertNotNull("Expected geometry", geomAttribute);
    Point point = (Point) geomAttribute;
    Coordinate coordinate = point.getCoordinate();
    assertEquals("Invalid x coordinate", 11.12, coordinate.x, 0.1);
    assertEquals("Invalid y coordinate", 46.07, coordinate.y, 0.1);
    featureIterator.close();
  }
 public void write() throws IOException {
   try {
     SimpleFeatureType target = getFeatureType();
     for (int i = 0; i < target.getAttributeCount(); i++) {
       AttributeDescriptor at = target.getDescriptor(i);
       Object value = retyped.getAttribute(i);
       current.setAttribute(at.getLocalName(), value);
     }
     delegate.write();
   } catch (IllegalAttributeException e) {
     throw (IOException) new IOException("Error occurred while retyping feature").initCause(e);
   }
 }
  /**
   * Creates a query that requests the features in sourceLayer as dictated by filter. Query only
   * requests the attributes that can be mapped from sourceLayer to targetLayer.
   *
   * @param queryAttributes populates with a mapping of attributeTypeNames from targetLayer to
   *     sourcelayer
   * @return
   */
  @SuppressWarnings("unchecked")
  private Query createQuery(
      ILayer sourceLayer, Filter filter, Layer targetLayer, Map<String, String> queryAttributes) {
    SimpleFeatureType sourceSchema = sourceLayer.getSchema();
    SimpleFeatureType targetSchema = targetLayer.getSchema();
    // Maps type names to type names since we are ignoring case

    queryAttributes.putAll(FeatureUtils.createAttributeMapping(sourceSchema, targetSchema));
    Set<String> properties = new HashSet(queryAttributes.values());
    return new DefaultQuery(
        sourceSchema.getName().getLocalPart(),
        filter,
        properties.toArray(new String[properties.size()]));
  }
Ejemplo n.º 28
0
  /**
   * Forces the specified CRS on geometry attributes (all or some, depends on the parameters).
   *
   * @param schema the original schema
   * @param crs the forced crs
   * @param forceOnlyMissing if true, will force the specified crs only on the attributes that do
   *     miss one
   * @return
   * @throws SchemaException
   */
  public static SimpleFeatureType transform(
      SimpleFeatureType schema, CoordinateReferenceSystem crs, boolean forceOnlyMissing)
      throws SchemaException {
    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
    tb.setName(schema.getTypeName());
    tb.setNamespaceURI(schema.getName().getNamespaceURI());
    tb.setAbstract(schema.isAbstract());

    GeometryDescriptor defaultGeometryType = null;
    for (int i = 0; i < schema.getAttributeCount(); i++) {
      AttributeDescriptor attributeType = schema.getDescriptor(i);
      if (attributeType instanceof GeometryDescriptor) {
        GeometryDescriptor geometryType = (GeometryDescriptor) attributeType;
        AttributeDescriptor forced;

        tb.descriptor(geometryType);
        if (!forceOnlyMissing || geometryType.getCoordinateReferenceSystem() == null) {
          tb.crs(crs);
        }

        tb.add(geometryType.getLocalName(), geometryType.getType().getBinding());
      } else {
        tb.add(attributeType);
      }
    }
    if (schema.getGeometryDescriptor() != null) {
      tb.setDefaultGeometry(schema.getGeometryDescriptor().getLocalName());
    }

    tb.setSuperType((SimpleFeatureType) schema.getSuper());

    return tb.buildFeatureType();
  }
Ejemplo n.º 29
0
  /**
   * Creates a flat FeatureType <code>wq_ir_results</code> with a structure like the following, from
   * which a complex one should be constructed grouping by station_no attribute.
   *
   * <p>Following this sample schema, a total of 10 unique station_no identifiers will be created,
   * and for each one, a total of N desagregate rows with the same station_no, where N goes from 1
   * to 10. So for the first station_no there will be just one occurrence and the last one will have
   * 10.
   *
   * <p>
   *
   * <table>
   * <tr>
   * <td> station_no (string) </td>
   * <td> sitename (string)</td>
   * <td> anzlic_no (string)</td>
   * <td> project_no (string)</td>
   * <td> id (string)</td>
   * <td> sample_collection_date (string)</td>
   * <td> determinand_description (string)</td>
   * <td> results_value (float)</td>
   * <td> location (Point)</td>
   * </tr>
   * <tr>
   * <td> station_1 </td>
   * <td> sitename_1 </td>
   * <td> anzlic_no_1 </td>
   * <td> project_no_1 </td>
   * <td> id_1_1 </td>
   * <td> sample_collection_date_1_1 </td>
   * <td> determinand_description_1_1 </td>
   * <td> 1.1 </td>
   * <td> POINT(1, 1) </td>
   * </tr>
   * <tr>
   * <td> station_2 </td>
   * <td> sitename_2 </td>
   * <td> anzlic_no_2 </td>
   * <td> project_no_2 </td>
   * <td> id_2_1 </td>
   * <td> sample_collection_date_2_1 </td>
   * <td> determinand_description_2_1 </td>
   * <td> 2.1 </td>
   * <td> POINT(2, 2) </td>
   * </tr>
   * <tr>
   * <td> station_2 </td>
   * <td> sitename_2 </td>
   * <td> anzlic_no_2 </td>
   * <td> project_no_2 </td>
   * <td> id_2_2 </td>
   * <td> sample_collection_date_2_2 </td>
   * <td> determinand_description_2_2 </td>
   * <td> 2.2 </td>
   * <td> POINT(2, 2) </td>
   * </tr>
   * <tr>
   * <td colspan="9">...</td>
   * </tr>
   * <tr>
   * <td> station_10 </td>
   * <td> sitename_10 </td>
   * <td> anzlic_no_10 </td>
   * <td> project_no_10 </td>
   * <td> id_10_10 </td>
   * <td> sample_collection_date_10_9 </td>
   * <td> determinand_description_10_9 </td>
   * <td> 10.10 </td>
   * <td> POINT(10, 10) </td>
   * </tr>
   * <tr>
   * <td> station_10 </td>
   * <td> sitename_10 </td>
   * <td> anzlic_no_10 </td>
   * <td> project_no_10 </td>
   * <td> id_10_10 </td>
   * <td> sample_collection_date_10_10 </td>
   * <td> determinand_description_10_10 </td>
   * <td> 10.10 </td>
   * <td> POINT(10, 10) </td>
   * </tr>
   * </table>
   *
   * @return
   * @throws Exception
   */
  public static MemoryDataStore createDenormalizedWaterQualityResults() throws Exception {
    MemoryDataStore dataStore = new MemoryDataStore();
    SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();

    builder.setName(TestData.WATERSAMPLE_TYPENAME.getLocalPart());

    builder.add("station_no", String.class);
    builder.add("sitename", String.class);
    builder.add("anzlic_no", String.class);
    builder.add("project_no", String.class);
    builder.add("id", String.class);
    builder.add("sample_collection_date", String.class);
    builder.add("determinand_description", String.class);
    builder.add("results_value", Float.class);
    builder.add("location", Point.class);

    SimpleFeatureType type = builder.buildFeatureType();

    dataStore.createSchema(type);

    final int NUM_STATIONS = 10;
    GeometryFactory gf = new GeometryFactory();

    SimpleFeatureBuilder fb = new SimpleFeatureBuilder(type);

    for (int groupValue = 1; groupValue <= NUM_STATIONS; groupValue++) {

      for (int measurement = 1; measurement <= groupValue; measurement++) {
        String fid = type.getName().getLocalPart() + "." + groupValue + "." + measurement;

        fb.add("station_no." + groupValue);
        fb.add("sitename" + groupValue);
        fb.add("anzlic_no" + groupValue);
        fb.add("project_no" + groupValue);

        String sufix = "_" + groupValue + "_" + measurement;
        fb.add("id" + sufix);
        fb.add("sample_collection_date" + sufix);
        fb.add("determinand_description" + sufix);
        fb.add(new Float(groupValue + "." + measurement));

        fb.add(gf.createPoint(new Coordinate(groupValue, groupValue)));

        SimpleFeature f = fb.buildFeature(fid);
        dataStore.addFeature(f);
      }
    }
    return dataStore;
  }
  // todo - add API doc describing what the method does (nf,ts - 2012-04-23)
  @Override
  public void setUserDataOf(SimpleFeatureType compatibleFeatureType) {

    compatibleFeatureType
        .getUserData()
        .put(PROPERTY_NAME_PLACEMARK_DESCRIPTOR, getClass().getName());

    final org.opengis.feature.type.GeometryDescriptor geometryDescriptor =
        compatibleFeatureType.getGeometryDescriptor();
    if (geometryDescriptor != null) {
      compatibleFeatureType
          .getUserData()
          .put(PROPERTY_NAME_DEFAULT_GEOMETRY, geometryDescriptor.getLocalName());
    }
  }