/**
   * The type of filter that returns should be in a single Or filter OR(a,b,c) instead of ((a OR b)
   * or c)
   */
  @Test
  public void testUnrollFid() throws Exception {
    Set<FeatureId> fids = new HashSet();
    String fid1 = "station_no.1"; // exists
    String fid2 = "station_no.500"; // doesn't exists
    fids.add(ff.featureId(fid1));
    fids.add(ff.featureId(fid2));
    Id fidFilter = ff.id(fids);
    Filter unrolled = (Filter) fidFilter.accept(visitor, null);
    assertNotNull(unrolled);
    assertTrue(unrolled instanceof OrImpl);
    List<Filter> filters = ((OrImpl) unrolled).getChildren();
    assertEquals(2, filters.size());
    for (Filter f : filters) {
      assertTrue(f instanceof IsEqualsToImpl);
    }

    FeatureCollection<SimpleFeatureType, SimpleFeature> results =
        mapping.getSource().getFeatures(unrolled);
    assertEquals(1, getCount(results));

    FeatureIterator<SimpleFeature> features = results.features();
    SimpleFeature unmappedFeature = (SimpleFeature) features.next();

    features.close();

    assertNotNull(unmappedFeature);
    Object object = unmappedFeature.getProperty("station_no").getValue();
    assertEquals(fid1, object);
  }
  /**
   * Uses the current {@link FIDValidator} to wipe out illegal feature ids from the returned
   * filters.
   *
   * @return a filter containing only valid fids as per the current {@link FIDValidator}, may be
   *     {@link Filter#EXCLUDE} if none matches or the filter is already empty
   */
  @Override
  public Object visit(Id filter, Object extraData) {
    // if the set of ID is empty, it's actually equivalent to Filter.EXCLUDE
    if (filter.getIDs().size() == 0) {
      return Filter.EXCLUDE;
    }

    Set<Identifier> validFids = new HashSet<Identifier>();

    for (Identifier id : filter.getIdentifiers()) {
      if (id instanceof FeatureId || id instanceof GmlObjectId) {
        // both FeatureId an GmlObjectId.getID() return String, but Identifier.getID()
        // returns Object. Yet, FeatureId and GmlObjectId are the only known subclasses of
        // Identifier that apply to Feature land
        if (fidValidator.isValid((String) id.getID())) {
          validFids.add(id);
        }
      }
    }

    Filter validIdFilter;
    if (validFids.size() == 0) {
      validIdFilter = Filter.EXCLUDE;
    } else {
      validIdFilter = getFactory(extraData).id(validFids);
    }
    return validIdFilter;
  }
  /**
   * Implementation for tests of fid -> fid unmapping.
   *
   * @param idExpression
   * @throws Exception
   */
  private void checkUnrollIdExpression(Expression idExpression) throws Exception {
    AttributeMapping featureMapping = null;
    Name featurePath = mapping.getTargetFeature().getName();
    QName featureName = Types.toQName(featurePath);
    for (Iterator it = mapping.getAttributeMappings().iterator(); it.hasNext(); ) {
      AttributeMapping attMapping = (AttributeMapping) it.next();
      StepList targetXPath = attMapping.getTargetXPath();
      if (targetXPath.size() > 1) {
        continue;
      }
      Step step = (Step) targetXPath.get(0);
      if (featureName.equals(step.getName())) {
        featureMapping = attMapping;
        break;
      }
    }
    featureMapping.setIdentifierExpression(idExpression);
    this.visitor = new UnmappingFilterVisitor(this.mapping);

    // retrieve a single sample feature
    Feature sourceFeature = DataUtilities.first(mapping.getSource().getFeatures());
    String fid = sourceFeature.getIdentifier().toString();
    Id fidFilter = ff.id(Collections.singleton(ff.featureId(fid)));
    Filter unrolled = (Filter) fidFilter.accept(visitor, null);
    assertNotNull(unrolled);
    assertTrue(unrolled instanceof Id);

    FeatureCollection<SimpleFeatureType, SimpleFeature> results =
        mapping.getSource().getFeatures(unrolled);
    assertEquals(1, getCount(results));

    SimpleFeature unmappedFeature = DataUtilities.first(results);

    assertEquals(fid, unmappedFeature.getID());
  }
Example #4
0
  public static Object Filter_getProperty(Object object, QName qName) {
    Filter filter = (Filter) object;

    // use the local name to handle oth the OGC and FES namespaces
    String name = qName.getLocalPart();

    // &lt;xsd:element ref="ogc:spatialOps"/&gt;
    if ("spatialOps".equals(name) && filter instanceof BinarySpatialOperator) {
      return filter;
    }

    // &lt;xsd:element ref="ogc:comparisonOps"/&gt;
    if ("comparisonOps".equals(name)) {
      // JD: extra check here because many of our spatial implementations
      // extend both
      if (filter instanceof BinaryComparisonOperator
          && !(filter instanceof BinarySpatialOperator)) {
        return filter;
      } else {
        // filters that don't extend BinaryComparisonOperator but are still
        // comparisonOps
        if (filter instanceof PropertyIsLike
            || filter instanceof PropertyIsNull
            || filter instanceof PropertyIsBetween) {
          return filter;
        }
      }
    }

    // &lt;xsd:element ref="ogc:logicOps"/&gt;
    if ("logicOps".equals(name)
        && (filter instanceof BinaryLogicOperator || filter instanceof Not)) {
      return filter;
    }
    // &lt;xsd:element ref="ogc:temporalOps"/&gt;
    if ("temporalOps".equals(name) && (filter instanceof BinaryTemporalOperator)) {
      return filter;
    }

    // &lt;xsd:element maxOccurs="unbounded" ref="ogc:_Id"/&gt;
    if (filter instanceof Id
        && ("_Id".equals(name) /*1.1/2.0*/ || "FeatureId".equals(name) /*1.0*/)) {
      // unwrap
      Id id = (Id) filter;

      return id.getIdentifiers();
    }

    return null;
  }
  /**
   * @see org.geotools.data.FeatureStore#modifyFeatures(org.opengis.feature.type.Name[],
   *     java.lang.Object[], org.opengis.filter.Filter)
   */
  @Override
  public void modifyFeatures(
      final Name[] attributeNames, final Object[] attributeValues, final Filter filter)
      throws IOException {

    final FeatureStore<T, F> unversioned = getUnversionedStore();
    final boolean versioned = isVersioned();
    Id affectedFeaturesFitler = null;
    Filter unversionedFilter = filter;
    if (versioned) {
      checkTransaction();
      // throws exception if filter has a resourceid that doesn't match
      // the current version
      checkEditFilterMatchesCurrentVersion(filter);

      unversionedFilter = VersionFilters.getUnversioningFilter(filter);
      if (unversionedFilter instanceof Id) {
        affectedFeaturesFitler = (Id) unversionedFilter;
      } else {
        FeatureCollection<T, F> affectedFeatures;

        affectedFeatures = unversioned.getFeatures(unversionedFilter);
        FeatureIterator<F> iterator = affectedFeatures.features();
        Set<Identifier> affectedIds = new HashSet<Identifier>();
        try {
          while (iterator.hasNext()) {
            affectedIds.add(iterator.next().getIdentifier());
          }
        } finally {
          iterator.close();
        }
        final FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null);
        affectedFeaturesFitler = ff.id(affectedIds);
      }
    }

    unversioned.modifyFeatures(attributeNames, attributeValues, unversionedFilter);

    if (versioned
        && affectedFeaturesFitler != null
        && affectedFeaturesFitler.getIdentifiers().size() > 0) {
      try {
        FeatureCollection newValues = unversioned.getFeatures(affectedFeaturesFitler);
        getVersioningState().stageUpdate(getSchema().getName(), newValues);
      } catch (Exception e) {
        Throwables.propagate(e);
      }
    }
  }
  /**
   * Mapping specifies station_no --> wq_plus/@id. A FidFilter over wq_plus type should result in a
   * compare equals filter over the station_no attribute of wq_ir_results simple type.
   */
  @Test
  public void testUnrollFidMappedToAttribute() throws Exception {
    String fid = "station_no.1";
    Id fidFilter = ff.id(Collections.singleton(ff.featureId(fid)));

    Filter unrolled = (Filter) fidFilter.accept(visitor, null);
    assertNotNull(unrolled);

    FeatureCollection<SimpleFeatureType, SimpleFeature> results =
        mapping.getSource().getFeatures(unrolled);
    assertEquals(1, getCount(results));

    FeatureIterator<SimpleFeature> features = results.features();
    SimpleFeature unmappedFeature = (SimpleFeature) features.next();
    features.close();

    assertNotNull(unmappedFeature);
    Object object = unmappedFeature.getProperty("station_no").getValue();
    assertEquals(fid, object);
  }
 /**
  * Throws an IllegalArgumentException if {@code filter} contains a resource filter that doesn't
  * match the current version of a feature
  *
  * @param filter original upate filter
  */
 private void checkEditFilterMatchesCurrentVersion(final Filter filter) {
   final Id versionFilter = VersionFilters.getVersioningFilter(filter);
   if (versionFilter == null) {
     return;
   }
   // don't allow non current versions
   GeoGIT ggit = new GeoGIT(repository);
   VersionQuery query = new VersionQuery(ggit, getSchema().getName());
   for (Identifier id : versionFilter.getIdentifiers()) {
     ResourceId rid = (ResourceId) id;
     List<Ref> requested;
     List<Ref> current;
     try {
       requested = Lists.newArrayList(query.get(rid));
       current = Lists.newArrayList(query.get(new ResourceIdImpl(rid.getID(), null)));
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
     if (!current.equals(requested)) {
       throw new IllegalArgumentException(
           "Requested resource id filter doesn't match curent version for feature " + rid.getID());
     }
   }
 }
  public Object parse(ElementInstance instance, Node node, Object value) throws Exception {
    Filter filter = (Filter) super.parse(instance, node, value);

    // some checks, these should perhaps be made part of the Filter binding
    if (filter instanceof Id) {
      Id idFilter = (Id) filter;

      if (idFilter.getIdentifiers().size() > 1) {
        // there should only be one type of id specified
        HashSet types = new HashSet();

        for (Iterator i = idFilter.getIdentifiers().iterator(); i.hasNext(); ) {
          Identifier id = (Identifier) i.next();
          types.add(id.getClass());
        }

        if (types.size() != 1) {
          throw new Exception("Only one type of Id can be supplied in a single filter");
        }
      }
    }

    return filter;
  }
Example #9
0
 @Override
 public Object visit(Id filter, Object extraData) {
   StringWriter output = asStringWriter(extraData);
   Set<Identifier> ids = filter.getIdentifiers();
   output.append(" (");
   for (Iterator<Identifier> i = ids.iterator(); i.hasNext(); ) {
     Identifier id = i.next();
     String fid = decodeFID(id.toString());
     output.write(primaryKey.getName() + ":" + "\"" + fid + "\"");
     if (i.hasNext()) {
       output.write(" OR ");
     }
   }
   output.append(") ");
   return output;
 }
  /**
   * Test method for 'org.locationtech.udig.validation.ValidateOverlaps.op(Display, Object,
   * IProgressMonitor)'
   */
  @Ignore
  @Test
  public void testOverlapsOp() throws Exception {
    // create features suitable for the test
    GeometryFactory factory = new GeometryFactory();
    LineString[] line = new LineString[4];
    // first test: 2 overlapping lines, overlap test fails?
    line[0] =
        factory.createLineString(
            new Coordinate[] {
              new Coordinate(10, 10), new Coordinate(20, 20),
            });
    line[1] =
        factory.createLineString(
            new Coordinate[] {
              new Coordinate(15, 15), new Coordinate(25, 25),
            });
    assertTrue(line[0].overlaps(line[1])); // just checking :)
    // second test: does this validation test for self-overlaps? (it shouldn't)
    line[2] =
        factory.createLineString(
            new Coordinate[] {
              new Coordinate(50, 50), new Coordinate(60, 50), new Coordinate(55, 50),
            });
    // third test: an intersecting line; is valid?
    line[3] =
        factory.createLineString(
            new Coordinate[] {
              new Coordinate(10, 20), new Coordinate(20, 10),
            });

    String[] attrValues = new String[4];
    attrValues[0] = "value0"; // $NON-NLS-1$
    attrValues[1] = "value1"; // $NON-NLS-1$
    attrValues[2] = "value2"; // $NON-NLS-1$
    attrValues[3] = "value3"; // $NON-NLS-1$

    SimpleFeatureType ft =
        DataUtilities.createType(
            "myLineType", "*geom:LineString,name:String"); // $NON-NLS-1$ //$NON-NLS-2$
    ft = DataUtilities.createSubType(ft, null, DefaultEngineeringCRS.CARTESIAN_2D);
    SimpleFeature[] features = new SimpleFeature[4];
    // add lines
    features[0] =
        SimpleFeatureBuilder.build(ft, new Object[] {line[0], attrValues[0]}, Integer.toString(0));
    features[1] =
        SimpleFeatureBuilder.build(ft, new Object[] {line[1], attrValues[1]}, Integer.toString(1));
    features[2] =
        SimpleFeatureBuilder.build(ft, new Object[] {line[2], attrValues[2]}, Integer.toString(2));
    features[3] =
        SimpleFeatureBuilder.build(ft, new Object[] {line[3], attrValues[3]}, Integer.toString(3));

    IGeoResource resource = MapTests.createGeoResource(features, true);
    Map map = MapTests.createNonDynamicMapAndRenderer(resource, new Dimension(500, 512));
    ValidateOverlaps validator = new ValidateOverlaps();
    validator.op(Display.getDefault(), map.getLayersInternal().get(0), new NullProgressMonitor());
    assertEquals(
        1,
        validator.genericResults.failedFeatures
            .size()); // only line[0] and line[1] should fail (counts as 1)
    map.sendCommandSync(
        new AbstractCommand() {

          public void run(IProgressMonitor monitor) throws Exception {}

          public String getName() {
            return null;
          }
        }); // send a sync command so async doesn't give us a false junit failure

    Id filter = (Id) map.getLayersInternal().get(0).getFilter();
    String[] fids = filter.getIDs().toArray(new String[0]);
    // System.out.println(fids[0].length()+" features in FID");
    assertEquals(1, fids[0].length()); // only 1 feature failed?
    assertEquals(features[0].getID(), fids[0]); // it was feature 0 that failed?
  }
  public void XtestUserSelection() throws Exception {

    // test normal click
    doEventBasedSelection(1, 0, 1);

    IStructuredSelection structuredSelection = ((IStructuredSelection) table.getSelection());
    assertNotNull("Selection expected", structuredSelection);

    Object firstElement = structuredSelection.getFirstElement();
    assertNotNull("First element should not be null", firstElement);

    Id idFilter = (Id) firstElement;
    assertFalse("Expect a non empty selection", idFilter.getIdentifiers().isEmpty());
    assertFalse("Expect a non empty selection", idFilter.getIDs().isEmpty());
    Set<Object> ds = (idFilter).getIDs();

    String[] fids = ds.toArray(new String[0]);
    assertEquals("Expect selected ID to match", feature2.getID(), fids[0]);

    assertSelectedBackgroundColor(1);

    doEventBasedSelection(2, 0, 1);

    firstElement = structuredSelection.getFirstElement();
    fids = ds.toArray(new String[0]);
    assertEquals(1, fids.length);
    assertEquals(feature3.getID(), fids[0]);
    assertSelectedBackgroundColor(2);

    doEventBasedSelection(2, 0, 2);

    firstElement = structuredSelection.getFirstElement();
    assertEquals(1, fids.length);
    fids = ds.toArray(new String[0]);
    assertEquals(feature3.getID(), fids[0]);
    assertSelectedBackgroundColor(2);

    // test MOD2 click
    doEventBasedSelection(0, SWT.MOD2, 1);

    firstElement = structuredSelection.getFirstElement();
    fids = ds.toArray(new String[0]);
    assertEquals(3, fids.length);
    assertTrue(contains(feature3.getID(), fids));
    assertTrue(contains(feature1.getID(), fids));
    assertTrue(contains(feature2.getID(), fids));
    assertSelectedBackgroundColor(0, 1, 2);

    doEventBasedSelection(1, SWT.MOD2, 1);

    firstElement = structuredSelection.getFirstElement();
    fids = ds.toArray(new String[0]);
    assertEquals(2, fids.length);
    assertTrue(contains(feature3.getID(), fids));
    assertTrue(contains(feature2.getID(), fids));
    assertSelectedBackgroundColor(1, 2);

    // test MOD1 click
    doEventBasedSelection(1, SWT.MOD1, 1);

    firstElement = structuredSelection.getFirstElement();
    fids = ds.toArray(new String[0]);
    assertEquals(1, fids.length);
    assertTrue(contains(feature3.getID(), fids));
    assertSelectedBackgroundColor(2);

    doEventBasedSelection(1, SWT.MOD1, 1);

    firstElement = structuredSelection.getFirstElement();
    fids = ds.toArray(new String[0]);
    assertEquals(2, fids.length);
    assertTrue(contains(feature3.getID(), fids));
    assertTrue(contains(feature2.getID(), fids));
    assertSelectedBackgroundColor(1, 2);
  }