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

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

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

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

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

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

      if (Geometry.class.isAssignableFrom(binding)) {
        CoordinateReferenceSystem crs;
        AttributeType originalAttributeType = origional.getType(name);
        if (originalAttributeType != null && originalAttributeType instanceof GeometryType) {
          GeometryType geometryType = (GeometryType) originalAttributeType;
          crs = geometryType.getCoordinateReferenceSystem();
        } else {
          crs = origional.getCoordinateReferenceSystem();
        }
        build.crs(crs);
        build.add(name, binding);
      } else {
        build.add(name, binding);
      }
    }
    build.setName(origional.getTypeName());
    return build.buildFeatureType();
  }
Ejemplo n.º 2
0
 private void register(AttributeType type, boolean anonymous) {
   Name name = type.getName();
   Object old;
   if (anonymous) {
     old = anonTypeRegistry.put(name, type);
   } else {
     old = typeRegistry.put(name, type);
   }
   if (old != null) {
     LOGGER.fine(type.getName() + " replaced by new value.");
   }
 }
  public NonFeatureTypeProxy(
      final AttributeType type,
      final FeatureTypeMapping mapping,
      Collection<PropertyDescriptor> schema) {
    super(type.getName(), null);

    subject = type;

    AttributeDescriptor originalTarget = mapping.getTargetFeature();
    int maxOccurs = originalTarget.getMaxOccurs();
    int minOccurs = originalTarget.getMinOccurs();
    boolean nillable = originalTarget.isNillable();
    Object defaultValue = originalTarget.getDefaultValue();
    Name name = originalTarget.getName();

    // create a new descriptor with the wrapped type and set it to the mapping
    ComplexFeatureTypeFactoryImpl typeFactory = new ComplexFeatureTypeFactoryImpl();
    AttributeDescriptor descriptor =
        typeFactory.createAttributeDescriptor(
            this, name, minOccurs, maxOccurs, nillable, defaultValue);
    descriptor.getUserData().putAll(originalTarget.getUserData());
    mapping.setTargetFeature(descriptor);
    // smuggle FEATURE_LINK descriptor
    schema.add(ComplexFeatureConstants.FEATURE_CHAINING_LINK);
    this.descriptors = schema;
  }
    AttributeType findType(Class binding) {
      for (Schema schema : typeMappingProfiles) {
        for (Map.Entry<Name, AttributeType> e : schema.entrySet()) {
          AttributeType at = e.getValue();
          if (at.getBinding() != null && at.getBinding().equals(binding)) {
            return at;
          }
        }

        for (AttributeType at : schema.values()) {
          if (binding.isAssignableFrom(at.getBinding())) {
            return at;
          }
        }
      }
      return null;
    }
  /**
   * Used to supply a list of suggested values; given the provided attribtue descriptor.
   *
   * @param descriptor
   * @return list of suggested values (may be empty if no values are suggested)
   */
  protected SortedSet<String> generateSuggestedValues(AttributeDescriptor descriptor) {
    SortedSet<String> options = new TreeSet<String>();

    Object defaultValue = descriptor.getDefaultValue();
    if (defaultValue != null) {
      options.add(String.valueOf(defaultValue));
    }
    AttributeType type = descriptor.getType();
    if (Number.class.isAssignableFrom(type.getBinding())) {
      options.add("0");
      options.add("1");
      options.add("2");
      options.add("3");
      options.add("4");
      options.add("5");
    }
    return options;
  }
 /**
  * Parses the value of the current attribute, parser cursor shall be on a feature attribute
  * START_TAG event.
  *
  * @return
  * @throws IOException
  * @throws XmlPullParserException
  * @throws FactoryException
  * @throws NoSuchAuthorityCodeException
  */
 @SuppressWarnings("unchecked")
 private Object parseAttributeValue() throws XmlPullParserException, IOException {
   final String name = parser.getName();
   final AttributeDescriptor attribute = expectedProperties.get(name);
   final AttributeType type = attribute.getType();
   Object parsedValue;
   if (type instanceof GeometryType) {
     parser.nextTag();
     try {
       parsedValue = parseGeom();
     } catch (NoSuchAuthorityCodeException e) {
       throw new DataSourceException(e);
     } catch (FactoryException e) {
       throw new DataSourceException(e);
     }
   } else {
     String rawTextValue = parser.nextText();
     Class binding = type.getBinding();
     parsedValue = Converters.convert(rawTextValue, binding);
   }
   return parsedValue;
 }
Ejemplo n.º 7
0
  private AttributeDescriptor createAttributeDescriptor(
      AttributeType type,
      CoordinateReferenceSystem crs,
      Name elemName,
      int minOccurs,
      int maxOccurs,
      boolean nillable,
      Object defaultValue) {
    AttributeDescriptor descriptor = null;
    if (maxOccurs == -1) {
      // this happens when maxOccurs is set to "unbounded"
      maxOccurs = Integer.MAX_VALUE;
    }

    if (!(type instanceof AttributeTypeProxy)
        && Geometry.class.isAssignableFrom(type.getBinding())) {
      // create geometry descriptor with the simple feature type CRS
      GeometryType geomType =
          new GeometryTypeImpl(
              type.getName(),
              type.getBinding(),
              crs,
              type.isIdentified(),
              type.isAbstract(),
              type.getRestrictions(),
              type.getSuper(),
              type.getDescription());
      descriptor =
          typeFactory.createGeometryDescriptor(
              geomType, elemName, minOccurs, maxOccurs, nillable, defaultValue);
    } else {
      descriptor =
          typeFactory.createAttributeDescriptor(
              type, elemName, minOccurs, maxOccurs, nillable, defaultValue);
    }
    return descriptor;
  }
Ejemplo n.º 8
0
  /**
   * create a FeatureSource with the specified Query
   *
   * @param entry
   * @param query - a query containing a filter that will be applied to the data
   */
  public ExcelFeatureSource(ContentEntry entry, Query query) {
    super(entry, query);
    Date beginingOfExcelTime = HSSFDateUtil.getJavaDate(0);

    dataStore = (ExcelDataStore) entry.getDataStore();

    sheet = dataStore.getSheet();
    latCol = dataStore.getLatColumnIndex();
    lonCol = dataStore.getLonColumnIndex();
    int rows = sheet.getPhysicalNumberOfRows();
    int start = dataStore.getHeaderRowIndex() + 1;
    latCol = dataStore.getLatColumnIndex();
    lonCol = dataStore.getLonColumnIndex();
    features = new ArrayList<SimpleFeature>();
    filteredFeatures = new ArrayList<SimpleFeature>();
    evaluator = dataStore.workbook.getCreationHelper().createFormulaEvaluator();
    if (schema == null) {
      schema = getSchema();
    }
    GeometryFactory geometryFactory = dataStore.getGeometryFactory();

    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(schema);
    Row header = sheet.getRow(dataStore.getHeaderRowIndex());
    for (int i = start; i < rows; i++) {
      Row data = sheet.getRow(i);
      double x = 0.0;
      double y = 0.0;
      for (int col = data.getFirstCellNum(); col < data.getLastCellNum(); col++) {
        final Cell cell = data.getCell(col);
        CellValue value = evaluator.evaluate(cell);
        if (col == latCol) {

          if (value.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            y = value.getNumberValue();
          }
        } else if (col == lonCol) {
          if (value.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            x = value.getNumberValue();
          }
        } else {
          // cast and handle
          final String name = header.getCell(col).getStringCellValue().trim();
          switch (value.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
              AttributeType type = schema.getType(name);
              Class<?> clazz = type.getBinding();
              if (clazz == Double.class) {
                builder.set(name, value.getNumberValue());
              } else if (clazz == java.sql.Date.class) {
                final java.util.Date javaDate = HSSFDateUtil.getJavaDate(value.getNumberValue());
                final Calendar cal = Calendar.getInstance();
                cal.clear();
                cal.setTime(javaDate);
                java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
                builder.set(name, date);
              } else if (clazz == java.util.Date.class) {
                final java.util.Date javaDate = HSSFDateUtil.getJavaDate(value.getNumberValue());
                builder.set(name, javaDate);
              } else if (clazz == Time.class) {
                final java.util.Date javaDate = HSSFDateUtil.getJavaDate(value.getNumberValue());
                final Calendar cal = Calendar.getInstance();
                cal.clear();
                cal.setTime(javaDate);
                cal.set(0, 0, 0);
                Time time = new Time(cal.getTimeInMillis());
                builder.set(name, time);
              }
              break;
            case Cell.CELL_TYPE_STRING:
              builder.set(name, value.getStringValue().trim());
              break;
            case Cell.CELL_TYPE_BOOLEAN:
              builder.set(name, value.getBooleanValue());
              break;

            default:
              System.out.println(
                  "We don't handle "
                      + cell.getCellType()
                      + " type cells "
                      + cell.getStringCellValue());
          }
        }
      }
      Point p = geometryFactory.createPoint(new Coordinate(x, y));
      builder.set("the_geom", p);

      SimpleFeature feature = builder.buildFeature(null);
      features.add(feature);
    }
    filterFeatures(query);
  }
Ejemplo n.º 9
0
  /**
   * Creates an {@link AttributeType} that matches the xsd type definition as much as possible.
   *
   * <p>The original type definition given by the {@link XSDTypeDefinition} is kept as
   * AttributeType's metadata stored as a "user data" property using <code>XSDTypeDefinition.class
   * </code> as key.
   *
   * <p>If it is a complex attribute, it will contain all the properties declared in the <code>
   * typeDefinition</code>, as well as all the properties declared in its super types. TODO: handle
   * the case where the extension mechanism is restriction.
   *
   * @param assignedName
   * @param typeDefinition
   * @return
   */
  private AttributeType createType(
      final Name assignedName,
      final XSDTypeDefinition typeDefinition,
      CoordinateReferenceSystem crs,
      boolean anonymous) {

    AttributeType attType;
    // /////////
    if (processingTypes.contains(assignedName)) {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Recursion found for type " + assignedName + ". Proxying it.");
      }
      attType =
          createProxiedType(
              assignedName, typeDefinition, anonymous ? anonTypeRegistry : typeRegistry);
      return attType;
    }
    processingTypes.push(assignedName);
    // //////////

    final XSDTypeDefinition baseType = typeDefinition.getBaseType();

    AttributeType superType = null;
    if (baseType != null) {
      String targetNamespace = baseType.getTargetNamespace();
      String name = baseType.getName();
      if (name != null) {
        Name baseTypeName = new NameImpl(targetNamespace, name);
        superType = getAttributeType(baseTypeName, baseType, crs);
      }
    } else {
      LOGGER.warning(assignedName + " has no super type");
    }

    if (typeDefinition instanceof XSDComplexTypeDefinition) {
      XSDComplexTypeDefinition complexTypeDef;
      complexTypeDef = (XSDComplexTypeDefinition) typeDefinition;
      boolean includeParents = true;
      List<XSDElementDeclaration> children =
          Schemas.getChildElementDeclarations(typeDefinition, includeParents);

      final Collection<PropertyDescriptor> schema =
          new ArrayList<PropertyDescriptor>(children.size());

      XSDElementDeclaration childDecl;
      AttributeDescriptor descriptor;
      for (Iterator it = children.iterator(); it.hasNext(); ) {
        childDecl = (XSDElementDeclaration) it.next();
        try {
          descriptor = createAttributeDescriptor(complexTypeDef, childDecl, crs);
        } catch (NoSuchElementException e) {
          String msg =
              "Failed to create descriptor for '"
                  + childDecl.getTargetNamespace()
                  + "#"
                  + childDecl.getName()
                  + " from container '"
                  + typeDefinition.getTargetNamespace()
                  + "#"
                  + typeDefinition.getName()
                  + "'";
          NoSuchElementException nse = new NoSuchElementException(msg);
          nse.initCause(e);
          throw nse;
        }
        schema.add(descriptor);
      }

      if (includeAttributes) {
        for (XSDAttributeUse attgcontent : complexTypeDef.getAttributeUses()) {
          XSDAttributeDeclaration att = attgcontent.getContent();
          descriptor =
              createAttributeDescriptor(
                  getXmlAttributeType(),
                  null,
                  new NameImpl(null, "@" + att.getName()),
                  0,
                  1,
                  false,
                  null);
          schema.add(descriptor);
        }
      }

      // set substitution group for descriptors here
      for (XSDElementDeclaration elemDecl : children) {
        if (elemDecl.isElementDeclarationReference()) {
          elemDecl = elemDecl.getResolvedElementDeclaration();
        }
        PropertyDescriptor att = null;
        for (PropertyDescriptor desc : schema) {
          if (desc.getName().getLocalPart().equals(elemDecl.getName())
              && desc.getName().getNamespaceURI().equals(elemDecl.getTargetNamespace())) {
            att = desc;
            break;
          }
        }
        setSubstitutionGroup(complexTypeDef, elemDecl, att, crs);
      }
      attType = createComplexAttributeType(assignedName, schema, complexTypeDef, superType);
    } else {
      Class<?> binding = String.class;
      boolean isIdentifiable = false;
      boolean isAbstract = false;
      List<Filter> restrictions = Collections.emptyList();
      InternationalString description = null;
      attType =
          typeFactory.createAttributeType(
              assignedName,
              binding,
              isIdentifiable,
              isAbstract,
              restrictions,
              superType,
              description);
    }

    attType.getUserData().put(XSDTypeDefinition.class, typeDefinition);

    processingTypes.pop();

    // even if the type is anonymous, it still has to be registered somewhere because
    // it's needed for the proxied types to find them. That's why we have 2 registries,
    // typeRegistry
    // and anonTypeRegistry. TypeRegistry is the global one, since anonymous types are meant to
    // be
    // local and shouldn't be searchable.
    register(attType, anonymous);

    return attType;
  }
 /**
  * Specifies an attribute type binding.
  *
  * <p>This method is used to associate an attribute type with a java class. The class is retreived
  * from <code>type.getBinding()</code>. When the {@link #add(String, Class)} method is used to add
  * an attribute to the type being built, this binding is used to locate the attribute type.
  *
  * @param type The attribute type.
  */
 public void addBinding(AttributeType type) {
   bindings().put(type.getBinding(), type);
 }