Example #1
0
  private SimpleFeatureType getFeatureType(String path, GeogigCLI cli) {

    checkParameter(path != null, "No path specified.");

    String refspec;
    if (path.contains(":")) {
      refspec = path;
    } else {
      refspec = "WORK_HEAD:" + path;
    }

    checkParameter(!refspec.endsWith(":"), "No path specified.");

    final GeoGIG geogig = cli.getGeogig();

    Optional<ObjectId> rootTreeId =
        geogig.command(ResolveTreeish.class).setTreeish(refspec.split(":")[0]).call();

    checkParameter(
        rootTreeId.isPresent(), "Couldn't resolve '" + refspec + "' to a treeish object");

    RevTree rootTree = geogig.getRepository().getTree(rootTreeId.get());
    Optional<NodeRef> featureTypeTree =
        geogig
            .command(FindTreeChild.class)
            .setChildPath(refspec.split(":")[1])
            .setParent(rootTree)
            .call();

    checkParameter(
        featureTypeTree.isPresent(),
        "pathspec '" + refspec.split(":")[1] + "' did not match any valid path");

    Optional<RevObject> revObject =
        cli.getGeogig()
            .command(RevObjectParse.class)
            .setObjectId(featureTypeTree.get().getMetadataId())
            .call();
    if (revObject.isPresent() && revObject.get() instanceof RevFeatureType) {
      RevFeatureType revFeatureType = (RevFeatureType) revObject.get();
      if (revFeatureType.type() instanceof SimpleFeatureType) {
        return (SimpleFeatureType) revFeatureType.type();
      } else {
        throw new InvalidParameterException("Cannot find feature type for the specified path");
      }
    } else {
      throw new InvalidParameterException("Cannot find feature type for the specified path");
    }
  }
Example #2
0
 @Test
 public void testImportException() throws Exception {
   when(cli.getConsole()).thenThrow(new MockitoException("Exception"));
   PGImport importCommand = new PGImport();
   importCommand.all = true;
   importCommand.support.dataStoreFactory = TestHelper.createTestFactory();
   exception.expect(MockitoException.class);
   importCommand.run(cli);
 }
Example #3
0
  private void setUpGeogig(GeogigCLI cli) throws Exception {
    final File userhome = tempFolder.newFolder("mockUserHomeDir");
    final File workingDir = tempFolder.newFolder("mockWorkingDir");
    tempFolder.newFolder("mockWorkingDir", ".geogig");

    final Platform platform = mock(Platform.class);
    when(platform.pwd()).thenReturn(workingDir);
    when(platform.getUserHome()).thenReturn(userhome);

    cli.setPlatform(platform);
  }
Example #4
0
  @Override
  public void runInternal(GeogigCLI cli) throws IOException {
    checkParameter(patchFiles.size() < 2, "Only one single patch file accepted");
    checkParameter(!patchFiles.isEmpty(), "No patch file specified");

    Console console = cli.getConsole();

    File patchFile = new File(patchFiles.get(0));
    checkParameter(patchFile.exists(), "Patch file cannot be found");
    FileInputStream stream;
    try {
      stream = new FileInputStream(patchFile);
    } catch (FileNotFoundException e1) {
      throw new IllegalStateException("Can't open patch file " + patchFile);
    }
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
      Closeables.closeQuietly(reader);
      Closeables.closeQuietly(stream);
      throw new IllegalStateException("Error reading patch file " + patchFile, e);
    }
    Patch patch = PatchSerializer.read(reader);
    Closeables.closeQuietly(reader);
    Closeables.closeQuietly(stream);

    VerifyPatchResults verify =
        cli.getGeogig().command(VerifyPatchOp.class).setPatch(patch).setReverse(reverse).call();
    Patch toReject = verify.getToReject();
    Patch toApply = verify.getToApply();
    if (toReject.isEmpty()) {
      console.println("Patch can be applied.");
    } else {
      console.println("Error: Patch cannot be applied\n");
      console.println("Applicable entries:\n");
      console.println(toApply.toString());
      console.println("\nConflicting entries:\n");
      console.println(toReject.toString());
    }
  }
Example #5
0
  /** Executes the export command using the provided options. */
  @Override
  protected final void runInternal(GeogigCLI cli) throws IOException {
    if (args.isEmpty()) {
      printUsage(cli);
      throw new CommandFailedException();
    }

    String path = args.get(0);
    String tableName = args.get(1);

    checkParameter(tableName != null && !tableName.isEmpty(), "No table name specified");

    DataStore dataStore = getDataStore();

    ObjectId featureTypeId = null;
    if (!Arrays.asList(dataStore.getTypeNames()).contains(tableName)) {
      SimpleFeatureType outputFeatureType;
      if (sFeatureTypeId != null) {
        // Check the feature type id string is a correct id
        Optional<ObjectId> id =
            cli.getGeogig().command(RevParse.class).setRefSpec(sFeatureTypeId).call();
        checkParameter(id.isPresent(), "Invalid feature type reference", sFeatureTypeId);
        TYPE type = cli.getGeogig().command(ResolveObjectType.class).setObjectId(id.get()).call();
        checkParameter(
            type.equals(TYPE.FEATURETYPE),
            "Provided reference does not resolve to a feature type: ",
            sFeatureTypeId);
        outputFeatureType =
            (SimpleFeatureType)
                cli.getGeogig()
                    .command(RevObjectParse.class)
                    .setObjectId(id.get())
                    .call(RevFeatureType.class)
                    .get()
                    .type();
        featureTypeId = id.get();
      } else {
        try {
          SimpleFeatureType sft = getFeatureType(path, cli);
          outputFeatureType =
              new SimpleFeatureTypeImpl(
                  new NameImpl(tableName),
                  sft.getAttributeDescriptors(),
                  sft.getGeometryDescriptor(),
                  sft.isAbstract(),
                  sft.getRestrictions(),
                  sft.getSuper(),
                  sft.getDescription());
        } catch (GeoToolsOpException e) {
          throw new CommandFailedException("No features to export.", e);
        }
      }
      try {
        dataStore.createSchema(outputFeatureType);
      } catch (IOException e) {
        throw new CommandFailedException("Cannot create new table in database", e);
      }
    } else {
      if (!overwrite) {
        throw new CommandFailedException("The selected table already exists. Use -o to overwrite");
      }
    }

    SimpleFeatureSource featureSource = dataStore.getFeatureSource(tableName);
    if (!(featureSource instanceof SimpleFeatureStore)) {
      throw new CommandFailedException("Can't write to the selected table");
    }
    SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
    if (overwrite) {
      try {
        featureStore.removeFeatures(Filter.INCLUDE);
      } catch (IOException e) {
        throw new CommandFailedException("Error truncating table: " + e.getMessage(), e);
      }
    }
    ExportOp op =
        cli.getGeogig()
            .command(ExportOp.class)
            .setFeatureStore(featureStore)
            .setPath(path)
            .setFilterFeatureTypeId(featureTypeId)
            .setAlter(alter);
    if (defaultType) {
      op.exportDefaultFeatureType();
    }
    try {
      op.setProgressListener(cli.getProgressListener()).call();
    } catch (IllegalArgumentException iae) {
      throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
    } catch (GeoToolsOpException e) {
      switch (e.statusCode) {
        case MIXED_FEATURE_TYPES:
          throw new CommandFailedException(
              "The selected tree contains mixed feature types. Use --defaulttype or --featuretype <feature_type_ref> to export.",
              e);
        default:
          throw new CommandFailedException("Could not export. Error:" + e.statusCode.name(), e);
      }
    }

    cli.getConsole().println(path + " exported successfully to " + tableName);
  }
Example #6
0
  @Override
  public void runInternal(GeogigCLI cli) throws IOException {
    checkParameter(patchFiles.size() < 2, "Only one single patch file accepted");
    checkParameter(!patchFiles.isEmpty(), "No patch file specified");

    ConsoleReader console = cli.getConsole();
    GeoGIG geogig = cli.getGeogig();

    File patchFile = new File(patchFiles.get(0));
    checkParameter(patchFile.exists(), "Patch file cannot be found");
    FileInputStream stream;
    try {
      stream = new FileInputStream(patchFile);
    } catch (FileNotFoundException e1) {
      throw new CommandFailedException("Can't open patch file " + patchFile, e1);
    }
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
      Closeables.closeQuietly(reader);
      Closeables.closeQuietly(stream);
      throw new CommandFailedException("Error reading patch file " + patchFile, e);
    }
    Patch patch = PatchSerializer.read(reader);
    Closeables.closeQuietly(reader);
    Closeables.closeQuietly(stream);

    if (reverse) {
      patch = patch.reversed();
    }

    if (summary) {
      console.println(patch.toString());
    } else if (check) {
      VerifyPatchResults verify =
          cli.getGeogig().command(VerifyPatchOp.class).setPatch(patch).call();
      Patch toReject = verify.getToReject();
      Patch toApply = verify.getToApply();
      if (toReject.isEmpty()) {
        console.println("Patch can be applied.");
      } else {
        console.println("Error: Patch cannot be applied\n");
        console.println("Applicable entries:\n");
        console.println(toApply.toString());
        console.println("\nConflicting entries:\n");
        console.println(toReject.toString());
      }
    } else {
      try {
        Patch rejected =
            geogig.command(ApplyPatchOp.class).setPatch(patch).setApplyPartial(reject).call();
        if (reject) {
          if (rejected.isEmpty()) {
            console.println("Patch applied succesfully");
          } else {
            int accepted = patch.count() - rejected.count();
            StringBuilder sb = new StringBuilder();
            File file = new File(patchFile.getAbsolutePath() + ".rej");
            sb.append("Patch applied only partially.\n");
            sb.append(Integer.toString(accepted) + " changes were applied.\n");
            sb.append(Integer.toString(rejected.count()) + " changes were rejected.\n");
            BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8);
            PatchSerializer.write(writer, patch);
            writer.flush();
            writer.close();
            sb.append(
                "Patch file with rejected changes created at " + file.getAbsolutePath() + "\n");
            throw new CommandFailedException(sb.toString());
          }
        } else {
          console.println("Patch applied succesfully");
        }
      } catch (CannotApplyPatchException e) {
        throw new CommandFailedException(e);
      }
    }
  }
Example #7
0
 @After
 public void tearDown() throws Exception {
   cli.close();
 }
Example #8
0
  /** Executes the revlist command using the provided options. */
  @Override
  public void runInternal(GeogigCLI cli) throws IOException {
    checkParameter(!args.commits.isEmpty(), "No starting commit provided");

    geogig = cli.getGeogig();

    LogOp op =
        geogig.command(LogOp.class).setTopoOrder(args.topo).setFirstParentOnly(args.firstParent);

    for (String commit : args.commits) {
      if (commit.contains("..")) {
        checkParameter(
            args.commits.size() == 1, "Only one value accepted when using <since>..<until> syntax");
        List<String> sinceUntil = ImmutableList.copyOf((Splitter.on("..").split(commit)));
        checkParameter(
            sinceUntil.size() == 2 || sinceUntil.size() == 1,
            "Invalid refSpec format, expected [<commit> ...]|[<since>..<until>]: %s",
            commit);
        String sinceRefSpec;
        String untilRefSpec;
        if (sinceUntil.size() == 1) {
          // just until was given
          sinceRefSpec = null;
          untilRefSpec = sinceUntil.get(0);
        } else {
          sinceRefSpec = sinceUntil.get(0);
          untilRefSpec = sinceUntil.get(1);
        }
        if (sinceRefSpec != null) {
          Optional<ObjectId> since;
          since = geogig.command(RevParse.class).setRefSpec(sinceRefSpec).call();
          checkParameter(since.isPresent(), "Object not found '%s'", sinceRefSpec);
          op.setSince(since.get());
        }
        if (untilRefSpec != null) {
          Optional<ObjectId> until;
          until = geogig.command(RevParse.class).setRefSpec(untilRefSpec).call();
          checkParameter(until.isPresent(), "Object not found '%s'", sinceRefSpec);
          op.setUntil(until.get());
        }
      } else {
        Optional<ObjectId> commitId = geogig.command(RevParse.class).setRefSpec(commit).call();
        checkParameter(commitId.isPresent(), "Object not found '%s'", commit);
        checkParameter(
            geogig.getRepository().commitExists(commitId.get()),
            "%s does not resolve to a commit",
            commit);
        op.addCommit(commitId.get());
      }
    }
    if (args.author != null && !args.author.isEmpty()) {
      op.setAuthor(args.author);
    }
    if (args.committer != null && !args.committer.isEmpty()) {
      op.setCommiter(args.committer);
    }
    if (args.skip != null) {
      op.setSkip(args.skip.intValue());
    }
    if (args.limit != null) {
      op.setLimit(args.limit.intValue());
    }
    if (args.since != null || args.until != null) {
      Date since = new Date(0);
      Date until = new Date();
      if (args.since != null) {
        since = new Date(geogig.command(ParseTimestamp.class).setString(args.since).call());
      }
      if (args.until != null) {
        until = new Date(geogig.command(ParseTimestamp.class).setString(args.until).call());
      }
      op.setTimeRange(new Range<Date>(Date.class, since, until));
    }
    if (!args.pathNames.isEmpty()) {
      for (String s : args.pathNames) {
        op.addPath(s);
      }
    }
    Iterator<RevCommit> log = op.call();
    console = cli.getConsole();

    RawPrinter printer = new RawPrinter(args.changed);
    while (log.hasNext()) {
      printer.print(log.next());
      console.flush();
    }
  }