Example #1
0
 public static void main(String[] args) throws IOException {
   List<SystemProperty> properties = SystemPropertiesParser.parse();
   System.out.println(NORMAL_GSON.toJson(properties));
   Files.write(Paths.get("system_properties_min.json"), NORMAL_GSON.toJson(properties).getBytes());
   Files.write(Paths.get("system_properties.json"), PRETTY_GSON.toJson(properties).getBytes());
   createReadMe(properties);
 }
  @Test
  public void should_not_copy_given_file_from_source_directory_if_it_already_exist()
      throws Exception {
    write(source.toPath().resolve("pbButton.json"), "contents from source".getBytes());
    write(destination.toPath().resolve("pbButton.json"), "contents from destination".getBytes());

    visitor.visitFile(source.toPath().resolve("pbButton.json"), null);

    assertThat(readAllBytes(destination.toPath().resolve("pbButton.json")))
        .isEqualTo("contents from destination".getBytes());
  }
Example #3
0
  // Test borrowed from BytesAndLines
  public void testLines() throws IOException {
    final Charset US_ASCII = Charset.forName("US-ASCII");
    Path tmpfile = Files.createTempFile("blah", "txt");

    try {
      // zero lines
      assertTrue(Files.size(tmpfile) == 0, "File should be empty");
      try (Stream<String> s = Files.lines(tmpfile)) {
        checkLines(s, Collections.emptyList());
      }
      try (Stream<String> s = Files.lines(tmpfile, US_ASCII)) {
        checkLines(s, Collections.emptyList());
      }

      // one line
      List<String> oneLine = Arrays.asList("hi");
      Files.write(tmpfile, oneLine, US_ASCII);
      try (Stream<String> s = Files.lines(tmpfile)) {
        checkLines(s, oneLine);
      }
      try (Stream<String> s = Files.lines(tmpfile, US_ASCII)) {
        checkLines(s, oneLine);
      }

      // two lines using platform's line separator
      List<String> twoLines = Arrays.asList("hi", "there");
      Files.write(tmpfile, twoLines, US_ASCII);
      try (Stream<String> s = Files.lines(tmpfile)) {
        checkLines(s, twoLines);
      }
      try (Stream<String> s = Files.lines(tmpfile, US_ASCII)) {
        checkLines(s, twoLines);
      }

      // MalformedInputException
      byte[] bad = {(byte) 0xff, (byte) 0xff};
      Files.write(tmpfile, bad);
      try (Stream<String> s = Files.lines(tmpfile)) {
        checkMalformedInputException(s);
      }
      try (Stream<String> s = Files.lines(tmpfile, US_ASCII)) {
        checkMalformedInputException(s);
      }

      // NullPointerException
      checkNullPointerException(() -> Files.lines(null));
      checkNullPointerException(() -> Files.lines(null, US_ASCII));
      checkNullPointerException(() -> Files.lines(tmpfile, null));

    } finally {
      Files.delete(tmpfile);
    }
  }
Example #4
0
  @Test
  public void testFileSystemGet() throws Exception {
    final File barFile = new File(tmpDir, "bar.html");
    final String expectedContentA = "<html/>";
    final String expectedContentB = "<html><body/></html>";
    Files.write(barFile.toPath(), expectedContentA.getBytes(StandardCharsets.UTF_8));

    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
      final String lastModified;
      HttpUriRequest req = new HttpGet(newUri("/fs/bar.html"));
      try (CloseableHttpResponse res = hc.execute(req)) {
        lastModified = assert200Ok(res, "text/html", expectedContentA);
      }

      // Test if the 'If-Modified-Since' header works as expected.
      req = new HttpGet(newUri("/fs/bar.html"));
      req.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate());

      try (CloseableHttpResponse res = hc.execute(req)) {
        assert304NotModified(res, lastModified, "text/html");
      }

      // Test if the 'If-Modified-Since' header works as expected after the file is modified.
      req = new HttpGet(newUri("/fs/bar.html"));
      req.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate());

      // HTTP-date has no sub-second precision; wait until the current second changes.
      Thread.sleep(1000);

      Files.write(barFile.toPath(), expectedContentB.getBytes(StandardCharsets.UTF_8));

      try (CloseableHttpResponse res = hc.execute(req)) {
        final String newLastModified = assert200Ok(res, "text/html", expectedContentB);

        // Ensure that the 'Last-Modified' header did not change.
        assertThat(newLastModified, is(not(lastModified)));
      }

      // Test if the cache detects the file removal correctly.
      final boolean deleted = barFile.delete();
      assertThat(deleted, is(true));

      req = new HttpGet(newUri("/fs/bar.html"));
      req.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate());
      req.setHeader(HttpHeaders.CONNECTION, "close");

      try (CloseableHttpResponse res = hc.execute(req)) {
        assert404NotFound(res);
      }
    }
  }
Example #5
0
  private void buildJSImagesList() {
    String str = "var tinyMCEImageList = new Array(\n";
    Path dir = Paths.get(System.getProperty("user.home"), ".saas", "app", "ui", "img", "www");
    boolean isFirst = true;
    for (File f : dir.toFile().listFiles()) {
      if (f.isDirectory()) {
        continue;
      }

      String s = "[\"" + f.getName() + "\", \"img/www/" + f.getName() + "\"]";
      if (isFirst) {
        str += s;
        isFirst = false;
      } else {
        str += ",\n" + s;
      }
    }

    str += "\n);";

    Path f =
        Paths.get(System.getProperty("user.home"), ".saas", "app", "ui", "js", "image_list.js");
    try {
      Files.write(f, str.getBytes());
    } catch (IOException ex) {
      Logger.getGlobal().log(Level.WARNING, str, ex);
      JSMediator.alert(getSession(), ex.toString());
    }
  }
  /*
   * this tests ensure that MethodParameters produces by javac is packed
   * correctly. Usually this is not the case as new attributes are available
   * in the sdk jars, since MethodParameters happens to be an optional
   * attribute, thus this test.
   */
  static void testMethodParameters() throws Exception {
    List<String> scratch = new ArrayList<>();
    final String fname = "MP";
    String javaFileName = fname + Utils.JAVA_FILE_EXT;
    String javaClassName = fname + Utils.CLASS_FILE_EXT;
    scratch.add("class " + fname + " {");
    scratch.add("void foo2(int j, final int k){}");
    scratch.add("}");
    File cwd = new File(".");
    File javaFile = new File(cwd, javaFileName);
    Files.write(javaFile.toPath(), scratch, Charset.defaultCharset(), CREATE, TRUNCATE_EXISTING);

    Utils.compiler(javaFile.getName(), "-parameters");

    // jar the file up
    File testjarFile = new File(cwd, "test" + Utils.JAR_FILE_EXT);
    Utils.jar("cvf", testjarFile.getName(), javaClassName);

    // pack using --repack
    File outjarFile = new File(cwd, "out" + Utils.JAR_FILE_EXT);
    scratch.clear();
    scratch.add(Utils.getPack200Cmd());
    scratch.add("--repack");
    scratch.add("--unknown-attribute=error");
    scratch.add(outjarFile.getName());
    scratch.add(testjarFile.getName());
    Utils.runExec(scratch);

    Utils.doCompareVerify(testjarFile, outjarFile);
  }
Example #7
0
  private static void writeReport(Report report) {
    if (report == null) {
      return;
    }

    if (!SHOULD_WRITE_REPORT) {
      return;
    }

    report.timestamp = new Date().toString();
    report.javaVersion = System.getProperty("java.runtime.version");
    report.hardwareConfig = getHwConfigFromEnv();
    report.jvmArgs = getNonXenonJvmArgs();
    report.xenonArgs = getXenonTestArgs();
    report.id = getIdFromEnv();
    report.os = System.getProperty("os.name") + " " + System.getProperty("os.version");
    Path dest = getReportRootFolder();
    dest = dest.resolve(report.id);

    report.prepare();
    Logger logger = Logger.getAnonymousLogger();
    try {
      Files.createDirectories(dest);
      dest = dest.resolve(report.name + ".json").toAbsolutePath();
      String json = Utils.toJsonHtml(report);
      Files.write(dest, json.getBytes(Utils.CHARSET));

      logger.info(String.format("Report for test run %s written to %s", report.id, dest));
    } catch (IOException e) {
      logger.log(Level.WARNING, "Could not save test results to " + dest, e);
    }
  }
Example #8
0
  public <T> void exportToCsv(String fileName, Iterator<T> data) {
    try {
      Files.createDirectories(Paths.get(DIR));
      StringBuilder content = new StringBuilder();

      List<Method> getters = null;
      while (data.hasNext()) {
        T t = data.next();
        if (getters == null) {
          getters = ReflectionUtil.getAllGetters(t.getClass());
          getters.sort((a, b) -> a.getName().length() - b.getName().length());
        }
        for (Method getter : getters) {
          try {
            String value = String.valueOf(getter.invoke(t));
            content.append(value).append(',');
          } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
          }
        }
        content.append('\n');
      }

      Files.write(
          Paths.get(DIR + fileName),
          content.toString().getBytes("UTF-8"),
          CREATE,
          WRITE,
          StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #9
0
  @Test
  public void testCreateRelativeSymlinkToFilesInRoot() throws IOException {
    ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmp.getRoot());
    tmp.newFile("biz.txt");

    Path pathToDesiredLinkUnderProjectRoot = Paths.get("gamma.txt");
    Path pathToExistingFileUnderProjectRoot = Paths.get("biz.txt");
    Path relativePath =
        MorePaths.createRelativeSymlink(
            pathToDesiredLinkUnderProjectRoot,
            pathToExistingFileUnderProjectRoot,
            projectFilesystem);
    assertEquals("biz.txt", relativePath.toString());

    Path absolutePathToDesiredLinkUnderProjectRoot =
        projectFilesystem.resolve(pathToDesiredLinkUnderProjectRoot);
    assertTrue(Files.isSymbolicLink(absolutePathToDesiredLinkUnderProjectRoot));
    Path targetOfSymbolicLink = Files.readSymbolicLink(absolutePathToDesiredLinkUnderProjectRoot);
    assertEquals(relativePath, targetOfSymbolicLink);

    Path absolutePathToExistingFileUnderProjectRoot =
        projectFilesystem.resolve(pathToExistingFileUnderProjectRoot);
    Files.write(absolutePathToExistingFileUnderProjectRoot, "Hello, World!".getBytes());
    String dataReadFromSymlink =
        new String(Files.readAllBytes(absolutePathToDesiredLinkUnderProjectRoot));
    assertEquals("Hello, World!", dataReadFromSymlink);
  }
  void ReceiveFileChunksFromServer() throws Exception, ClassNotFoundException {
    try {
      if (flagFilename) {
        filename = (String) in.readObject();
        totalChunks = Integer.parseInt((String) in.readObject());
        flagFilename = false;
      }

      if (availableChunks == null) availableChunks = new File[totalChunks];

      if (requiredChunks == null) requiredChunks = new File[totalChunks];

      int partNumber = Integer.parseInt((String) in.readObject());

      File partFile = new File("chunks/" + filename + "." + partNumber);
      byte[] msg = (byte[]) in.readObject();
      Files.write(partFile.toPath(), msg);
      availableChunks[partNumber] = partFile;
      System.out.println("Received chunk " + partNumber);
    } catch (ClassNotFoundException e) {
      flag = true;
    } catch (Exception e) {
      flag = true;
    }
  }
  public static void main(String[] args) {

    if (args.length < 1 || args.length > 2) {
      System.out.println("Usage: PosTagger <file_in> [<file_out]");
      System.exit(0);
    }

    try {

      CSVReader reader = new CSVReader(new FileReader(args[0]), ';');

      //            List<String> lstSemanticSkeletons =
      // BisonAdapter.getStrSemanticSkeletons(Files.lines(Paths.get(args[0])));
      List<String> lstSemanticSkeletons =
          BisonAdapter.getStrSemanticSkeletons(reader.readAll().stream());
      if (args.length == 2) {
        Files.write(Paths.get(args[1]), lstSemanticSkeletons);
      } else {
        lstSemanticSkeletons.forEach(System.out::println);
      }

    } catch (IOException e) {
      System.err.println("Problem opening file: " + args[0]);
    }
  }
Example #12
0
  private static void createReadMe(List<SystemProperty> properties) throws IOException {
    HtmlCanvas html = new HtmlCanvas();
    html.table();

    html.tbody()
        .tr()
        .td()
        .content("Key")
        .td()
        .content("Description")
        .td()
        .content("Uses")
        ._tr()
        ._tbody();

    String githubUrl = "https://github.com/android/%s/blob/%s/%s";
    String branch = "lollipop-release";

    for (SystemProperty property : properties) {
      html.tr();
      html.td().content(property.key);
      html.td().content(property.desc);
      html.td();
      for (SystemProperty.GithubInfo o : property.github) {
        String url = String.format(githubUrl, o.repo, branch, o.path);
        html.a(href(url)).content(o.getClassName());
        html.br();
      }
      html._td();
      html._tr();
    }

    Files.write(Paths.get("README.md"), html.toHtml().getBytes());
  }
Example #13
0
  /**
   * Save state.
   *
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public default void SaveState() throws IOException {

    final Gson newGsonWriter = new Gson();
    final String stringFileinJSON = newGsonWriter.toJson(this);
    final String path = GetFolder() + "\\" + GetName() + "_" + GetID() + ".txt";
    Files.write(Paths.get(path), stringFileinJSON.getBytes());
  }
 public void setDirectionOut(int i) {
   try {
     Files.write(gpioDirection[i], OUT);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
 public void setValueLow(int i) {
   try {
     Files.write(gpioValue[i], VALUE_LOW);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
 public void setDebugCurrentPinmuxMode2(int i) {
   try {
     Files.write(gpioDebugCurrentPinMux[i], MODE_2);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
  @Test
  public void processesExternModules() throws IOException {
    Path extern = path("root/externs/xml.js");
    Path module = path("root/source/foo.js");

    createDirectories(extern.getParent());
    write(
        extern,
        lines(
                "/** @const */",
                "var xml = {};",
                "/** @param {string} str",
                " *  @return {!Object}",
                " */",
                "xml.parse = function(str) {};",
                "module.exports = xml;")
            .getBytes(StandardCharsets.UTF_8));

    CompilerUtil compiler = createCompiler(ImmutableSet.of(extern), ImmutableSet.of(module));
    compiler.compile(module, "var xml = require('xml');", "xml.parse('abc');");

    assertThat(compiler.toSource())
        .contains(
            lines(
                "var xml = $jscomp.scope.xml_module;",
                "var module$root$source$foo = {};",
                "$jscomp.scope.xml_module.parse(\"abc\");"));
  }
Example #18
0
 private synchronized void print(
     String url,
     String startTime,
     String endTime,
     int fileSize,
     String cacheBool,
     int statusCode) {
   String entry =
       url
           + " "
           + startTime
           + " "
           + endTime
           + " "
           + fileSize
           + " "
           + cacheBool
           + " "
           + statusCode
           + System.lineSeparator();
   try {
     Files.write(Paths.get("log.txt"), entry.getBytes(), StandardOpenOption.APPEND);
   } catch (IOException ex) {
     Logger.getLogger(doComms.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
Example #19
0
 private void doRequest(Object info) {
   try {
     Response response = this.callPDP(RequestParser.parseRequest(info));
     Path resultFile;
     if (this.output != null) {
       resultFile =
           Paths.get(
               this.output.toString(), "Response." + String.format("%03d", this.num) + ".json");
     } else {
       resultFile =
           Paths.get(
               this.directory, "results", "Response." + String.format("%03d", this.num) + ".json");
     }
     //
     // Write the response to the result file
     //
     logger.info("Response is: " + response.toString());
     if (resultFile != null) {
       Files.write(resultFile, response.toString().getBytes());
     }
   } catch (IllegalArgumentException
       | IllegalAccessException
       | DataTypeException
       | IOException e) {
     logger.error(e);
     e.printStackTrace();
   }
 }
Example #20
0
File: U.java Project: abinns/bdmds
 /**
  * Given a file and contents, and Charset, attempts to write the entire string provided to the
  * file using the specified encoding. If the file does not exist, it creates it. If the file
  * exists, it overwrites the contents, truncating prior to any writing.
  *
  * @param path the path of the file to write to
  * @param contents the data to be written to the file
  * @param encoding the string encoding method to use
  */
 public static void writeToFile(String path, String contents, Charset encoding) {
   try {
     Files.write(Paths.get(path), contents.getBytes(encoding));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  /** Generate evolutions. */
  @Override
  public void create() {
    if (!environment.isProd()) {
      config
          .serverConfigs()
          .forEach(
              (key, serverConfig) -> {
                String evolutionScript = generateEvolutionScript(servers.get(key));
                if (evolutionScript != null) {
                  File evolutions = environment.getFile("conf/evolutions/" + key + "/1.sql");
                  try {
                    String content = "";
                    if (evolutions.exists()) {
                      content = new String(Files.readAllBytes(evolutions.toPath()), "utf-8");
                    }

                    if (content.isEmpty() || content.startsWith("# --- Created by Ebean DDL")) {
                      environment.getFile("conf/evolutions/" + key).mkdirs();
                      if (!content.equals(evolutionScript)) {
                        Files.write(evolutions.toPath(), evolutionScript.getBytes("utf-8"));
                      }
                    }
                  } catch (IOException e) {
                    throw new RuntimeException(e);
                  }
                }
              });
    }
  }
 public void execute() throws MojoExecutionException {
   Log log = getLog();
   String root = project.getBasedir().getPath();
   String[] matchingFiles = scan(new File(root));
   for (String matchingFile : matchingFiles) {
     log.info("compiling '" + matchingFile + "'...");
     Path sourceFile = Paths.get(matchingFile);
     try {
       // Reading template file
       byte[] fileBytes = Files.readAllBytes(sourceFile);
       String template =
           Charset.forName(sourceEncoding).decode(ByteBuffer.wrap(fileBytes)).toString();
       // Creating template name
       int templateNameExtensionIndex = sourceFile.getFileName().toString().lastIndexOf('.');
       String templateName =
           templateNameExtensionIndex > 0
               ? sourceFile.getFileName().toString().substring(0, templateNameExtensionIndex)
               : sourceFile.getFileName().toString();
       // Compiling template
       String result = HoganTemplateCompileHelper.compileHoganTemplate(template, templateName);
       // Writing output file
       ByteBuffer bb = Charset.forName(outputEncoding).encode(result);
       fileBytes = new byte[bb.remaining()];
       bb.get(fileBytes);
       Path outputFilePath = sourceFile.getParent().resolve(templateName + ".js");
       log.info("writing '" + outputFilePath.toString() + "'");
       Files.write(outputFilePath, fileBytes, StandardOpenOption.CREATE);
     } catch (IOException e) {
       throw new MojoExecutionException("Error while compiling Hogan Template", e);
     }
   }
 }
Example #23
0
 /**
  * save current state into file
  *
  * @param file_name filename
  * @throws IOException
  */
 public void saveToFile(String file_name) throws IOException {
   assert !"".equals(file_name);
   log.info("Serialize VM to " + file_name);
   Path path = Paths.get(file_name);
   byte[] serialized_vm = this.serialize();
   Files.write(path, serialized_vm);
 }
 private void assertFileChangesReflected(String context) throws Exception {
   if (context.length() > 0 && !context.endsWith("/")) {
     context = context + "/";
   }
   Path tmpDir = Paths.get(System.getProperty("user.dir"), "src", "main", "webapp", "tmp");
   Files.createDirectories(tmpDir);
   Path newFile = tmpDir.resolve("new-file.txt");
   try {
     Files.write(newFile, "This is new-file.txt.".getBytes());
     assertContains(context + "tmp/new-file.txt", "This is new-file.txt.");
     Files.write(newFile, "This is updated new-file.txt.".getBytes());
     assertContains(context + "tmp/new-file.txt", "This is updated new-file.txt.");
   } finally {
     Files.deleteIfExists(newFile);
   }
 }
Example #25
0
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    checkCreate(qc);

    final Path path = toPath(0, qc);
    final B64 archive = toB64(exprs[1], qc, false);
    final TokenSet hs = entries(2, qc);

    try (ArchiveIn in = ArchiveIn.get(archive.input(info), info)) {
      while (in.more()) {
        final ZipEntry ze = in.entry();
        final String name = ze.getName();
        if (hs == null || hs.delete(token(name)) != 0) {
          final Path file = path.resolve(name);
          if (ze.isDirectory()) {
            Files.createDirectories(file);
          } else {
            Files.createDirectories(file.getParent());
            Files.write(file, in.read());
          }
        }
      }
    } catch (final IOException ex) {
      throw ARCH_FAIL_X.get(info, ex);
    }
    return null;
  }
Example #26
0
  public static void main(String[] args) {
    // setup
    final Path in = getPath("in.txt");
    final Path out = getPath("out.txt");

    // action
    try {
      final byte[] bytes = Files.readAllBytes(in);
      System.out.println("-->");
      System.out.println(new String(bytes));

      final byte[] reversed = CollectionUtils.reverse(bytes);
      Files.write(out, reversed);
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }

    // check
    try {
      final byte[] result = Files.readAllBytes(out);
      System.out.println("<--");
      System.out.println(new String(result));
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }
  public void event(WatchEvent.Kind kind, Path path) {
    // System.out.println("Log event");

    File file = new File(path.toString());
    String ip = "0.0.0.0", owner = "unknown";
    try {
      ip = Inet4Address.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
    try {
      FileOwnerAttributeView ownerAttributeView =
          Files.getFileAttributeView(path, FileOwnerAttributeView.class);
      owner = ownerAttributeView.getOwner().getName();
    } catch (IOException e) {
      e.printStackTrace();
    }

    String entry =
        String.format(
            "[%s] \"%s\" copied on \"%s\" by \"%s\"\n",
            new SimpleDateFormat("dd/MMM/YYYY HH:mm:ss").format(new Date()),
            path.toString(),
            ip,
            owner);

    try {
      Files.write(Paths.get(logFile), entry.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  @BeforeClass(groups = "AllEnv")
  public void makeTestDirectories() throws IOException {
    if (Files.exists(Cテスト用ルートディレクトリ)) DirectoryDeleter.delete(Cテスト用ルートディレクトリ);

    Files.createDirectories(C読み込みテスト用ディレクトリ);
    Files.createDirectories(C書き込みテスト用ディレクトリ);
    Files.createDirectories(C読み込める設定ファイルかと思ったらディレクトリだった);
    Files.createDirectories(C書き込める設定ファイルかと思ったらディレクトリだった);

    Files.createFile(C存在するけど形式がおかしい設定ファイル);
    Files.write(
        C存在して読み込み可能な設定ファイル,
        Arrays.asList(
            "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>",
            "<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">",
            "<properties>",
            "<comment>Properties File for Boardgame Server</comment>",
            "<entry key=\"WINDOW_H\">252</entry>",
            "<entry key=\"WINDOW_Y\">2</entry>",
            "<entry key=\"WINDOW_X\">1</entry>",
            "<entry key=\"WINDOW_W\">251</entry>",
            "</properties>"),
        Charset.forName("UTF-8"));
    Files.createFile(C設定ファイルが書き込み不能だった);
    C設定ファイルが書き込み不能だった.toFile().setWritable(false);
  }
  @Before
  public void setUp() throws Exception {
    assumeThat(TD_API_KEY, not(isEmptyOrNullString()));
    projectDir = folder.getRoot().toPath().toAbsolutePath().normalize();
    config = folder.newFile().toPath();
    Files.write(config, asList("secrets.td.apikey = " + TD_API_KEY));
    outfile = projectDir.resolve("outfile");

    client = TDClient.newBuilder(false).setApiKey(TD_API_KEY).build();
    database = "tmp_" + UUID.randomUUID().toString().replace('-', '_');
    client.createDatabase(database);

    table = "test";
    String insertJobId =
        client.submit(
            TDJobRequest.newPrestoQuery(database, "create table " + table + " as select 1"));

    TestUtils.expect(Duration.ofMinutes(5), jobSuccess(client, insertJobId));

    String selectCountJobId =
        client.submit(TDJobRequest.newPrestoQuery(database, "select count(*) from " + table));
    TestUtils.expect(Duration.ofMinutes(5), jobSuccess(client, selectCountJobId));

    List<ArrayNode> result = downloadResult(selectCountJobId);
    assertThat(result.get(0).get(0).asInt(), is(1));
  }
Example #30
0
  public static void main(String[] args) throws Exception {
    if (args.length < 1) {
      System.out.println("USAGE : java -jar GoEuroTest.jar <CITY_NAME>");
      System.exit(1);
    }
    String urlStr = "http://api.goeuro.com/api/v2/position/suggest/en/";
    urlStr = urlStr + URLEncoder.encode(args[0], "UTF-8");
    URL url = new URL(urlStr);

    String lines = "";
    String fileHeader = "_id,name,type,latitude,longitude\r\n"; // out csv file header
    lines += fileHeader;
    try {
      InputStream inputStream = url.openStream();
      JsonReader jsonReader = Json.createReader(inputStream);
      JsonArray results = jsonReader.readArray();
      if (results.isEmpty()) {
        System.out.println("INFO: City '" + args[0] + "' returned 0 results.");
        return;
      }
      for (JsonObject result : results.getValuesAs(JsonObject.class)) {
        lines += result.getJsonNumber("_id") + ",";
        lines += result.getString("name") + ",";
        lines += result.getString("type") + ",";
        lines += result.getJsonObject("geo_position").getJsonNumber("latitude") + ",";
        lines += result.getJsonObject("geo_position").getJsonNumber("longitude") + "\r\n";
      }
      Files.write(Paths.get("./out.csv"), lines.getBytes());
      System.out.println("INFO: Wrote results to 'out.csv'.");
    } catch (Throwable e) {
      System.out.println("ERROR: Could not write CSV File 'out.csv'. Error: " + e);
    }
  }