/**
   * Push all new objects from the specified {@link Ref} to the remote.
   *
   * @param ref the local ref that points to new commit data
   * @param refspec the remote branch to push to
   */
  @Override
  public void pushNewData(Ref ref, String refspec, ProgressListener progress)
      throws SynchronizationException {
    Optional<Ref> remoteRef = HttpUtils.getRemoteRef(repositoryURL, refspec);
    checkPush(ref, remoteRef);
    beginPush();

    progress.setDescription("Uploading objects to " + refspec);
    progress.setProgress(0);

    CommitTraverser traverser = getPushTraverser(remoteRef);

    traverser.traverse(ref.getObjectId());

    List<ObjectId> toSend = new LinkedList<ObjectId>(traverser.commits);
    Collections.reverse(toSend);
    Set<ObjectId> have = new HashSet<ObjectId>(traverser.have);

    Deduplicator deduplicator = deduplicationService.createDeduplicator();
    try {
      sendPackedObjects(toSend, have, deduplicator, progress);
    } finally {
      deduplicator.release();
    }

    ObjectId originalRemoteRefValue = ObjectId.NULL;
    if (remoteRef.isPresent()) {
      originalRemoteRefValue = remoteRef.get().getObjectId();
    }

    String nameToSet =
        remoteRef.isPresent() ? remoteRef.get().getName() : Ref.HEADS_PREFIX + refspec;

    endPush(nameToSet, ref.getObjectId(), originalRemoteRefValue.toString());
  }
Example #2
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));
    }
  }
 private JsonObject createFetchMessage(List<ObjectId> want, Set<ObjectId> have) {
   JsonObject message = new JsonObject();
   JsonArray wantArray = new JsonArray();
   for (ObjectId id : want) {
     wantArray.add(new JsonPrimitive(id.toString()));
   }
   JsonArray haveArray = new JsonArray();
   for (ObjectId id : have) {
     haveArray.add(new JsonPrimitive(id.toString()));
   }
   message.add("want", wantArray);
   message.add("have", haveArray);
   return message;
 }
Example #4
0
    public void print(RevCommit commit) throws IOException {

      StringBuilder sb = new StringBuilder();
      sb.append("commit ").append(commit.getId().toString()).append('\n');
      sb.append("tree ").append(commit.getTreeId().toString()).append('\n');
      sb.append("parent");
      for (ObjectId parentId : commit.getParentIds()) {
        sb.append(' ').append(parentId.toString());
      }
      sb.append('\n');
      sb.append("author ").append(format(commit.getAuthor())).append('\n');
      sb.append("committer ").append(format(commit.getCommitter())).append('\n');

      if (commit.getMessage() != null) {
        sb.append("message\n");
        sb.append("\t" + commit.getMessage().replace("\n", "\n\t"));
        sb.append('\n');
      }
      if (showChanges) {
        Iterator<DiffEntry> diff =
            geogig
                .command(DiffOp.class)
                .setOldVersion(commit.parentN(0).or(ObjectId.NULL))
                .setNewVersion(commit.getId())
                .call();
        DiffEntry diffEntry;
        sb.append("changes\n");
        while (diff.hasNext()) {
          diffEntry = diff.next();
          String path = diffEntry.newPath() != null ? diffEntry.newPath() : diffEntry.oldPath();
          sb.append('\t')
              .append(path)
              .append(' ')
              .append(diffEntry.oldObjectId().toString())
              .append(' ')
              .append(diffEntry.newObjectId().toString())
              .append('\n');
        }
      }
      console.println(sb.toString());
    }
  /**
   * Executes the command.
   *
   * @return an {@code Optional} that contains the Node if it was found, or {@link
   *     Optional#absent()} if it wasn't
   */
  @Override
  protected Optional<NodeRef> _call() {
    checkNotNull(childPath, "childPath");
    final RevTree tree;
    if (parent == null) {
      ObjectId rootTreeId = command(ResolveTreeish.class).setTreeish(Ref.HEAD).call().get();
      if (rootTreeId.isNull()) {
        return Optional.absent();
      }
      tree = command(RevObjectParse.class).setObjectId(rootTreeId).call(RevTree.class).get();
    } else {
      tree = parent.get();
    }
    final String path = childPath;
    final String parentPath = this.parentPath == null ? "" : this.parentPath;
    final ObjectDatabase target = indexDb ? stagingDatabase() : objectDatabase();

    DepthSearch depthSearch = new DepthSearch(target);
    Optional<NodeRef> childRef = depthSearch.find(tree, parentPath, path);
    return childRef;
  }
  private Optional<NodeRef> parseID(ObjectId commitId, String path, GeoGIG geogig) {
    Optional<RevObject> object = geogig.command(RevObjectParse.class).setObjectId(commitId).call();
    RevCommit commit = null;
    if (object.isPresent() && object.get() instanceof RevCommit) {
      commit = (RevCommit) object.get();
    } else {
      throw new CommandSpecException(
          "Couldn't resolve id: " + commitId.toString() + " to a commit");
    }

    object = geogig.command(RevObjectParse.class).setObjectId(commit.getTreeId()).call();

    if (object.isPresent()) {
      RevTree tree = (RevTree) object.get();
      return geogig.command(FindTreeChild.class).setParent(tree).setChildPath(path).call();
    } else {
      throw new CommandSpecException("Couldn't resolve commit's treeId");
    }
  }
    @Override
    public void write(Writer w) throws IOException {
      Form options = getRequest().getResourceRef().getQueryAsForm();

      ObjectId oid = ObjectId.valueOf(options.getFirstValue("oid", ObjectId.NULL.toString()));
      Request request = getRequest();
      Optional<GeoGIG> ggit = getGeogig(request);
      Preconditions.checkState(ggit.isPresent());

      GeoGIG geogig = ggit.get();
      Repository repository = geogig.getRepository();
      boolean blobExists = repository.blobExists(oid);

      if (blobExists) {
        w.write("1");
      } else {
        w.write("0");
      }
      w.flush();
    }
 @Test
 public void testReadWriteConflicts() throws Exception {
   Conflict conflict =
       new Conflict(
           idP1,
           ObjectId.forString("ancestor"),
           ObjectId.forString("ours"),
           ObjectId.forString("theirs"));
   Conflict conflict2 =
       new Conflict(
           idP2,
           ObjectId.forString("ancestor2"),
           ObjectId.forString("ours2"),
           ObjectId.forString("theirs2"));
   ArrayList<Conflict> conflicts = Lists.newArrayList(conflict, conflict2);
   geogig.command(ConflictsWriteOp.class).setConflicts(conflicts).call();
   List<Conflict> returnedConflicts = geogig.command(ConflictsReadOp.class).call();
   assertEquals(conflicts, returnedConflicts);
 }
  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);
    }
  }