예제 #1
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;
 }
예제 #2
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);
  }
예제 #3
0
  /**
   * Checks if the feature type specified is a GridCoverage wrapper
   *
   * @param featureType
   * @return
   */
  public static boolean isWrappedCoverage(SimpleFeatureType featureType) {
    if (!"GridCoverage".equals(featureType.getName().getLocalPart())) return false;

    if (featureType.getAttributeCount() != 2) return false;

    AttributeDescriptor polyDescriptor = featureType.getDescriptor("geom");
    if (polyDescriptor == null || !Polygon.class.equals(polyDescriptor.getType().getBinding()))
      return false;

    AttributeDescriptor gridDescriptor = featureType.getDescriptor("grid");
    if (gridDescriptor == null || !GridCoverage.class.equals(gridDescriptor.getType().getBinding()))
      return false;

    return true;
  }
  /**
   * tests that the schema for the defined tests tables are returned.
   *
   * @throws IOException DOCUMENT ME!
   * @throws SeException
   */
  @Test
  public void testGetSchema() throws IOException, SeException {
    SimpleFeatureType schema;

    schema = store.getSchema(testData.getTempTableName());
    assertNotNull(schema);
    // ROW_ID is not included in TEST_TABLE_COLS
    assertEquals(TEST_TABLE_COLS.length, schema.getAttributeCount());

    for (int i = 0; i < TEST_TABLE_COLS.length; i++) {
      assertEquals("at index" + i, TEST_TABLE_COLS[i], schema.getDescriptor(i).getLocalName());
    }
    assertFalse(schema.getDescriptor(0).isNillable());
    assertTrue(schema.getDescriptor(1).isNillable());
  }
예제 #5
0
 /**
  * Compare input and output schemas for different case mapping in attribute names.
  *
  * @param destSchema
  * @param schema
  * @return
  */
 protected Map<String, String> compareSchemas(
     SimpleFeatureType destSchema, SimpleFeatureType schema) {
   Map<String, String> diffs = new HashMap<String, String>();
   for (AttributeDescriptor ad : destSchema.getAttributeDescriptors()) {
     String attribute = ad.getLocalName();
     if (schema.getDescriptor(attribute) == null) {
       for (String variant : getNameVariants(attribute)) {
         if (schema.getDescriptor(variant) != null) {
           diffs.put(attribute, variant);
           break;
         }
       }
     }
   }
   return diffs;
 }
예제 #6
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();
  }
  /**
   * 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;
  }
예제 #8
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();
  }
예제 #9
0
  /** Maps attributes with the same name and same types to each other. */
  @SuppressWarnings("unchecked")
  private static void performDirectMapping(
      SimpleFeatureType sourceSchema,
      SimpleFeatureType targetSchema,
      Map<String, String> queryAttributes) {
    for (int i = 0; i < sourceSchema.getAttributeCount(); i++) {
      AttributeDescriptor source = sourceSchema.getDescriptor(i);
      for (int j = 0; j < targetSchema.getAttributeCount(); j++) {
        AttributeDescriptor target = targetSchema.getDescriptor(j);

        // don't worry about case of attribute name
        if (target.getName().getLocalPart().equalsIgnoreCase(source.getName().getLocalPart())
            && target.getType().getBinding().isAssignableFrom(source.getType().getBinding())) {
          queryAttributes.put(target.getName().getLocalPart(), source.getName().getLocalPart());
        }
      }
    }
  }
예제 #10
0
 private void checkSchemaCorrect(SimpleFeatureType ft, boolean includeProportionColumns) {
   if (includeProportionColumns) {
     assertEquals(5, ft.getAttributeCount());
   } else {
     assertEquals(3, ft.getAttributeCount());
   }
   assertEquals(Point.class, ft.getGeometryDescriptor().getType().getBinding());
   assertEquals(
       Integer.class, ft.getDescriptor(PointStackerProcess.ATTR_COUNT).getType().getBinding());
   assertEquals(
       Integer.class,
       ft.getDescriptor(PointStackerProcess.ATTR_COUNT_UNIQUE).getType().getBinding());
   if (includeProportionColumns) {
     assertEquals(
         Double.class,
         ft.getDescriptor(PointStackerProcess.ATTR_NORM_COUNT).getType().getBinding());
     assertEquals(
         Double.class,
         ft.getDescriptor(PointStackerProcess.ATTR_NORM_COUNT_UNIQUE).getType().getBinding());
   }
 }
 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);
   }
 }
예제 #12
0
 protected Feature feature(SimpleFeatureType type, String id, Object... values)
     throws ParseException {
   SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
   for (int i = 0; i < values.length; i++) {
     Object value = values[i];
     if (type.getDescriptor(i) instanceof GeometryDescriptor) {
       if (value instanceof String) {
         value = new WKTReader2().read((String) value);
       }
     }
     builder.set(i, value);
   }
   return builder.buildFeature(id);
 }
예제 #13
0
  /**
   * DOCUMENT ME!
   *
   * @param featureType DOCUMENT ME!
   * @param properties DOCUMENT ME!
   * @return DOCUMENT ME!
   * @throws SchemaException DOCUMENT ME!
   */
  public static SimpleFeatureType createSubType(SimpleFeatureType featureType, String[] properties)
      throws SchemaException {
    if (properties == null) {
      return featureType;
    }

    boolean same = featureType.getAttributeCount() == properties.length;

    for (int i = 0; (i < featureType.getAttributeCount()) && same; i++) {
      same = featureType.getDescriptor(i).getLocalName().equals(properties[i]);
    }

    if (same) {
      return featureType;
    }

    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
    tb.setName(featureType.getName());

    for (int i = 0; i < properties.length; i++) {
      tb.add(featureType.getDescriptor(properties[i]));
    }
    return tb.buildFeatureType();
  }
예제 #14
0
  public void testIntegerToDateTransform() throws Exception {
    Catalog cat = getCatalog();

    File dir = unpack("shape/archsites_epsg_prj.zip");

    SpatialFile file = new SpatialFile(new File(dir, "archsites.shp"));
    file.prepare();

    ImportContext context = importer.createContext(file, store);
    assertEquals(1, context.getTasks().size());

    context.setTargetStore(store);

    ImportTask task = context.getTasks().get(0);
    // this is a silly test - CAT_ID ranges from 1-25 and is not supposed to be a date
    // java date handling doesn't like dates in year 1
    task.getTransform().add(new IntegerFieldToDateTransform("CAT_ID"));
    importer.run(context);

    assertEquals(ImportContext.State.COMPLETE, context.getState());

    FeatureTypeInfo ft = cat.getFeatureTypeByDataStore(store, "archsites");
    assertNotNull(ft);

    SimpleFeatureType schema = (SimpleFeatureType) ft.getFeatureType();
    assertEquals(Timestamp.class, schema.getDescriptor("CAT_ID").getType().getBinding());

    FeatureIterator it = ft.getFeatureSource(null, null).getFeatures().features();
    int year = 2;
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {
      // make sure we have something
      assertTrue(it.hasNext());
      // the first date will be bogus due to java date limitation
      it.next();
      while (it.hasNext()) {
        SimpleFeature f = (SimpleFeature) it.next();
        // class will be timestamp
        cal.setTime((Date) f.getAttribute("CAT_ID"));
        assertEquals(year++, cal.get(Calendar.YEAR));
      }
    } finally {
      it.close();
    }
  }
예제 #15
0
파일: CsvFile.java 프로젝트: bcdev/beam
  @Override
  public void parseRecords(int offset, int numRecords) throws IOException {
    featureCollection = new ListFeatureCollection(simpleFeatureType);
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(simpleFeatureType);

    skipToLine(offset);
    String line;
    long featureCount = offset;
    while ((numRecords == -1 || featureCount < offset + numRecords)
        && (line = stream.readLine()) != null) {
      String[] tokens = getTokens(line);
      if (tokens == null) {
        break;
      }
      int expectedTokenCount = simpleFeatureType.getAttributeCount();
      expectedTokenCount += hasFeatureId ? 1 : 0;
      if (tokens.length != expectedTokenCount) {
        continue;
      }
      builder.reset();
      String featureId = "" + featureCount++;
      for (int i = 0; i < tokens.length; i++) {
        String token = tokens[i];
        if (i == 0 && hasFeatureId) {
          featureId = token;
        } else {
          try {
            Object value = null;
            int currentIndex = i;
            currentIndex -= hasFeatureId ? 1 : 0;
            if (!VectorDataNodeIO.NULL_TEXT.equals(token)) {
              value = converters[currentIndex].parse(token);
            }
            builder.set(simpleFeatureType.getDescriptor(currentIndex).getLocalName(), value);
          } catch (ConversionException e) {
            BeamLogManager.getSystemLogger()
                .warning(String.format("Problem in '%s': %s", csv.getPath(), e.getMessage()));
          }
        }
      }
      SimpleFeature simpleFeature = builder.buildFeature(featureId);
      featureCollection.add(simpleFeature);
      bytePositionForOffset.put(featureCount, stream.getStreamPosition());
    }
    recordsParsed = true;
  }
 PRMSAnimationAttributeReader(
     PRMSAnimationFileMetaData animationFileMetaData, SimpleFeatureType featureType)
     throws IOException {
   this.featureType = featureType;
   this.animationFileMetaData = animationFileMetaData;
   this.readerAttributeCount = featureType.getAttributeCount();
   this.readerRecordIndex = 0;
   readerAttributeToRecordEntryIndices = new int[readerAttributeCount];
   for (int readerAttributeIndex = 0;
       readerAttributeIndex < readerAttributeCount;
       ++readerAttributeIndex) {
     readerAttributeToRecordEntryIndices[readerAttributeIndex] =
         animationFileMetaData.getRecordEntryIndex(
             featureType.getDescriptor(readerAttributeIndex).getLocalName());
   }
   readerRecordBuffer = new PRMSAnimationRecordBuffer(animationFileMetaData);
 }
예제 #17
0
  /**
   * if the query has been parsed as just a where clause filter, or has no filter at all, the result
   * count calculation is optimized by selecting a <code>count()</code> single row. If the filter
   * involves any kind of spatial filter, such as BBOX, the calculation can't be optimized by this
   * way, because the ArcSDE Java API throws a <code>"DATABASE LEVEL
   * ERROR OCURRED"</code> exception. So, in this case, a query over the shape field is made and the
   * result is traversed counting the number of rows inside a while loop
   */
  public int calculateResultCount() throws IOException {

    final SimpleFeatureType schema = this.schema;
    final GeometryDescriptor geometryDescriptor = schema.getGeometryDescriptor();

    final String colName;
    if (geometryDescriptor == null) {
      // gemetryless type, use any other column for the query
      colName = schema.getDescriptor(0).getLocalName();
    } else {
      colName = geometryDescriptor.getLocalName();
    }
    final SeQueryInfo qInfo = filters.getQueryInfo(new String[] {colName});

    final SeFilter[] spatialFilters = filters.getSpatialFilters();

    final Command<Integer> countCmd =
        new Command<Integer>() {
          @Override
          public Integer execute(ISession session, SeConnection connection)
              throws SeException, IOException {

            SeQuery query = new SeQuery(connection);
            try {
              versioningHandler.setUpStream(session, query);

              if (spatialFilters != null && spatialFilters.length > 0) {
                query.setSpatialConstraints(SeQuery.SE_OPTIMIZE, true, spatialFilters);
              }

              SeTable.SeTableStats tableStats =
                  query.calculateTableStatistics(
                      "*", SeTable.SeTableStats.SE_COUNT_STATS, qInfo, 0);

              int actualCount = tableStats.getCount();
              return new Integer(actualCount);
            } finally {
              query.close();
            }
          }
        };

    final Integer count = session.issue(countCmd);
    return count.intValue();
  }
  static SimpleFeature retype(SimpleFeature source, SimpleFeatureBuilder builder)
      throws IllegalAttributeException {
    SimpleFeatureType target = builder.getFeatureType();
    for (int i = 0; i < target.getAttributeCount(); i++) {
      AttributeDescriptor attributeType = target.getDescriptor(i);
      Object value = null;

      if (source.getFeatureType().getDescriptor(attributeType.getName()) != null) {
        value = source.getAttribute(attributeType.getName());
      }

      builder.add(value);
    }

    FeatureId id = reTypeId(source.getIdentifier(), source.getFeatureType(), target);
    SimpleFeature retyped = builder.buildFeature(id.getID());
    retyped.getUserData().putAll(source.getUserData());
    return retyped;
  }
예제 #19
0
 /** Maps the default geometry attribute regardless of whether they are the same type. */
 @SuppressWarnings("unchecked")
 private static void mapGeometryAttributes(
     SimpleFeatureType sourceSchema,
     SimpleFeatureType targetSchema,
     Map<String, String> queryAttributes) {
   // Now we'll match the geometry on type only. I don't care if it has the same type name.
   GeometryDescriptor defaultGeometry = targetSchema.getGeometryDescriptor();
   if (defaultGeometry == null) {
     return;
   } else if (!queryAttributes.containsKey(defaultGeometry.getName())) {
     // first check source's default geom and see if it matches
     Class<?> binding = sourceSchema.getGeometryDescriptor().getType().getBinding();
     if (defaultGeometry.getType().getBinding().isAssignableFrom(binding)) {
       queryAttributes.put(
           defaultGeometry.getName().getLocalPart(),
           sourceSchema.getGeometryDescriptor().getName().getLocalPart());
     } else {
       // we have to look through all the source attributes looking for a geometry that
       // matches.
       boolean found = false;
       for (int i = 0; i < sourceSchema.getAttributeCount(); i++) {
         AttributeDescriptor source = sourceSchema.getDescriptor(i);
         if (defaultGeometry
             .getType()
             .getBinding()
             .isAssignableFrom(source.getType().getBinding())) {
           queryAttributes.put(
               defaultGeometry.getName().getLocalPart(), source.getName().getLocalPart());
           found = true;
           break;
         }
       }
       // ok so we're going to have to do some transformations. Match default geometries
       // then.
       if (!found) {
         queryAttributes.put(
             defaultGeometry.getName().getLocalPart(),
             sourceSchema.getGeometryDescriptor().getName().getLocalPart());
       }
     }
   }
 }
예제 #20
0
  private static String buildSortByClause(
      final SimpleFeatureType fullSchema,
      final SortBy[] sortByAttributes,
      final FIDReader fidReader) {

    if (sortByAttributes == null || sortByAttributes.length == 0) {
      return null;
    }

    StringBuilder byClause = new StringBuilder("ORDER BY ");
    for (int i = 0; i < sortByAttributes.length; i++) {
      SortBy sortAtt = sortByAttributes[i];
      if (sortAtt == NATURAL_ORDER || sortAtt == REVERSE_ORDER) {
        if (fidReader instanceof SdeManagedFidReader || fidReader instanceof UserManagedFidReader) {
          byClause.append(fidReader.getFidColumn()).append(" ");
          byClause.append(sortAtt == NATURAL_ORDER ? "ASC" : "DESC");
        } else {
          throw new IllegalArgumentException(
              sortAtt + " sorting is not supported for featureclasses" + " with no primary key");
        }
      } else {
        final PropertyName propertyName = sortAtt.getPropertyName();
        final String attName = propertyName.getPropertyName();
        final AttributeDescriptor descriptor = fullSchema.getDescriptor(attName);
        if (descriptor == null) {
          throw new IllegalArgumentException(attName + " does not exist. Can't sort by it");
        }
        if (descriptor instanceof GeometryDescriptor) {
          throw new IllegalArgumentException(
              attName + " is a geometry attribute. Can't sort by it");
        }

        byClause.append(attName).append(" ");
        byClause.append(sortAtt.getSortOrder() == SortOrder.ASCENDING ? "ASC" : "DESC");
      }
      if (i < sortByAttributes.length - 1) {
        byClause.append(", ");
      }
    }
    return byClause.toString();
  }
예제 #21
0
  /**
   * Create a new Features from the provided coordinates and of the type indicated by geomType
   *
   * @param coordCRS The crs of the coordinates provided
   * @param destinationCRS The desired crs of the geometry
   * @param type the feature type of the object created
   * @param coordinates the coordinates that will be used to create the new feature
   * @param geomType the type of geometry that will be created
   * @return A new features.
   * @throws Exception
   */
  public static <T extends Geometry> SimpleFeature createFeature(
      CoordinateReferenceSystem coordCRS,
      CoordinateReferenceSystem destinationCRS,
      SimpleFeatureType type,
      Coordinate[] coordinates,
      Class<T> geomType)
      throws Exception {

    transform(coordCRS, destinationCRS, coordinates);
    Object[] attrs = new Object[type.getAttributeCount()];
    for (int i = 0; i < attrs.length; i++) {
      attrs[i] = setDefaultValue(type.getDescriptor(i));
    }
    final SimpleFeature newFeature = SimpleFeatureBuilder.build(type, attrs, null);
    // Class geomType = type.getDefaultGeometry().getType();

    T geom = GeometryBuilder.create().safeCreateGeometry(geomType, coordinates);
    newFeature.setDefaultGeometry(geom);

    return newFeature;
  }
예제 #22
0
파일: CsvFile.java 프로젝트: bcdev/beam
  @Override
  public Object[] parseRecords(final int offset, final int numRecords, final String rowName)
      throws IOException {
    AttributeDescriptor attributeDescriptor = simpleFeatureType.getDescriptor(rowName);
    int expectedTokenCount = simpleFeatureType.getAttributeCount();
    expectedTokenCount += hasFeatureId ? 1 : 0;
    int rowIndex = simpleFeatureType.getAttributeDescriptors().indexOf(attributeDescriptor);
    int tokenIndex = rowIndex + (hasFeatureId ? 1 : 0);

    List<Object> values = new ArrayList<>(numRecords);
    skipToLine(offset);
    String line;
    long featureCount = offset;
    while ((numRecords == -1 || featureCount < offset + numRecords)
        && (line = stream.readLine()) != null) {
      String[] tokens = getTokens(line);
      if (tokens == null) {
        break;
      }

      if (tokens.length != expectedTokenCount) {
        continue;
      }
      featureCount++;

      String token = tokens[tokenIndex];
      try {
        Object value = null;
        if (!VectorDataNodeIO.NULL_TEXT.equals(token)) {
          value = converters[rowIndex].parse(token);
        }
        values.add(value);
      } catch (ConversionException e) {
        BeamLogManager.getSystemLogger()
            .warning(String.format("Problem in '%s': %s", csv.getPath(), e.getMessage()));
      }
      bytePositionForOffset.put(featureCount, stream.getStreamPosition());
    }
    return values.toArray();
  }
  public static SimpleFeatureType retype(SimpleFeatureType original, List<String> types) {
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();

    // initialize the builder
    b.init(original);

    // clear the attributes
    b.attributes().clear();

    // add attributes in order
    for (int i = 0; i < types.size(); i++) {
      b.add(original.getDescriptor(types.get(i)));
    }

    // handle default geometry
    GeometryDescriptor defaultGeometry = original.getGeometryDescriptor();
    if (defaultGeometry != null && types.contains(defaultGeometry.getLocalName())) {
      b.setDefaultGeometry(defaultGeometry.getLocalName());
    }

    return b.buildFeatureType();
  }
예제 #24
0
  public void testDateFormatTransform() throws Exception {
    Catalog cat = getCatalog();

    File dir = unpack("shape/ivan.zip");

    SpatialFile file = new SpatialFile(new File(dir, "ivan.shp"));
    file.prepare();

    ImportContext context = importer.createContext(file, store);
    assertEquals(1, context.getTasks().size());

    context.setTargetStore(store);

    ImportTask task = context.getTasks().get(0);
    task.getTransform().add(new DateFormatTransform("timestamp", "yyyy-MM-dd HH:mm:ss.S"));

    importer.run(context);

    assertEquals(ImportContext.State.COMPLETE, context.getState());

    FeatureTypeInfo ft = cat.getFeatureTypeByDataStore(store, "ivan");
    assertNotNull(ft);

    SimpleFeatureType schema = (SimpleFeatureType) ft.getFeatureType();
    assertTrue(
        Date.class.isAssignableFrom(schema.getDescriptor("timestamp").getType().getBinding()));

    FeatureIterator it = ft.getFeatureSource(null, null).getFeatures().features();
    try {
      assertTrue(it.hasNext());
      while (it.hasNext()) {
        SimpleFeature f = (SimpleFeature) it.next();
        assertTrue(f.getAttribute("timestamp") instanceof Date);
      }
    } finally {
      it.close();
    }
  }
예제 #25
0
  /**
   * Creates the bounding box filters (one for each geometric attribute) needed to query a <code>
   * Layer</code>'s feature source to return just the features for the target rendering extent
   *
   * @param schema the layer's feature source schema
   * @param bbox the expression holding the target rendering bounding box
   * @return an or'ed list of bbox filters, one for each geometric attribute in <code>attributes
   *     </code>. If there are just one geometric attribute, just returns its corresponding <code>
   *     GeometryFilter</code>.
   * @throws IllegalFilterException if something goes wrong creating the filter
   */
  private static Filter createBBoxFilter(SimpleFeatureType schema, Envelope bbox)
      throws IllegalFilterException {
    List filters = new ArrayList();
    for (int j = 0; j < schema.getAttributeCount(); j++) {
      AttributeDescriptor attType = schema.getDescriptor(j);

      if (attType instanceof GeometryDescriptor) {
        Filter gfilter =
            filterFactory.bbox(
                attType.getLocalName(),
                bbox.getMinX(),
                bbox.getMinY(),
                bbox.getMaxX(),
                bbox.getMaxY(),
                null);
        filters.add(gfilter);
      }
    }

    if (filters.size() == 0) return Filter.INCLUDE;
    else if (filters.size() == 1) return (Filter) filters.get(0);
    else return filterFactory.or(filters);
  }
예제 #26
0
  public void testCleanMerge() throws Exception {
    // grab the datastore
    VersioningFeatureStore restricted =
        (VersioningFeatureStore) synchStore.getFeatureSource("restricted");
    SimpleFeatureType schema = restricted.getSchema();
    // make the same changes as in the post diff
    Id updateFilter =
        ff.id(singleton(ff.featureId("restricted.be7cafea-d0b7-4257-9b9c-1ed3de3f7ef4")));
    restricted.modifyFeatures(schema.getDescriptor("cat"), -48, updateFilter);
    // remove the third feature
    Id removeFilter =
        ff.id(singleton(ff.featureId("restricted.d91fe390-bdc7-4b22-9316-2cd6c8737ef5")));
    restricted.removeFeatures(removeFilter);
    assertEquals(3, restricted.getCount(Query.ALL));

    // get the response and do the basic checks
    MockHttpServletResponse response =
        postAsServletResponse(root(true), loadTextResource("PostDiffInitial.xml"));
    checkPostDiffSuccessResponse(response);

    // check there are no conflicts
    assertEquals(0, gss.getActiveConflicts("restricted").size());

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

    // we should have got back an empty transaction
    // ... check the main element
    assertXpathEvaluatesTo("-1", "/gss:GetDiffResponse/@fromVersion", dom);
    assertXpathEvaluatesTo("6", "/gss:GetDiffResponse/@toVersion", dom);
    assertXpathEvaluatesTo("sf:restricted", "/gss:GetDiffResponse/@typeName", dom);
    // check the transaction is empty
    assertXpathEvaluatesTo("0", "count(/gss:GetDiffResponse/gss:Changes/*)", dom);
  }
  /**
   * A new feature type using the attribute names of all joined feature type.
   *
   * @return a new feature type
   * @throws IllegalAttributeException
   * @throws SchemaException
   */
  public SimpleFeature getFeature() throws IllegalAttributeException, SchemaException {

    SimpleFeatureType unionFeatureType = getFeatureType();
    // adds the attributes values
    Object[] attrList = new Object[unionFeatureType.getAttributeCount()];
    for (SimpleFeature feature : this.unionFeatures) {

      SimpleFeatureType featureType = feature.getFeatureType();
      for (int j = 0; j < featureType.getAttributeCount(); j++) {

        // gets the attribute value
        AttributeDescriptor attrType = featureType.getDescriptor(j);
        if (!(attrType instanceof GeometryDescriptor)) {

          Object attrValue = feature.getAttribute(j);

          // gets the position in the union
          String unionAttrName =
              findAttributeName(featureType.getTypeName(), attrType.getLocalName());

          int unionAttrPosition = unionFeatureType.indexOf(unionAttrName);

          // set the value in union
          attrList[unionAttrPosition] = attrValue;
        }
      }
    }
    // creates the new feature
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(unionFeatureType);
    builder.addAll(attrList);
    // SimpleFeature product = unionFeatureType.create(attrList);
    SimpleFeature product = builder.buildFeature(null);
    product.setDefaultGeometry(this.geometry);

    return product;
  }
예제 #28
0
  public void testNumberFormatTransform() throws Exception {
    Catalog cat = getCatalog();

    File dir = unpack("shape/restricted.zip");

    SpatialFile file = new SpatialFile(new File(dir, "restricted.shp"));
    file.prepare();

    ImportContext context = importer.createContext(file, store);
    assertEquals(1, context.getTasks().size());

    context.setTargetStore(store);

    ImportTask task = context.getTasks().get(0);
    task.getTransform().add(new NumberFormatTransform("cat", Integer.class));
    importer.run(context);

    assertEquals(ImportContext.State.COMPLETE, context.getState());

    FeatureTypeInfo ft = cat.getFeatureTypeByDataStore(store, "restricted");
    assertNotNull(ft);

    SimpleFeatureType schema = (SimpleFeatureType) ft.getFeatureType();
    assertEquals(Integer.class, schema.getDescriptor("cat").getType().getBinding());

    FeatureIterator it = ft.getFeatureSource(null, null).getFeatures().features();
    try {
      assertTrue(it.hasNext());
      while (it.hasNext()) {
        SimpleFeature f = (SimpleFeature) it.next();
        assertTrue(f.getAttribute("cat") instanceof Integer);
      }
    } finally {
      it.close();
    }
  }
 /** @see org.eclipse.ui.views.properties.IPropertySource#getPropertyValue(java.lang.Object) */
 public Object getPropertyValue(Object id) {
   int i = ((Integer) id).intValue();
   String name = type.getDescriptor(i).getType().getBinding().getName();
   return name.substring(name.lastIndexOf('.') + 1);
 }
예제 #30
0
 public UniqueVisitor(String attrName, SimpleFeatureType type) throws IllegalFilterException {
   FilterFactory factory = CommonFactoryFinder.getFilterFactory(null);
   expr = factory.property(type.getDescriptor(attrName).getLocalName());
 }