Exemplo n.º 1
0
  private ByteSequencesReader sort() throws IOException {
    String prefix = getClass().getSimpleName();
    Path directory = OfflineSorter.getDefaultTempDir();
    tempInput = Files.createTempFile(directory, prefix, ".input");
    tempSorted = Files.createTempFile(directory, prefix, ".sorted");

    final OfflineSorter.ByteSequencesWriter writer =
        new OfflineSorter.ByteSequencesWriter(tempInput);
    boolean success = false;
    try {
      BytesRef spare;
      byte[] buffer = new byte[0];
      ByteArrayDataOutput output = new ByteArrayDataOutput(buffer);

      while ((spare = source.next()) != null) {
        encode(writer, output, buffer, spare, source.payload(), source.contexts(), source.weight());
      }
      writer.close();
      new OfflineSorter(tieBreakByCostComparator).sort(tempInput, tempSorted);
      ByteSequencesReader reader = new OfflineSorter.ByteSequencesReader(tempSorted);
      success = true;
      return reader;

    } finally {
      if (success) {
        IOUtils.close(writer);
      } else {
        try {
          IOUtils.closeWhileHandlingException(writer);
        } finally {
          close();
        }
      }
    }
  }
Exemplo n.º 2
0
  @Override
  public Engine createEngine() throws Exception {
    testFile = "jpa-test." + JpaH2DataStore.FILE_EXT;

    try {
      // File temp = Files.createTempFile("jpa-test", "." + JpaH2DataStore.FILE_EXT).toFile();
      // temp.deleteOnExit();
      testFile = Files.createTempFile("jpa-test", "." + JpaH2DataStore.FILE_EXT).toString();

    } catch (final IOException ex) {
      Logger.getLogger(JpaH2EngineTest.class.getName())
          .log(Level.SEVERE, ex.getLocalizedMessage(), ex);
      fail();
    }

    EngineFactory.deleteDatabase(testFile);

    try {
      return EngineFactory.bootLocalEngine(
          testFile, EngineFactory.DEFAULT, PASSWORD, DataStoreType.H2_DATABASE);
    } catch (final Exception e) {
      fail(e.getMessage());
      return null;
    }
  }
Exemplo n.º 3
0
 /**
  * Copies the content of a JAR resource to the destination specified before the container starts
  * up. Useful to add test configuration files before tests are run.
  *
  * @param resourceInputStream input stream to te he JAR resource to copy
  * @param destination destination relative to DDF_HOME
  * @return option object to include in a {@link #configureCustom()} method
  * @throws IOException thrown if a problem occurs while copying the resource
  */
 protected Option installStartupFile(InputStream resourceInputStream, String destination)
     throws IOException {
   File tempFile = Files.createTempFile("StartupFile", ".temp").toFile();
   tempFile.deleteOnExit();
   FileUtils.copyInputStreamToFile(resourceInputStream, tempFile);
   return replaceConfigurationFile(destination, tempFile);
 }
  @Test
  public void testLoadFromJar() throws Exception {
    File jar = Files.createTempFile("battlecode-test", ".jar").toFile();

    jar.deleteOnExit();

    ZipOutputStream z = new ZipOutputStream(new FileOutputStream(jar));

    ZipEntry classEntry = new ZipEntry("instrumentertest/Nothing.class");

    z.putNextEntry(classEntry);

    IOUtils.copy(
        getClass().getClassLoader().getResourceAsStream("instrumentertest/Nothing.class"), z);

    z.closeEntry();
    z.close();

    IndividualClassLoader jarLoader =
        new IndividualClassLoader(
            "instrumentertest", new IndividualClassLoader.Cache(jar.toURI().toURL()));

    Class<?> jarClass = jarLoader.loadClass("instrumentertest.Nothing");

    URL jarClassLocation = jarClass.getResource("Nothing.class");

    // EXTREMELY scientific

    assertTrue(jarClassLocation.toString().startsWith("jar:"));
    assertTrue(jarClassLocation.toString().contains(jar.toURI().toURL().toString()));
  }
  private LameResult index(JarFile jar, JarEntry jarEntry)
      throws IOException, MojoExecutionException {
    // lib/spring.jar
    // suffix -> ".jar
    // prefix -> "spring"
    String name = jarEntry.getName();
    int dotIndex = name.lastIndexOf('.');
    String suffix = name.substring(dotIndex);
    int slashIndex = name.lastIndexOf('/');
    String prefix;
    if (slashIndex == -1) {
      prefix = name.substring(0, dotIndex);
    } else {
      prefix = name.substring(slashIndex + 1, dotIndex);
    }

    Path tempPath = Files.createTempFile(prefix, suffix);
    File tempFile = tempPath.toFile();
    try (InputStream input = jar.getInputStream(jarEntry)) {
      // Files.copy will do the buffering
      Files.copy(input, tempPath, REPLACE_EXISTING);
    }
    LameIndex lameIndex;
    try (JarFile tempJar = new JarFile(tempFile)) {
      lameIndex = index(tempJar);
    }
    boolean changed = lameIndex.changed;
    if (changed) {
      tempFile = writeIndexes(tempFile, name, lameIndex.subDeploymentIndices);
      return new LameResult(tempFile, true, lameIndex.index);
    } else {
      return new LameResult(null, false, null);
    }
  }
  @BeforeClass
  public static void setUpClass() throws IOException {

    // Run before the test JVM starts to ensure the dynamic download
    // actually happens during the test run

    PropsUtil.setProps(new PropsImpl());

    String jarName =
        PropsUtil.get(PropsKeys.SETUP_LIFERAY_POOL_PROVIDER_JAR_NAME, new Filter("hikaricp"));

    Path jarPath = Paths.get("lib/portal", jarName);

    if (Files.exists(jarPath)) {
      Path tempFilePath = Files.createTempFile(null, null);

      Files.move(jarPath, tempFilePath, StandardCopyOption.REPLACE_EXISTING);

      URI uri = tempFilePath.toUri();

      URL url = uri.toURL();

      System.setProperty(_HIKARICP_JAR_URL, url.toExternalForm());
    }
  }
Exemplo n.º 7
0
  /**
   * Sends a GET request and returns the response.
   *
   * @param endpoint The endpoint to send the request to.
   * @param headers Any additional headers to send with this request. You can use {@link
   *     org.apache.http.HttpHeaders} constants for header names.
   * @return A {@link Path} to the downloaded content, if any.
   * @throws IOException If an error occurs.
   * @see java.nio.file.Files#probeContentType(Path)
   */
  public Response<Path> get(Endpoint endpoint, NameValuePair... headers) throws IOException {

    // Create the request
    HttpGet get = new HttpGet(endpoint.url());
    get.setHeaders(combineHeaders(headers));
    Path tempFile = null;

    // Send the request and process the response
    try (CloseableHttpResponse response = httpClient().execute(get)) {

      if (response.getStatusLine().getStatusCode() != HttpStatus.OK_200) {
        return null;
      } // If bad response return null

      // Request the content
      HttpEntity entity = response.getEntity();

      // Download the content to a temporary file
      if (entity != null) {
        tempFile = Files.createTempFile("download", "file");
        try (InputStream input = entity.getContent();
            OutputStream output = Files.newOutputStream(tempFile)) {
          IOUtils.copy(input, output);
        }
      }

      return new Response<>(response.getStatusLine(), tempFile);
    }
  }
  /** Create a jar file from the classes directory, creating it directly in the toolkit. */
  private static String createJarFile(File toolkitLib, final File classesDir) throws IOException {

    final Path classesPath = classesDir.toPath();
    Path jarPath = Files.createTempFile(toolkitLib.toPath(), "classes", ".jar");
    try (final JarOutputStream jarOut =
        new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(jarPath.toFile()), 128 * 1024))) {

      Files.walkFileTree(
          classesDir.toPath(),
          new FileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                throws IOException {
              return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
              File classFile = file.toFile();
              if (classFile.isFile()) {
                //  Write the entry followed by the data.
                Path relativePath = classesPath.relativize(file);
                JarEntry je = new JarEntry(relativePath.toString());
                je.setTime(classFile.lastModified());
                jarOut.putNextEntry(je);

                final byte[] data = new byte[32 * 1024];
                try (final BufferedInputStream classIn =
                    new BufferedInputStream(new FileInputStream(classFile), data.length)) {

                  for (; ; ) {
                    int count = classIn.read(data);
                    if (count == -1) break;
                    jarOut.write(data, 0, count);
                  }
                }
                jarOut.closeEntry();
              }
              return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
              return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                throws IOException {
              dir.toFile().delete();
              return FileVisitResult.CONTINUE;
            }
          });
    }

    return jarPath.getFileName().toString();
  }
Exemplo n.º 9
0
 private Path dumpSearchResults(User user, Request request)
     throws ParseException, IOException, FileNotFoundException {
   user = userService.validate(user);
   Query query = searchService.getQuery(request);
   IndexSearcher searcher = getSearcher(request, user);
   Filter f =
       NumericRangeFilter.newLongRange(
           MailSchemaField.date.name(), request.startTime, request.endTime, true, true);
   TopDocs docs = searcher.search(query, f, request.scanSize);
   Path tempFile =
       Files.createTempFile(format("kw-%s-%s", user.id, request.keywordField), ".mailytics.temp");
   PrintWriter writer = new PrintWriter(tempFile.toFile());
   TIntHashSet dupSet = new TIntHashSet();
   for (ScoreDoc sd : docs.scoreDocs) {
     Document doc = searcher.doc(sd.doc);
     String string = doc.get(request.keywordField.name());
     int hash = string.hashCode();
     if (!dupSet.contains(hash)) {
       writer.println(string);
       dupSet.add(hash);
     }
   }
   dupSet.clear();
   writer.close();
   return tempFile;
 }
Exemplo n.º 10
0
  private static String getCustomProperties() throws ReporterException {
    if (System.getProperty("reporter.config") == null) {
      return null;
    }
    File propFile = new File(System.getProperty("reporter.config"));
    if (!propFile.exists() || propFile.isDirectory()) {
      return null;
    }

    try {
      File file = Files.createTempFile("reporter", ".properties").toFile();
      file.deleteOnExit();
      FileWriter fw = new FileWriter(file);
      String fileText = new String(Files.readAllBytes(propFile.toPath()));

      // replace variables
      fileText =
          fileText.replace(
              "${file.separator}", Matcher.quoteReplacement(System.getProperty("file.separator")));
      fileText =
          fileText.replace("${user.dir}", Matcher.quoteReplacement(System.getProperty("user.dir")));

      fw.write(fileText);
      fw.close();
      return file.getAbsolutePath();
    } catch (IOException e) {
      throw new ReporterException(
          "Failed to read custom config file at: " + propFile.getAbsolutePath());
    }
  }
  /**
   * Uncompress a file to a temporary file.
   *
   * @param context Step context
   * @param file file to uncompress
   * @return the path to the uncompressed file
   * @throws IOException if an error occurs while creating the uncompressed file
   */
  private File uncompressFile(final TaskContext context, final DataFile file) throws IOException {

    checkNotNull(file, "file argument cannot be null");

    final DataFile realFile;
    final DataProtocol protocol = file.getProtocol();

    // Get the underlying file if the file protocol is a storage protocol
    if (protocol instanceof StorageDataProtocol) {

      realFile = ((StorageDataProtocol) protocol).getUnderLyingData(file);
    } else {
      realFile = file;
    }

    final File outputFile =
        Files.createTempFile(
                context.getLocalTempDirectory().toPath(),
                MODULE_NAME + "-",
                realFile.getExtension())
            .toFile();

    context.getLogger().fine("Uncompress/copy " + realFile + " to " + outputFile);

    DataFiles.copy(realFile, new DataFile(outputFile));

    return outputFile;
  }
Exemplo n.º 12
0
  public void testInvalidFormat(ImageResultVerifier... verifiers) throws IOException {
    Path tempFile = null;
    try {
      tempFile = Files.createTempFile("jtrim", ".test");

      final ContextAwareTaskExecutor taskExecutor =
          TaskExecutors.contextAware(SyncTaskExecutor.getSimpleExecutor());

      AsyncDataLink<ImageResult> link = create(tempFile, taskExecutor);
      ImageCollectorListener listener = new ImageCollectorListener(taskExecutor);
      AsyncDataController controller = link.getData(Cancellation.UNCANCELABLE_TOKEN, listener);
      assertNotNull(controller.getDataState());
      controller.controlData(null);

      AsyncReport report = listener.getReport();
      ImageResult lastResult = listener.getLastResult();
      long imageCount = listener.getImageCount();

      listener.verifyNoTrivialErrors();

      assertEquals("Should not have received an image.", 0L, imageCount);

      ImageResultVerifier verifier =
          combineVerifiers(new FailedVerifier(Throwable.class), combineVerifiers(verifiers));
      verifier.verifyImageResult(imageCount, lastResult, report);
    } finally {
      if (tempFile != null) {
        Files.deleteIfExists(tempFile);
      }
    }
  }
  public static void reconstructTurtle(File partFolder, File reconstructed) throws IOException {
    Path tmpOut = Files.createTempFile(partFolder.toPath(), "reconstr", ".tmp");
    FileOutputStream dstOut = new FileOutputStream(tmpOut.toFile());
    FileChannel dstOutChannel = dstOut.getChannel();
    try {
      if (!Files.isDirectory(partFolder.toPath()))
        throw new IOException("Not a directory: " + partFolder);
      File[] fileList =
          FileUtils.listFiles(partFolder, new PrefixFileFilter("part"), TrueFileFilter.TRUE)
              .toArray(new File[0]);
      Arrays.sort(fileList);
      RandomAccessFile inputFile;

      inputFile = new RandomAccessFile(fileList[0], "r");
      inputFile.getChannel().transferTo(0, inputFile.length(), dstOutChannel);
      inputFile.close();
      for (int i = 1; i < fileList.length; i++) {
        inputFile = new RandomAccessFile(fileList[i], "r");
        long lastPrefix = findTurtlePrefixEnd(inputFile);
        inputFile
            .getChannel()
            .transferTo(lastPrefix, inputFile.length() - lastPrefix, dstOutChannel);
        inputFile.close();
      }
    } finally {
      dstOut.close();
    }
    Files.move(
        tmpOut,
        reconstructed.toPath(),
        StandardCopyOption.ATOMIC_MOVE,
        StandardCopyOption.REPLACE_EXISTING);
    FileUtils.deleteQuietly(tmpOut.toFile());
    FileUtils.deleteQuietly(partFolder);
  }
Exemplo n.º 14
0
 public FileBucket() {
   try {
     path = Files.createTempFile(null, null);
     path.toFile().deleteOnExit();
   } catch (IOException e) {
   }
 }
Exemplo n.º 15
0
  @Test
  public void testFileRollover() throws IOException {
    Path homeDir = Files.createTempDirectory("logger");
    Path statusPath = Files.createTempFile("status", "dat");

    ProtoLogger p = new ProtoLogger(homeDir.toString());
    p.setMaxLogFile(500);

    for (int i = 0; i < 1000; i++) {
      p.write("topic-1", ByteString.copyFromUtf8(i + ""));
    }
    p.close();

    ProtoSpout ps =
        new ProtoSpout(
            new ProtoSpout.TupleParser() {
              @Override
              public List<Object> parse(ByteString buffer) {
                return Collections.<Object>singletonList(buffer.toStringUtf8());
              }

              @Override
              public Fields getOutputFields() {
                throw new UnsupportedOperationException("Default operation");
              }
            },
            statusPath.toFile(),
            new File(homeDir.toFile(), "topic-1"),
            Pattern.compile("[0-9a-f]*"));

    final List<List<Object>> tuples = Lists.newArrayList();
    SpoutOutputCollector collector =
        new SpoutOutputCollector(null) {
          @Override
          public List<Integer> emit(List<Object> tuple) {
            tuples.add(tuple);
            return null;
          }

          @Override
          public List<Integer> emit(List<Object> tuple, Object messageId) {
            return emit(tuple);
          }
        };
    ps.open(null, null, collector);

    for (int i = 0; i < 1000; i++) {
      ps.nextTuple();
    }
    assertEquals(1000, tuples.size());

    Iterator<List<Object>> ix = tuples.iterator();
    for (int i = 0; i < 1000; i++) {
      List<Object> x = ix.next();
      assertEquals(1, x.size());
      assertEquals(i + "", x.get(0));
    }
  }
 public void injectIcon(int id, final InputStream iconStream) throws IOException {
   Path f = Files.createTempFile("launcher", "ico");
   try {
     Files.copy(iconStream, f, StandardCopyOption.REPLACE_EXISTING);
   } finally {
     iconStream.close();
   }
   new IconResourceInjector().injectIcon(f.toFile(), myRoot, "IRD" + id);
 }
Exemplo n.º 17
0
  @Test
  public void testFile() {

    List<String> stringData = new ArrayList<>();

    for (int i = 0; i < 100; i++) {
      stringData.add(UUID.randomUUID().toString());
    }

    List<Integer> integerData = new ArrayList<>();

    for (String uuid : stringData) {
      integerData.add(uuid.hashCode());
    }

    File tempFile = null;

    try {
      tempFile = Files.createTempFile("test", "").toFile();
      tempFile.deleteOnExit();
    } catch (IOException e) {
      fail(e.toString());
    }

    try (FileOutputStream fos = new FileOutputStream(tempFile)) {
      BinaryStreamDriver bsd = new BinaryStreamDriver();
      XStream xstream = new XStream(bsd);

      try (ObjectOutputStream out = xstream.createObjectOutputStream(fos)) {
        out.writeObject(stringData);
        out.writeObject(integerData);
      }
    } catch (IOException e) {
      fail(e.toString());
    }

    assertTrue(FileMagic.isBinaryXStreamFile(tempFile));
    assertFalse(FileMagic.isOfxV2(tempFile));

    try (FileInputStream fis = new FileInputStream(tempFile)) {
      BinaryStreamDriver bsd = new BinaryStreamDriver();
      XStream xstream = new XStream(bsd);

      try (ObjectInputStream in = xstream.createObjectInputStream(fis)) {
        List<?> strings = (List<?>) in.readObject();
        List<?> integers = (List<?>) in.readObject();

        assertArrayEquals(strings.toArray(), stringData.toArray());
        assertArrayEquals(integers.toArray(), integerData.toArray());
      } catch (ClassNotFoundException e) {
        fail(e.toString());
      }
    } catch (IOException e) {
      fail(e.toString());
    }
  }
Exemplo n.º 18
0
  @Override
  public IExtendedScannerInfo getDefaultScannerInfo(
      IBuildConfiguration buildConfig,
      IExtendedScannerInfo baseScannerInfo,
      ILanguage language,
      URI buildDirectoryURI) {
    try {
      String[] commands = getCompileCommands(language);
      if (commands == null || commands.length == 0) {
        // no default commands
        return null;
      }

      Path buildDirectory = Paths.get(buildDirectoryURI);

      // Pick the first one
      Path command = Paths.get(commands[0]);
      List<String> commandLine = new ArrayList<>();
      if (command.isAbsolute()) {
        commandLine.add(command.toString());
      } else {
        commandLine.add(getCommandPath(command).toString());
      }

      if (baseScannerInfo != null && baseScannerInfo.getIncludePaths() != null) {
        for (String includePath : baseScannerInfo.getIncludePaths()) {
          commandLine.add("-I" + includePath); // $NON-NLS-1$
        }
      }

      addDiscoveryOptions(commandLine);

      // output to stdout
      commandLine.add("-o"); // $NON-NLS-1$
      commandLine.add("-"); // $NON-NLS-1$

      // Source is an empty tmp file
      String extension;
      if (GPPLanguage.ID.equals(language.getId())) {
        extension = ".cpp";
      } else if (GCCLanguage.ID.equals(language.getId())) {
        extension = ".c";
      } else {
        // In theory we shouldn't get here
        return null;
      }

      Path tmpFile = Files.createTempFile(buildDirectory, ".sc", extension); // $NON-NLS-1$
      commandLine.add(tmpFile.toString());

      return getScannerInfo(buildConfig, commandLine, buildDirectory, tmpFile);
    } catch (IOException e) {
      Activator.log(e);
      return null;
    }
  }
Exemplo n.º 19
0
  private boolean canCreate(String pathPart) {
    try {
      Path tempFile = Files.createTempFile(pathPart, "canCreate");
      Files.deleteIfExists(tempFile);

      return true;
    } catch (Exception e) {
      logger.log(Level.SEVERE, "WARNING: Cannot create file: " + pathPart);
      return false;
    }
  }
Exemplo n.º 20
0
  @Slow
  @Test
  public void testProxyWithBigResponseContentWithSlowReader() throws Exception {
    prepareProxy();

    // Create a 6 MiB file
    final int length = 6 * 1024;
    Path targetTestsDir = MavenTestingUtils.getTargetTestingDir().toPath();
    Files.createDirectories(targetTestsDir);
    final Path temp = Files.createTempFile(targetTestsDir, "test_", null);
    byte[] kb = new byte[1024];
    new Random().nextBytes(kb);
    try (OutputStream output = Files.newOutputStream(temp, StandardOpenOption.CREATE)) {
      for (int i = 0; i < length; ++i) output.write(kb);
    }

    prepareServer(
        new HttpServlet() {
          @Override
          protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
            try (InputStream input = Files.newInputStream(temp)) {
              IO.copy(input, response.getOutputStream());
            }
          }
        });

    Request request =
        client.newRequest("localhost", serverConnector.getLocalPort()).path("/proxy/test");
    final CountDownLatch latch = new CountDownLatch(1);
    request.send(
        new BufferingResponseListener(2 * length * 1024) {
          @Override
          public void onContent(Response response, ByteBuffer content) {
            try {
              // Slow down the reader
              TimeUnit.MILLISECONDS.sleep(5);
              super.onContent(response, content);
            } catch (InterruptedException x) {
              response.abort(x);
            }
          }

          @Override
          public void onComplete(Result result) {
            Assert.assertFalse(result.isFailed());
            Assert.assertEquals(200, result.getResponse().getStatus());
            Assert.assertEquals(length * 1024, getContent().length);
            latch.countDown();
          }
        });
    Assert.assertTrue(latch.await(30, TimeUnit.SECONDS));
  }
 @Override
 public Path getTempFile() {
   checkFileStructure();
   Path path = Paths.get(pathFile.toString(), FILE_SYSTEM, TEMP);
   try {
     path = Files.createTempFile(path, null, ".txt");
     return path;
   } catch (IOException e) {
     FileSystemLogging.logger.log(Level.FINE, "IOException while creating temp file", e);
     return null;
   }
 }
Exemplo n.º 22
0
  public static SyncFile updateFileSyncFile(Path filePath, long syncAccountId, SyncFile syncFile)
      throws Exception {

    // Local sync file

    if (FileUtil.getFileKey(filePath) != syncFile.getSyncFileId()) {
      FileUtil.writeFileKey(filePath, String.valueOf(syncFile.getSyncFileId()));
    }

    Path deltaFilePath = null;

    String name = _getName(filePath, syncFile);
    String sourceChecksum = syncFile.getChecksum();
    String sourceFileName = syncFile.getName();
    long sourceVersionId = syncFile.getVersionId();
    String targetChecksum = FileUtil.getChecksum(filePath);

    if (!FileUtil.checksumsEqual(sourceChecksum, targetChecksum)
        && !IODeltaUtil.isIgnoredFilePatchingExtension(syncFile)) {

      deltaFilePath = Files.createTempFile(String.valueOf(filePath.getFileName()), ".tmp");

      deltaFilePath =
          IODeltaUtil.delta(filePath, IODeltaUtil.getChecksumsFilePath(syncFile), deltaFilePath);

      IODeltaUtil.checksums(syncFile);
    }

    syncFile.setChecksum(targetChecksum);
    syncFile.setFilePathName(filePath.toString());
    syncFile.setName(name);

    update(syncFile);

    // Remote sync file

    if ((syncFile.getState() != SyncFile.STATE_ERROR)
        && (syncFile.getState() != SyncFile.STATE_UNSYNCED)) {

      FileEventUtil.updateFile(
          filePath,
          syncAccountId,
          syncFile,
          deltaFilePath,
          name,
          sourceChecksum,
          sourceFileName,
          sourceVersionId,
          targetChecksum);
    }

    return syncFile;
  }
 public Optional<File> intoDirectory(Path path) {
   if (WebDriverFactory.isAlive(driver)) {
     try {
       Path pageSourceFile = Files.createTempFile(path, "pagesource", ".html.txt");
       Files.write(pageSourceFile, pageSource());
       return Optional.of(pageSourceFile.toFile());
     } catch (IOException couldNotCreatePageSourcce) {
       LOGGER.warn("Could not save the page source HTML file", couldNotCreatePageSourcce);
     }
   }
   return Optional.absent();
 }
Exemplo n.º 24
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);
    }
  }
Exemplo n.º 25
0
  @Test
  public void executableExample() throws Exception {
    // Test
    final Path tempFile = Files.createTempFile("sc", ".out").toAbsolutePath();
    ExecutableExample.main(new String[] {tempFile.toString()});

    final List<String> failures =
        compareOutput("ExecutableExample.html", tempFile, TextOutputFormat.html.name());
    if (failures.size() > 0) {
      fail(failures.toString());
    }
  }
 @Test
 public void test() throws IOException {
   final Path tempFile = Files.createTempFile("log4j2", ".xml");
   try {
     final Log4j1ConfigurationConverter.CommandLineArguments cla =
         new Log4j1ConfigurationConverter.CommandLineArguments();
     cla.setPathIn(pathIn);
     cla.setPathOut(tempFile);
     Log4j1ConfigurationConverter.run(cla);
   } finally {
     Files.deleteIfExists(tempFile);
   }
 }
Exemplo n.º 27
0
  private void testWrite(AssetFile asset) throws IOException {
    Path tmpFile = Files.createTempFile("disunity", null);

    try {
      asset.save(tmpFile);

      if (!FileUtils.contentEquals(asset.getSourceFile().toFile(), tmpFile.toFile())) {
        throw new IOException("Files are not equal");
      }
    } finally {
      Files.deleteIfExists(tmpFile);
    }
  }
  /*
   * Read POST uploads and write them to a temp file, returning the Path to that file.
   */
  private static Path readUpload(ByteBuf content) throws IOException {
    byte[] bytes = new byte[content.readableBytes()];
    content.readBytes(bytes);
    content.release();

    // write to a temp file
    Path imgIn = Files.createTempFile("upload", ".jpg");
    Files.write(imgIn, bytes);

    imgIn.toFile().deleteOnExit();

    return imgIn;
  }
Exemplo n.º 29
0
  /**
   * Creates a zip file of the metadata and recorded artifacts and stores it in the artifact cache.
   */
  public void performUploadToArtifactCache(
      ImmutableSet<RuleKey> ruleKeys, ArtifactCache artifactCache, BuckEventBus eventBus)
      throws InterruptedException {

    // Skip all of this if caching is disabled. Although artifactCache.store() will be a noop,
    // building up the zip is wasted I/O.
    if (!artifactCache.isStoreSupported()) {
      return;
    }

    ArtifactCompressionEvent.Started started =
        ArtifactCompressionEvent.started(ArtifactCompressionEvent.Operation.COMPRESS, ruleKeys);
    eventBus.post(started);

    final Path zip;
    ImmutableSet<Path> pathsToIncludeInZip = ImmutableSet.of();
    ImmutableMap<String, String> buildMetadata;
    try {
      pathsToIncludeInZip = getRecordedDirsAndFiles();
      zip =
          Files.createTempFile(
              "buck_artifact_" + MoreFiles.sanitize(buildTarget.getShortName()), ".zip");
      buildMetadata = getBuildMetadata();
      projectFilesystem.createZip(pathsToIncludeInZip, zip, ImmutableMap.<Path, String>of());
    } catch (IOException e) {
      eventBus.post(
          ConsoleEvent.info(
              "Failed to create zip for %s containing:\n%s",
              buildTarget, Joiner.on('\n').join(ImmutableSortedSet.copyOf(pathsToIncludeInZip))));
      e.printStackTrace();
      return;
    } finally {
      eventBus.post(ArtifactCompressionEvent.finished(started));
    }

    // Store the artifact, including any additional metadata.
    ListenableFuture<Void> storeFuture =
        artifactCache.store(ruleKeys, buildMetadata, BorrowablePath.notBorrowablePath(zip));
    storeFuture.addListener(
        new Runnable() {
          @Override
          public void run() {
            try {
              Files.deleteIfExists(zip);
            } catch (IOException e) {
              throw new RuntimeException(e);
            }
          }
        },
        directExecutor());
  }
Exemplo n.º 30
0
  private static void testGetImage(String format, GetImageTest test) throws Throwable {
    Path tempFile = null;
    try {
      tempFile = Files.createTempFile("jtrim", ".test");
      BufferedImage testImage = createTestImageWithoutAlpha(TEST_IMG_WIDTH, TEST_IMG_HEIGHT);
      ImageIO.write(testImage, format, tempFile.toFile());

      test.testGetImage(tempFile);
    } finally {
      if (tempFile != null) {
        Files.deleteIfExists(tempFile);
      }
    }
  }