Esempio n. 1
0
    @Override
    public Void call() {
      RevTree tree = builder.build();

      Node treeNode;
      {
        ObjectId treeMetadataId = builder.getDefaultMetadataId();
        String name = NodeRef.nodeFromPath(treePath);
        ObjectId oid = tree.getId();
        Envelope bounds = SpatialOps.boundsOf(tree);
        treeNode = Node.create(name, oid, treeMetadataId, RevObject.TYPE.TREE, bounds);
      }

      final String parentPath = NodeRef.parentPath(treePath);
      final ObjectId parentMetadataId;
      if (NodeRef.ROOT.equals(parentPath)) {
        parentMetadataId = ObjectId.NULL;
      } else {
        Optional<NodeRef> parentRef =
            context
                .command(FindTreeChild.class)
                .setChildPath(parentPath)
                .setIndex(true)
                .setParent(workHead)
                .setParentPath(NodeRef.ROOT)
                .call();

        parentMetadataId = parentRef.isPresent() ? parentRef.get().getMetadataId() : ObjectId.NULL;
      }
      NodeRef newTreeRef = new NodeRef(treeNode, parentPath, parentMetadataId);
      target.put(newTreeRef, tree);
      return null;
    }
Esempio n. 2
0
  private NodeRef findOrCreateTree(final String treePath, final FeatureType type) {

    RevTree tree =
        context
            .command(FindOrCreateSubtree.class)
            .setChildPath(treePath)
            .setIndex(true)
            .setParent(workHead)
            .setParentPath(NodeRef.ROOT)
            .call();

    ObjectId metadataId = ObjectId.NULL;
    if (type != null) {
      RevFeatureType revFeatureType = RevFeatureTypeImpl.build(type);
      if (tree.isEmpty()) {
        indexDatabase.put(revFeatureType);
      }
      metadataId = revFeatureType.getId();
    }
    Envelope bounds = SpatialOps.boundsOf(tree);
    Node node =
        Node.create(NodeRef.nodeFromPath(treePath), tree.getId(), metadataId, TYPE.TREE, bounds);

    String parentPath = NodeRef.parentPath(treePath);
    return new NodeRef(node, parentPath, ObjectId.NULL);
  }
Esempio n. 3
0
 /** Provides for natural ordering of {@code NodeRef}, based on {@link #path()} */
 @Override
 public int compareTo(NodeRef o) {
   int c = parentPath.compareTo(o.getParentPath());
   if (c == 0) {
     return node.compareTo(o.getNode());
   }
   return c;
 }
Esempio n. 4
0
 /**
  * Tests equality over another {@code NodeRef} based on {@link #getParentPath() parent path},
  * {@link #getNode() node} name and id, and {@link #getMetadataId()}
  */
 @Override
 public boolean equals(Object o) {
   if (!(o instanceof NodeRef)) {
     return false;
   }
   NodeRef r = (NodeRef) o;
   return parentPath.equals(r.parentPath)
       && node.equals(r.node)
       && getMetadataId().equals(r.getMetadataId());
 }
Esempio n. 5
0
  private RevTreeBuilder2 createBuilder(String treePath, FeatureType type) {

    final NodeRef treeRef = findOrCreateTree(treePath, type);
    final ObjectId treeId = treeRef.objectId();
    final RevTree origTree = indexDatabase.getTree(treeId);

    ObjectId defaultMetadataId = treeRef.getMetadataId();

    RevTreeBuilder2 builder;
    Platform platform = context.platform();
    builder =
        new RevTreeBuilder2(indexDatabase, origTree, defaultMetadataId, platform, executorService);
    return builder;
  }
Esempio n. 6
0
  private static void addElement(
      List<String> lines, Patch patch, Map<String, RevFeatureType> featureTypes)
      throws IOException {
    String[] headerTokens = lines.get(0).split("\t");
    if (headerTokens.length == 4 || headerTokens.length == 3) { // feature or feature type
      // modified // modification
      if (lines.size() == 1) { // feature type
        FeatureTypeDiff diff =
            new FeatureTypeDiff(
                headerTokens[0],
                ObjectId.valueOf(headerTokens[1]),
                ObjectId.valueOf(headerTokens[2]));
        patch.addAlteredTree(diff);
      } else { // feature
        String element = Joiner.on("\n").join(lines.subList(1, lines.size()));
        ByteArrayInputStream stream;
        stream = new ByteArrayInputStream(element.getBytes(Charsets.UTF_8));
        String operation = headerTokens[0].trim();
        if (operation.equals("M")) {
          String fullPath = headerTokens[1].trim();
          String oldMetadataId = headerTokens[2].trim();
          String newMetadataId = headerTokens[3].trim();
          RevFeatureType newRevFeatureType = featureTypes.get(newMetadataId);
          RevFeatureType oldRevFeatureType = featureTypes.get(oldMetadataId);

          Map<PropertyDescriptor, AttributeDiff> map = Maps.newHashMap();
          for (int i = 1; i < lines.size(); i++) {
            addDifference(lines.get(i), map, oldRevFeatureType, newRevFeatureType);
          }
          FeatureDiff featureDiff =
              new FeatureDiff(fullPath, map, oldRevFeatureType, newRevFeatureType);
          patch.addModifiedFeature(featureDiff);
        } else if (operation.equals("A") || operation.equals("R")) {
          String fullPath = headerTokens[1].trim();
          String featureTypeId = headerTokens[2].trim();
          RevFeatureType revFeatureType;
          revFeatureType = featureTypes.get(featureTypeId);
          FeatureBuilder featureBuilder = new FeatureBuilder(revFeatureType);
          RevFeature revFeature = (RevFeature) serializer.read(null, stream);
          Feature feature = featureBuilder.build(NodeRef.nodeFromPath(fullPath), revFeature);
          if (operation.equals("R")) {
            patch.addRemovedFeature(fullPath, feature, revFeatureType);
          } else {
            patch.addAddedFeature(fullPath, feature, revFeatureType);
          }
        } else {
          throw new IllegalArgumentException("Wrong patch content: " + lines.get(0));
        }
      }

    } else if (headerTokens.length == 1) { // feature type definition
      String element = Joiner.on("\n").join(lines);
      ByteArrayInputStream stream = new ByteArrayInputStream(element.getBytes(Charsets.UTF_8));
      String[] tokens = lines.get(1).split("\t");
      RevFeatureType featureType = (RevFeatureType) serializer.read(null, stream);
      featureTypes.put(featureType.getId().toString(), featureType);
    } else {
      throw new IllegalArgumentException("Wrong patch content: " + lines.get(0));
    }
  }
Esempio n. 7
0
  /**
   * Executes the export operation using the parameters that have been specified.
   *
   * @return a FeatureCollection with the specified features
   */
  @Override
  protected SimpleFeatureStore _call() {
    final ObjectDatabase database = objectDatabase();
    if (filterFeatureTypeId != null) {
      RevObject filterType = database.getIfPresent(filterFeatureTypeId);
      checkArgument(
          filterType instanceof RevFeatureType, "Provided filter feature type is does not exist");
    }

    final SimpleFeatureStore targetStore = getTargetStore();

    final String refspec = resolveRefSpec();
    final String treePath = refspec.substring(refspec.indexOf(':') + 1);
    final RevTree rootTree = resolveRootTree(refspec);
    final NodeRef typeTreeRef = resolTypeTreeRef(refspec, treePath, rootTree);

    final ObjectId defaultMetadataId = typeTreeRef.getMetadataId();

    final RevTree typeTree = database.getTree(typeTreeRef.getObjectId());

    final ProgressListener progressListener = getProgressListener();

    progressListener.started();
    progressListener.setDescription(
        "Exporting from " + path + " to " + targetStore.getName().getLocalPart() + "... ");

    final Iterator<SimpleFeature> filtered;
    {
      final Iterator<SimpleFeature> plainFeatures =
          getFeatures(typeTree, database, defaultMetadataId, progressListener);

      Iterator<SimpleFeature> adaptedFeatures = adaptToArguments(plainFeatures, defaultMetadataId);

      Iterator<Optional<Feature>> transformed =
          Iterators.transform(adaptedFeatures, ExportOp.this.function);

      Iterator<SimpleFeature> result =
          Iterators.filter(
              Iterators.transform(
                  transformed,
                  new Function<Optional<Feature>, SimpleFeature>() {
                    @Override
                    public SimpleFeature apply(Optional<Feature> input) {
                      return (SimpleFeature) input.orNull();
                    }
                  }),
              Predicates.notNull());

      // check the resulting schema has something to contribute
      PeekingIterator<SimpleFeature> peekingIt = Iterators.peekingIterator(result);
      if (peekingIt.hasNext()) {
        Function<AttributeDescriptor, String> toString =
            new Function<AttributeDescriptor, String>() {
              @Override
              public String apply(AttributeDescriptor input) {
                return input.getLocalName();
              }
            };
        SimpleFeature peek = peekingIt.peek();
        Set<String> sourceAtts =
            new HashSet<String>(
                Lists.transform(peek.getFeatureType().getAttributeDescriptors(), toString));
        Set<String> targetAtts =
            new HashSet<String>(
                Lists.transform(targetStore.getSchema().getAttributeDescriptors(), toString));
        if (Sets.intersection(sourceAtts, targetAtts).isEmpty()) {
          throw new GeoToolsOpException(
              StatusCode.UNABLE_TO_ADD,
              "No common attributes between source and target feature types");
        }
      }

      filtered = peekingIt;
    }
    FeatureCollection<SimpleFeatureType, SimpleFeature> asFeatureCollection =
        new BaseFeatureCollection<SimpleFeatureType, SimpleFeature>() {

          @Override
          public FeatureIterator<SimpleFeature> features() {

            return new DelegateFeatureIterator<SimpleFeature>(filtered);
          }
        };

    // add the feature collection to the feature store
    final Transaction transaction;
    if (transactional) {
      transaction = new DefaultTransaction("create");
    } else {
      transaction = Transaction.AUTO_COMMIT;
    }
    try {
      targetStore.setTransaction(transaction);
      try {
        targetStore.addFeatures(asFeatureCollection);
        transaction.commit();
      } catch (final Exception e) {
        if (transactional) {
          transaction.rollback();
        }
        Throwables.propagateIfInstanceOf(e, GeoToolsOpException.class);
        throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_ADD);
      } finally {
        transaction.close();
      }
    } catch (IOException e) {
      throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_ADD);
    }

    progressListener.complete();

    return targetStore;
  }
Esempio n. 8
0
 /**
  * Returns the full path from the root tree to the object this ref points to
  *
  * <p>This is a derived property, shortcut for <code>
  * {@link #getParentPath()} + "/" + getNode().getName() </code>
  */
 public String path() {
   return NodeRef.appendChild(parentPath, node.getName());
 }
  public void post(Representation entity) {
    InputStream input = null;

    try {
      input = getRequest().getEntity().getStream();
      final GeoGIG ggit = getGeogig(getRequest()).get();
      final Reader body = new InputStreamReader(input);
      final JsonParser parser = new JsonParser();
      final JsonElement conflictJson = parser.parse(body);

      if (conflictJson.isJsonObject()) {
        final JsonObject conflict = conflictJson.getAsJsonObject();
        String featureId = null;
        RevFeature ourFeature = null;
        RevFeatureType ourFeatureType = null;
        RevFeature theirFeature = null;
        RevFeatureType theirFeatureType = null;
        JsonObject merges = null;
        if (conflict.has("path") && conflict.get("path").isJsonPrimitive()) {
          featureId = conflict.get("path").getAsJsonPrimitive().getAsString();
        }
        Preconditions.checkState(featureId != null);

        if (conflict.has("ours") && conflict.get("ours").isJsonPrimitive()) {
          String ourCommit = conflict.get("ours").getAsJsonPrimitive().getAsString();
          Optional<NodeRef> ourNode = parseID(ObjectId.valueOf(ourCommit), featureId, ggit);
          if (ourNode.isPresent()) {
            Optional<RevObject> object =
                ggit.command(RevObjectParse.class).setObjectId(ourNode.get().objectId()).call();
            Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature);

            ourFeature = (RevFeature) object.get();

            object =
                ggit.command(RevObjectParse.class)
                    .setObjectId(ourNode.get().getMetadataId())
                    .call();
            Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType);

            ourFeatureType = (RevFeatureType) object.get();
          }
        }

        if (conflict.has("theirs") && conflict.get("theirs").isJsonPrimitive()) {
          String theirCommit = conflict.get("theirs").getAsJsonPrimitive().getAsString();
          Optional<NodeRef> theirNode = parseID(ObjectId.valueOf(theirCommit), featureId, ggit);
          if (theirNode.isPresent()) {
            Optional<RevObject> object =
                ggit.command(RevObjectParse.class).setObjectId(theirNode.get().objectId()).call();
            Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature);

            theirFeature = (RevFeature) object.get();

            object =
                ggit.command(RevObjectParse.class)
                    .setObjectId(theirNode.get().getMetadataId())
                    .call();
            Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType);

            theirFeatureType = (RevFeatureType) object.get();
          }
        }

        if (conflict.has("merges") && conflict.get("merges").isJsonObject()) {
          merges = conflict.get("merges").getAsJsonObject();
        }
        Preconditions.checkState(merges != null);

        Preconditions.checkState(ourFeatureType != null || theirFeatureType != null);

        SimpleFeatureBuilder featureBuilder =
            new SimpleFeatureBuilder(
                (SimpleFeatureType)
                    (ourFeatureType != null ? ourFeatureType.type() : theirFeatureType.type()));

        ImmutableList<PropertyDescriptor> descriptors =
            (ourFeatureType == null ? theirFeatureType : ourFeatureType).sortedDescriptors();

        for (Entry<String, JsonElement> entry : merges.entrySet()) {
          int descriptorIndex = getDescriptorIndex(entry.getKey(), descriptors);
          if (descriptorIndex != -1 && entry.getValue().isJsonObject()) {
            PropertyDescriptor descriptor = descriptors.get(descriptorIndex);
            JsonObject attributeObject = entry.getValue().getAsJsonObject();
            if (attributeObject.has("ours")
                && attributeObject.get("ours").isJsonPrimitive()
                && attributeObject.get("ours").getAsBoolean()) {
              featureBuilder.set(
                  descriptor.getName(),
                  ourFeature == null ? null : ourFeature.getValues().get(descriptorIndex).orNull());
            } else if (attributeObject.has("theirs")
                && attributeObject.get("theirs").isJsonPrimitive()
                && attributeObject.get("theirs").getAsBoolean()) {
              featureBuilder.set(
                  descriptor.getName(),
                  theirFeature == null
                      ? null
                      : theirFeature.getValues().get(descriptorIndex).orNull());
            } else if (attributeObject.has("value")
                && attributeObject.get("value").isJsonPrimitive()) {
              JsonPrimitive primitive = attributeObject.get("value").getAsJsonPrimitive();
              if (primitive.isString()) {
                try {
                  Object object =
                      valueFromString(
                          FieldType.forBinding(descriptor.getType().getBinding()),
                          primitive.getAsString());
                  featureBuilder.set(descriptor.getName(), object);
                } catch (Exception e) {
                  throw new Exception(
                      "Unable to convert attribute ("
                          + entry.getKey()
                          + ") to required type: "
                          + descriptor.getType().getBinding().toString());
                }
              } else if (primitive.isNumber()) {
                try {
                  Object value =
                      valueFromNumber(
                          FieldType.forBinding(descriptor.getType().getBinding()),
                          primitive.getAsNumber());
                  featureBuilder.set(descriptor.getName(), value);
                } catch (Exception e) {
                  throw new Exception(
                      "Unable to convert attribute ("
                          + entry.getKey()
                          + ") to required type: "
                          + descriptor.getType().getBinding().toString());
                }
              } else if (primitive.isBoolean()) {
                try {
                  Object value =
                      valueFromBoolean(
                          FieldType.forBinding(descriptor.getType().getBinding()),
                          primitive.getAsBoolean());
                  featureBuilder.set(descriptor.getName(), value);
                } catch (Exception e) {
                  throw new Exception(
                      "Unable to convert attribute ("
                          + entry.getKey()
                          + ") to required type: "
                          + descriptor.getType().getBinding().toString());
                }
              } else if (primitive.isJsonNull()) {
                featureBuilder.set(descriptor.getName(), null);
              } else {
                throw new Exception(
                    "Unsupported JSON type for attribute value (" + entry.getKey() + ")");
              }
            }
          }
        }
        SimpleFeature feature = featureBuilder.buildFeature(NodeRef.nodeFromPath(featureId));
        RevFeature revFeature = RevFeatureBuilder.build(feature);
        ggit.getRepository().stagingDatabase().put(revFeature);

        getResponse()
            .setEntity(
                new StringRepresentation(revFeature.getId().toString(), MediaType.TEXT_PLAIN));
      }

    } catch (Exception e) {
      throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL, e);
    } finally {
      if (input != null) Closeables.closeQuietly(input);
    }
  }