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());
      }
    }
  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;
  }
  /**
   * 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.º 4
0
  /**
   * Create a derived FeatureType
   *
   * <p>
   *
   * @param featureType
   * @param properties - if null, every property of the feature type in input will be used
   * @param override
   * @throws SchemaException
   */
  public static SimpleFeatureType createSubType(
      SimpleFeatureType featureType, String[] properties, CoordinateReferenceSystem override)
      throws SchemaException {
    URI namespaceURI = null;
    if (featureType.getName().getNamespaceURI() != null) {
      try {
        namespaceURI = new URI(featureType.getName().getNamespaceURI());
      } catch (URISyntaxException e) {
        throw new RuntimeException(e);
      }
    }

    return createSubType(
        featureType, properties, override, featureType.getTypeName(), namespaceURI);
  }
Ejemplo n.º 5
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();
  }
  @Test
  public void testModifyIssue() throws Exception {
    String newDescription = "new modified description"; // $NON-NLS-1$

    list.clear();
    list.add(IssuesListTestHelper.createFeatureIssue("test")); // $NON-NLS-1$

    list.refresh();
    assertEquals(1, list.size());

    IIssue issue = list.get(0);
    issue.setDescription(newDescription);
    ((IRemoteIssuesList) list).save(issue);
    FilterFactory factory = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());

    Expression expr2 = factory.literal(issue.getId());
    Expression expr1 = factory.property(IssuesListTestHelper.ISSUE_ID_ATTR);
    Filter filter = factory.equals(expr1, expr2);

    SimpleFeature next =
        store
            .getFeatureSource(featureType.getName().getLocalPart())
            .getFeatures(filter)
            .features()
            .next();
    assertEquals(newDescription, next.getAttribute(IssuesListTestHelper.DESCRIPTION_ATTR));
  }
  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);
    }
  }
  /** Initializes the builder with state from a pre-existing feature type. */
  public void init(SimpleFeatureType type) {
    init();
    if (type == null) return;

    uri = type.getName().getNamespaceURI();
    local = type.getName().getLocalPart();
    description = type.getDescription();
    restrictions = null;
    restrictions().addAll(type.getRestrictions());
    this.defaultCrs = type.getCoordinateReferenceSystem();
    this.defaultCrsSet = true;
    attributes = null;
    attributes().addAll(type.getAttributeDescriptors());

    isAbstract = type.isAbstract();
    superType = (SimpleFeatureType) type.getSuper();
  }
Ejemplo n.º 9
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;
  }
 @Test
 public void testInitialLoad() throws Exception {
   assertEquals(4, list.size());
   assertEquals("0", list.get(0).getId()); // $NON-NLS-1$
   assertEquals("1", list.get(1).getId()); // $NON-NLS-1$
   assertEquals("2", list.get(2).getId()); // $NON-NLS-1$
   assertEquals("3", list.get(3).getId()); // $NON-NLS-1$
   assertEquals(
       4, store.getFeatureSource(featureType.getName().getLocalPart()).getCount(Query.ALL));
 }
 @Test
 public void testRemoveInt() throws Exception {
   list.remove(1);
   assertEquals(3, list.size());
   assertEquals("0", list.get(0).getId()); // $NON-NLS-1$
   assertEquals("2", list.get(1).getId()); // $NON-NLS-1$
   assertEquals("3", list.get(2).getId()); // $NON-NLS-1$
   assertEquals(
       3, store.getFeatureSource(featureType.getName().getLocalPart()).getCount(Query.ALL));
 }
    public IntersectedFeatureCollection(
        SimpleFeatureCollection delegate,
        List<String> firstAttributes,
        SimpleFeatureCollection features,
        List<String> sndAttributes,
        IntersectionMode intersectionMode,
        boolean percentagesEnabled,
        boolean areasEnabled) {
      super(delegate);
      this.features = features;
      this.firstAttributes = firstAttributes;
      this.sndAttributes = sndAttributes;
      this.intersectionMode = intersectionMode;
      this.percentagesEnabled = percentagesEnabled;
      this.areasEnabled = areasEnabled;
      SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();

      SimpleFeatureType firstFeatureCollectionSchema = delegate.getSchema();
      SimpleFeatureType secondFeatureCollectionSchema = features.getSchema();

      if (intersectionMode == IntersectionMode.FIRST) {
        geomType = firstFeatureCollectionSchema.getGeometryDescriptor();
      }
      if (intersectionMode == IntersectionMode.SECOND) {
        geomType = secondFeatureCollectionSchema.getGeometryDescriptor();
      }
      if (intersectionMode == IntersectionMode.INTERSECTION) {
        geomType = getIntersectionType(delegate, features);
      }
      tb.add(geomType);

      // gather the attributes from the first feature collection and skip
      collectAttributes(firstFeatureCollectionSchema, firstAttributes, tb);
      // gather the attributes from the second feature collection
      collectAttributes(secondFeatureCollectionSchema, sndAttributes, tb);
      // add the dyamic attributes as needed
      if (percentagesEnabled) {
        tb.add("percentageA", Double.class);
        tb.add("percentageB", Double.class);
      }
      if (areasEnabled) {
        tb.add("areaA", Double.class);
        tb.add("areaB", Double.class);
      }
      tb.add("INTERSECTION_ID", Integer.class);
      tb.setDescription(firstFeatureCollectionSchema.getDescription());
      tb.setCRS(firstFeatureCollectionSchema.getCoordinateReferenceSystem());
      tb.setAbstract(firstFeatureCollectionSchema.isAbstract());
      tb.setSuperType((SimpleFeatureType) firstFeatureCollectionSchema.getSuper());
      tb.setName(firstFeatureCollectionSchema.getName());

      this.fb = new SimpleFeatureBuilder(tb.buildFeatureType());
    }
Ejemplo n.º 13
0
  /** Quick check of namespace and typename */
  public static boolean equalsId(SimpleFeatureType typeA, SimpleFeatureType typeB) {
    if (typeA == typeB) return true;

    if (typeA == null || typeB == null) {
      return false;
    }

    String typeNameA = typeA.getTypeName();
    String typeNameB = typeB.getTypeName();
    if (typeNameA == null && typeNameB != null) return false;
    else if (!typeNameA.equals(typeNameB)) return false;

    String namespaceA = typeA.getName().getNamespaceURI();
    String namespaceB = typeB.getName().getNamespaceURI();
    if (namespaceA == null && namespaceB == null) return true;

    if (namespaceA == null && namespaceB != null) return false;
    else if (!namespaceA.equals(namespaceB)) return false;

    return true;
  }
 @Test
 public void testAddIIssue() throws Exception {
   FeatureIssue issue = IssuesListTestHelper.createFeatureIssue("new"); // $NON-NLS-1$
   list.add(issue);
   assertEquals(5, list.size());
   assertEquals("new", list.get(4).getId()); // $NON-NLS-1$
   list.refresh();
   assertEquals(5, list.size());
   assertEquals("new", list.get(4).getId()); // $NON-NLS-1$
   assertEquals("groupID", list.get(4).getGroupId()); // $NON-NLS-1$
   assertEquals("test description", list.get(4).getDescription()); // $NON-NLS-1$
   assertEquals(
       5, store.getFeatureSource(featureType.getName().getLocalPart()).getCount(Query.ALL));
 }
  /**
   * 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.º 16
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;
  }
Ejemplo n.º 17
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;
  }
Ejemplo n.º 18
0
  /**
   * Filters the feature type styles of <code>style</code> returning only those that apply to <code>
   * featureType</code>
   *
   * <p>This methods returns feature types for which <code>featureTypeStyle.getFeatureTypeName()
   * </code> matches the name of the feature type of <code>featureType</code>, or matches the name
   * of any parent type of the feature type of <code>featureType</code>. This method returns an
   * empty array in the case of which no rules match.
   *
   * @param style The style containing the feature type styles.
   * @param featureType The feature type being filtered against.
   */
  public static FeatureTypeStyle[] filterFeatureTypeStyles(Style style, SimpleFeatureType ftype) {
    List<FeatureTypeStyle> featureTypeStyles = style.featureTypeStyles();

    if (featureTypeStyles == null || featureTypeStyles.isEmpty()) {
      return new FeatureTypeStyle[0];
    }

    ArrayList<FeatureTypeStyle> filtered =
        new ArrayList<FeatureTypeStyle>(featureTypeStyles.size());
    for (FeatureTypeStyle fts : featureTypeStyles) {
      String ftName = fts.getFeatureTypeName();

      // yeah, ugly, but exactly the same code as the streaming renderer... we should
      // really factor out this style massaging in a delegate object (StyleOverlord)
      if (fts.featureTypeNames().isEmpty()
          || ((ftype.getName().getLocalPart() != null)
              && (ftype.getName().getLocalPart().equalsIgnoreCase(ftName)
                  || FeatureTypes.isDecendedFrom(ftype, null, ftName)))) {
        filtered.add(fts);
      }
    }

    return (FeatureTypeStyle[]) filtered.toArray(new FeatureTypeStyle[filtered.size()]);
  }
Ejemplo n.º 19
0
  @Test
  public void testTypes() throws IOException, NoSuchElementException {
    if (url == null) return;
    WFS_1_0_0_DataStore wfs;
    try {
      wfs = WFSDataStoreReadTest.getDataStore(url);
    } catch (ConnectException e) {
      e.printStackTrace(System.err);
      return;
    } catch (UnknownHostException e) {
      e.printStackTrace(System.err);
      return;
    } catch (NoRouteToHostException e) {
      e.printStackTrace(System.err);
      return;
    }
    String types[] = wfs.getTypeNames();
    String typeName = "unknown";
    for (int i = 0; i < types.length; i++) {
      typeName = types[i];
      if (typeName.equals("topp:geometrytype")) continue;
      SimpleFeatureType type = wfs.getSchema(typeName);
      type.getTypeName();
      type.getName().getNamespaceURI();

      SimpleFeatureSource source = wfs.getFeatureSource(typeName);
      source.getBounds();

      SimpleFeatureCollection features = source.getFeatures();
      features.getBounds();
      features.getSchema();
      // features.getFeatureType();

      Query query = new Query(typeName, Filter.INCLUDE, 20, Query.ALL_NAMES, "work already");
      features = source.getFeatures(query);
      features.size();
      SimpleFeatureIterator iterator = features.features();
      try {
        while (iterator.hasNext()) {
          SimpleFeature feature = (SimpleFeature) iterator.next();
        }
      } finally {
        iterator.close();
      }
    }
  }
Ejemplo n.º 20
0
  private static void writeFeatureType(ILayer layer, BufferedWriter out) throws IOException {
    WFSDataStore wfs = (WFSDataStore) layer.getResource(WFSDataStore.class, null);
    SimpleFeatureType type = layer.getSchema();
    String typeName = type.getName().getLocalPart();

    int hidden = layer.isVisible() ? 1 : 0;
    ServiceInfo serviceInfo = wfs.getInfo();
    String title = serviceInfo.getTitle();
    String version = "1.0.0"; // only known entry at this time //$NON-NLS-1$
    URI source = serviceInfo.getSource();
    String get = source == null ? "" : source.toString();

    ResourceInfo resourceInfo = wfs.getFeatureSource(typeName).getInfo();
    append(4, out, "<SimpleFeatureType hidden=\"" + hidden + "\">"); // $NON-NLS-1$ //$NON-NLS-2$
    append(
        6,
        out,
        "<Server service=\"OGC:WFS\" title=\""
            + title
            + "\" version=\""
            + version
            + "\">"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    append(
        8,
        out,
        "<OnlineResource method=\"GET\" xlink:href=\""
            + get
            + "\" xlink:type=\"simple\"/>"); //$NON-NLS-1$ //$NON-NLS-2$
    append(6, out, "</Server>"); // $NON-NLS-1$
    append(6, out, "<Name>" + typeName + "</Name>"); // $NON-NLS-1$ //$NON-NLS-2$
    append(6, out, "<Title>" + resourceInfo.getTitle() + "</Title>"); // $NON-NLS-1$ //$NON-NLS-2$
    // if( !Double.isNaN( layer.getMinScaleDenominator() ))
    //        append( 6, out,
    // "<sld:MinScaleDenominator>"+layer.getMinScaleDenominator()+"</sld:MinScaleDenominator>");
    // if( !Double.isNaN( layer.getMaxScaleDenominator() ))
    //        append( 6, out,
    // "<sld:MinScaleDenominator>"+layer.getMaxScaleDenominator()+"</sld:MinScaleDenominator>");
    String SRS = "EPSG:4326";
    CoordinateReferenceSystem crs = resourceInfo.getCRS();
    // TODO: anyone knows how to get the urn for the crs object?
    append(6, out, "<SRS>" + SRS + "</SRS>"); // $NON-NLS-1$ //$NON-NLS-2$
    append(4, out, "</SimpleFeatureType>"); // $NON-NLS-1$
  }
 @Test
 public void testBackendRemovedIssue() throws Exception {
   FeatureStore<SimpleFeatureType, SimpleFeature> fs =
       (FeatureStore<SimpleFeatureType, SimpleFeature>)
           store.getFeatureSource(featureType.getName().getLocalPart());
   FilterFactory factory = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
   Expression expr2 = factory.literal("1");
   Expression expr1 = factory.property(IssuesListTestHelper.ISSUE_ID_ATTR);
   Filter filter = factory.equals(expr1, expr2);
   fs.removeFeatures(filter);
   list.refresh();
   for (IIssue issue : list) {
     System.out.println(issue.getId());
   }
   assertEquals(3, list.size());
   assertEquals("0", list.get(0).getId()); // $NON-NLS-1$
   assertEquals("2", list.get(1).getId()); // $NON-NLS-1$
   assertEquals("3", list.get(2).getId()); // $NON-NLS-1$
 }
Ejemplo n.º 22
0
  @Test
  public void testSingleType() throws IOException, NoSuchElementException {
    if (url == null) return;
    WFS_1_0_0_DataStore wfs;
    try {
      wfs = WFSDataStoreReadTest.getDataStore(url);
    } catch (ConnectException e) {
      e.printStackTrace(System.err);
      return;
    } catch (UnknownHostException e) {
      e.printStackTrace(System.err);
      return;
    } catch (NoRouteToHostException e) {
      e.printStackTrace(System.err);
      return;
    }
    String typeName = "tiger:poi";
    SimpleFeatureType type = wfs.getSchema(typeName);
    type.getTypeName();
    type.getName().getNamespaceURI();

    SimpleFeatureSource source = wfs.getFeatureSource(typeName);
    source.getBounds();

    SimpleFeatureCollection features = source.getFeatures();
    features.getBounds();
    features.getSchema();
    // features.getFeatureType();

    Query query = new Query(typeName, Filter.INCLUDE, 20, Query.ALL_NAMES, "work already");
    features = source.getFeatures(query);
    features.size();

    SimpleFeatureIterator iterator = features.features();
    while (iterator.hasNext()) {
      SimpleFeature feature = iterator.next();
    }
    iterator.close();
  }
  @Test
  public void testBackendAddedIssue() throws Exception {
    IssuesListTestHelper.createFeature(
        "new", //$NON-NLS-1$
        Resolution.IN_PROGRESS,
        Priority.CRITICAL,
        new ReferencedEnvelope(0, 10, 0, 10, crs),
        store.getFeatureWriterAppend(
            featureType.getName().getLocalPart(), Transaction.AUTO_COMMIT));
    final IssuesListEvent[] change = new IssuesListEvent[1];
    list.addListener(
        new IIssuesListListener() {

          public void notifyChange(IssuesListEvent event) {
            change[0] = event;
          }
        });
    list.refresh();
    assertEquals(5, list.size());
    assertEquals("new", list.get(4).getId()); // $NON-NLS-1$
    assertEquals(IssuesListEventType.REFRESH, change[0].getType());
  }
Ejemplo n.º 24
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();
  }
Ejemplo n.º 25
0
  /** Creates GEOMETRY_COLUMN registrations and spatial indexes for all geometry columns */
  @Override
  public void postCreateTable(String schemaName, SimpleFeatureType featureType, Connection cx)
      throws SQLException {
    schemaName = schemaName != null ? schemaName : "public";
    String tableName = featureType.getName().getLocalPart();

    Statement st = null;
    try {
      st = cx.createStatement();

      // register all geometry columns in the database
      for (AttributeDescriptor att : featureType.getAttributeDescriptors()) {
        if (att instanceof GeometryDescriptor) {
          GeometryDescriptor gd = (GeometryDescriptor) att;

          // lookup or reverse engineer the srid
          int srid = -1;
          if (gd.getUserData().get(JDBCDataStore.JDBC_NATIVE_SRID) != null) {
            srid = (Integer) gd.getUserData().get(JDBCDataStore.JDBC_NATIVE_SRID);
          } else if (gd.getCoordinateReferenceSystem() != null) {
            try {
              Integer result = CRS.lookupEpsgCode(gd.getCoordinateReferenceSystem(), true);
              if (result != null) srid = result;
            } catch (Exception e) {
              LOGGER.log(
                  Level.FINE,
                  "Error looking up the " + "epsg code for metadata " + "insertion, assuming -1",
                  e);
            }
          }

          // assume 2 dimensions, but ease future customisation
          int dimensions = 2;

          // grab the geometry type
          String geomType = CLASS_TO_TYPE_MAP.get(gd.getType().getBinding());
          if (geomType == null) geomType = "GEOMETRY";

          String sql = null;
          if (getVersion(cx).compareTo(V_2_0_0) >= 0) {
            // postgis 2 and up we don't muck with geometry_columns, we just alter the
            // type directly to set the geometry type and srid
            // setup the geometry type
            sql =
                "ALTER TABLE \""
                    + schemaName
                    + "\".\""
                    + tableName
                    + "\" "
                    + "ALTER COLUMN \""
                    + gd.getLocalName()
                    + "\" "
                    + "TYPE geometry ("
                    + geomType
                    + ", "
                    + srid
                    + ");";

            LOGGER.fine(sql);
            st.execute(sql);
          } else {
            // register the geometry type, first remove and eventual
            // leftover, then write out the real one
            sql =
                "DELETE FROM GEOMETRY_COLUMNS"
                    + " WHERE f_table_catalog=''" //
                    + " AND f_table_schema = '"
                    + schemaName
                    + "'" //
                    + " AND f_table_name = '"
                    + tableName
                    + "'" //
                    + " AND f_geometry_column = '"
                    + gd.getLocalName()
                    + "'";

            LOGGER.fine(sql);
            st.execute(sql);

            sql =
                "INSERT INTO GEOMETRY_COLUMNS VALUES (''," //
                    + "'"
                    + schemaName
                    + "'," //
                    + "'"
                    + tableName
                    + "'," //
                    + "'"
                    + gd.getLocalName()
                    + "'," //
                    + dimensions
                    + "," //
                    + srid
                    + "," //
                    + "'"
                    + geomType
                    + "')";
            LOGGER.fine(sql);
            st.execute(sql);
          }

          // add srid checks
          if (srid > -1) {
            sql =
                "ALTER TABLE " //
                    + "\""
                    + schemaName
                    + "\"" //
                    + "." //
                    + "\""
                    + tableName
                    + "\"" //
                    + " ADD CONSTRAINT \"enforce_srid_" //
                    + gd.getLocalName()
                    + "\"" //
                    + " CHECK (ST_SRID(" //
                    + "\""
                    + gd.getLocalName()
                    + "\"" //
                    + ") = "
                    + srid
                    + ")";
            LOGGER.fine(sql);
            st.execute(sql);
          }

          // add dimension checks
          sql =
              "ALTER TABLE " //
                  + "\""
                  + schemaName
                  + "\"" //
                  + "." //
                  + "\""
                  + tableName
                  + "\"" //
                  + " ADD CONSTRAINT \"enforce_dims_" //
                  + gd.getLocalName()
                  + "\"" //
                  + " CHECK (st_ndims(\""
                  + gd.getLocalName()
                  + "\")" //
                  + " = 2)";
          LOGGER.fine(sql);
          st.execute(sql);

          // add geometry type checks
          if (!geomType.equals("GEOMETRY")) {
            sql =
                "ALTER TABLE " //
                    + "\""
                    + schemaName
                    + "\"" //
                    + "." //
                    + "\""
                    + tableName
                    + "\"" //
                    + " ADD CONSTRAINT \"enforce_geotype_" //
                    + gd.getLocalName()
                    + "\"" //
                    + " CHECK (geometrytype(" //
                    + "\""
                    + gd.getLocalName()
                    + "\"" //
                    + ") = '"
                    + geomType
                    + "'::text "
                    + "OR \""
                    + gd.getLocalName()
                    + "\"" //
                    + " IS NULL)";
            LOGGER.fine(sql);
            st.execute(sql);
          }

          // add the spatial index
          sql =
              "CREATE INDEX \"spatial_"
                  + tableName //
                  + "_"
                  + gd.getLocalName().toLowerCase()
                  + "\"" //
                  + " ON " //
                  + "\""
                  + schemaName
                  + "\"" //
                  + "." //
                  + "\""
                  + tableName
                  + "\"" //
                  + " USING GIST (" //
                  + "\""
                  + gd.getLocalName()
                  + "\"" //
                  + ")";
          LOGGER.fine(sql);
          st.execute(sql);
        }
      }
      if (!cx.getAutoCommit()) {
        cx.commit();
      }
    } finally {
      dataStore.closeSafe(st);
    }
  }
Ejemplo n.º 26
0
 @Override
 public boolean isSupported(final SimpleFeature entry) {
   return entry.getName().getURI().equals(featureType.getName().getURI());
 }
  public void write(Object value, OutputStream output, Operation operation)
      throws IOException, ServiceException {
    final FeatureDiffReader[] diffReaders = (FeatureDiffReader[]) value;

    // create a new feature collcetion type with just the numbers
    VersioningTransactionConverter converter = new VersioningTransactionConverter();
    final TransactionType transaction = converter.convert(diffReaders, TransactionType.class);

    // declare wfs schema location
    BaseRequestType gft = (BaseRequestType) operation.getParameters()[0];

    Encoder encoder = new Encoder(configuration, configuration.schema());
    encodeWfsSchemaLocation(encoder, gft.getBaseUrl());

    encoder.setIndenting(true);
    encoder.setEncoding(Charset.forName(geoServer.getSettings().getCharset()));

    // set up schema locations
    // round up the info objects for each feature collection
    HashMap /* <String,Set> */ ns2metas = new HashMap();

    for (int i = 0; i < diffReaders.length; i++) {
      final FeatureDiffReader diffReader = diffReaders[i];
      final SimpleFeatureType featureType = diffReader.getSchema();

      // load the metadata for the feature type
      String namespaceURI = featureType.getName().getNamespaceURI();
      FeatureTypeInfo meta =
          geoServer
              .getCatalog()
              .getFeatureTypeByName(namespaceURI, featureType.getName().getLocalPart());

      // add it to the map
      Set metas = (Set) ns2metas.get(namespaceURI);

      if (metas == null) {
        metas = new HashSet();
        ns2metas.put(namespaceURI, metas);
      }

      metas.add(meta);
    }

    // declare application schema namespaces
    for (Iterator i = ns2metas.entrySet().iterator(); i.hasNext(); ) {
      Map.Entry entry = (Map.Entry) i.next();

      String namespaceURI = (String) entry.getKey();
      Set metas = (Set) entry.getValue();

      StringBuffer typeNames = new StringBuffer();

      for (Iterator m = metas.iterator(); m.hasNext(); ) {
        FeatureTypeInfo meta = (FeatureTypeInfo) m.next();
        typeNames.append(meta.getName());

        if (m.hasNext()) {
          typeNames.append(",");
        }
      }

      // set the schema location
      encodeTypeSchemaLocation(encoder, gft.getBaseUrl(), namespaceURI, typeNames);
    }

    try {
      encoder.encode(transaction, element, output);
    } finally {
      for (int i = 0; i < diffReaders.length; i++) {
        diffReaders[i].close();
      }
    }
  }
 public void testCreate() throws Exception {
   dataStore.createSchema(zipCodeSchema.getName(), zipCodeSchema);
   SimpleFeatureType result = (SimpleFeatureType) dataStore.getFeatureType(tname(ZIPCODE));
   assertFeatureTypesEqual(zipCodeSchema, result);
 }
  /**
   * Write SQL string to create tables in the test database based on the property files.
   *
   * @param propertyFiles Property files from app-schema-test suite.
   * @param parser The parser (WKT or an SC4O one for 3D tests)
   * @throws IllegalAttributeException
   * @throws NoSuchElementException
   * @throws IOException
   */
  private void createTables(Map<String, File> propertyFiles, String parser)
      throws IllegalAttributeException, NoSuchElementException, IOException {

    StringBuffer buf = new StringBuffer();
    StringBuffer spatialIndex = new StringBuffer();
    // drop table procedure I copied from Victor's Oracle_Data_ref_set.sql
    buf.append("CREATE OR REPLACE PROCEDURE DROP_TABLE_OR_VIEW(TabName in Varchar2) IS ")
        .append("temp number:=0;")
        .append(" tes VARCHAR2 (200) := TabName;")
        .append(" drp_stmt VARCHAR2 (200):=null;")
        .append("BEGIN select count(*) into temp from user_tables where TABLE_NAME = tes;")
        .append("if temp = 1 then drp_stmt := 'Drop Table '||tes;")
        .append("EXECUTE IMMEDIATE drp_stmt;")
        // drop views too
        .append("else select count(*) into temp from user_views where VIEW_NAME = tes;")
        .append("if temp = 1 then drp_stmt := 'Drop VIEW '||tes;")
        .append("EXECUTE IMMEDIATE drp_stmt;end if;end if;")
        .append("EXCEPTION WHEN OTHERS THEN ")
        .append(
            "raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);")
        .append("END DROP_TABLE_OR_VIEW;\n");

    for (String fileName : propertyFiles.keySet()) {
      File file = new File(propertyFiles.get(fileName), fileName);

      try (PropertyFeatureReader reader = new PropertyFeatureReader("test", file)) {
        SimpleFeatureType schema = reader.getFeatureType();
        String tableName = schema.getName().getLocalPart().toUpperCase();
        // drop table if exists
        buf.append("CALL DROP_TABLE_OR_VIEW('").append(tableName).append("')\n");
        // create the table
        buf.append("CREATE TABLE ").append(tableName).append("(");
        // + pkey
        int size = schema.getAttributeCount() + 1;
        String[] fieldNames = new String[size];
        List<String> createParams = new ArrayList<String>();
        int j = 0;
        String type;
        String field;
        int spatialIndexCounter = 0;
        for (PropertyDescriptor desc : schema.getDescriptors()) {
          field = desc.getName().toString().toUpperCase();
          fieldNames[j] = field;
          if (desc instanceof GeometryDescriptor) {
            type = "SDO_GEOMETRY";
            // Update spatial index
            int srid = getSrid(((GeometryType) desc.getType()));

            spatialIndex
                .append("DELETE FROM user_sdo_geom_metadata WHERE table_name = '")
                .append(tableName)
                .append("'\n");

            spatialIndex
                .append("Insert into user_sdo_geom_metadata ")
                .append("(TABLE_NAME,COLUMN_NAME,DIMINFO,SRID)")
                .append("values ('")
                .append(tableName)
                .append("','")
                .append(field)
                .append("',MDSYS.SDO_DIM_ARRAY(MDSYS.SDO_DIM_ELEMENT('X',140.962,144.909,0.00001),")
                .append("MDSYS.SDO_DIM_ELEMENT('Y',-38.858,-33.98,0.00001)")
                .append( // support 3d index
                    ((GeometryDescriptor) desc).getCoordinateReferenceSystem() != null
                            && ((GeometryDescriptor) desc)
                                    .getCoordinateReferenceSystem()
                                    .getCoordinateSystem()
                                    .getDimension()
                                == 3
                        ? ", MDSYS.SDO_DIM_ELEMENT('Z',-100000, 100000, 1) ),"
                        : "),")
                .append(srid)
                .append(")\n");

            // ensure it's <= 30 characters to avoid Oracle exception
            String indexName =
                (tableName.length() <= 26 ? tableName : tableName.substring(0, 26)) + "_IDX";
            if (spatialIndexCounter > 0) {
              // to avoid duplicate index name when there are > 1 geometry in the same table
              indexName += spatialIndexCounter;
            }

            spatialIndex
                .append("CREATE INDEX \"")
                .append(indexName)
                .append("\" ON \"")
                .append(tableName)
                .append("\"(\"")
                .append(field)
                .append("\") ")
                .append("INDEXTYPE IS \"MDSYS\".\"SPATIAL_INDEX\"\n");
            spatialIndexCounter++;
          } else {
            type = Classes.getShortName(desc.getType().getBinding());
            if (type.equalsIgnoreCase("String")) {
              type = "NVARCHAR2(250)";
            } else if (type.equalsIgnoreCase("Double")) {
              type = "NUMBER";
            }
            // etc. assign as required
          }
          createParams.add(field + " " + type);
          j++;
        }
        // Add numeric PK for sorting
        fieldNames[j] = "PKEY";
        createParams.add("PKEY VARCHAR2(30)");
        buf.append(StringUtils.join(createParams.iterator(), ", "));
        buf.append(")\n");
        buf.append(
            "ALTER TABLE " + tableName + " ADD CONSTRAINT " + tableName + " PRIMARY KEY (PKEY)\n");
        // then insert rows
        SimpleFeature feature;
        FeatureId id;
        while (reader.hasNext()) {
          buf.append("INSERT INTO ").append(tableName).append("(");
          feature = reader.next();
          buf.append(StringUtils.join(fieldNames, ", "));
          buf.append(") ");
          buf.append("VALUES (");
          Collection<Property> properties = feature.getProperties();
          String[] values = new String[size];
          int valueIndex = 0;
          for (Property prop : properties) {
            Object value = prop.getValue();
            if (value instanceof Geometry) {
              // use wkt writer to convert geometry to string, so third dimension can be supported
              // if present.
              Geometry geom = (Geometry) value;
              value = new WKTWriter(geom.getCoordinate().z == Double.NaN ? 2 : 3).write(geom);
            }
            if (value == null || value.toString().equalsIgnoreCase("null")) {
              values[valueIndex] = "null";
            } else if (prop.getType() instanceof GeometryType) {
              int srid = getSrid(((GeometryType) prop.getType()));
              StringBuffer geomValue = new StringBuffer(parser + "('");
              geomValue.append(value).append("'");
              if (srid > -1) {
                // attach srid
                geomValue.append(", ").append(srid);
              }
              geomValue.append(")");
              values[valueIndex] = geomValue.toString();
            } else if (prop.getType().getBinding().getSimpleName().equalsIgnoreCase("DATE")) {
              values[valueIndex] = "TO_DATE('" + value + "', 'yyyy-MM-dd')";
            } else {
              values[valueIndex] = "'" + value + "'";
            }
            valueIndex++;
          }
          id = feature.getIdentifier();
          // insert primary key
          values[valueIndex] = "'" + id.toString() + "'";
          buf.append(StringUtils.join(values, ","));
          buf.append(")\n");
        }
      }
      buf.append(spatialIndex.toString());
      spatialIndex.delete(0, spatialIndex.length());
      if (buf.length() > 0) {
        this.sql = buf.toString();
      }
    }
  }
Ejemplo n.º 30
0
  public static SimpleFeatureType createSubType(
      SimpleFeatureType featureType,
      String[] properties,
      CoordinateReferenceSystem override,
      String typeName,
      URI namespace)
      throws SchemaException {

    if ((properties == null) && (override == null)) {
      return featureType;
    }

    if (properties == null) {
      properties = new String[featureType.getAttributeCount()];
      for (int i = 0; i < properties.length; i++) {
        properties[i] = featureType.getDescriptor(i).getLocalName();
      }
    }

    String namespaceURI = namespace != null ? namespace.toString() : null;
    boolean same =
        featureType.getAttributeCount() == properties.length
            && featureType.getTypeName().equals(typeName)
            && Utilities.equals(featureType.getName().getNamespaceURI(), namespaceURI);

    for (int i = 0; (i < featureType.getAttributeCount()) && same; i++) {
      AttributeDescriptor type = featureType.getDescriptor(i);
      same =
          type.getLocalName().equals(properties[i])
              && (((override != null) && type instanceof GeometryDescriptor)
                  ? assertEquals(
                      override, ((GeometryDescriptor) type).getCoordinateReferenceSystem())
                  : true);
    }

    if (same) {
      return featureType;
    }

    AttributeDescriptor[] types = new AttributeDescriptor[properties.length];

    for (int i = 0; i < properties.length; i++) {
      types[i] = featureType.getDescriptor(properties[i]);

      if ((override != null) && types[i] instanceof GeometryDescriptor) {
        AttributeTypeBuilder ab = new AttributeTypeBuilder();
        ab.init(types[i]);
        ab.setCRS(override);
        types[i] = ab.buildDescriptor(types[i].getLocalName(), ab.buildGeometryType());
      }
    }

    if (typeName == null) typeName = featureType.getTypeName();
    if (namespace == null && featureType.getName().getNamespaceURI() != null)
      try {
        namespace = new URI(featureType.getName().getNamespaceURI());
      } catch (URISyntaxException e) {
        throw new RuntimeException(e);
      }

    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
    tb.setName(typeName);
    tb.setNamespaceURI(namespace);
    tb.addAll(types);

    return tb.buildFeatureType();
  }