Java Code Examples for java.nio.file.StandardOpenOption

The following are top voted examples for showing how to use java.nio.file.StandardOpenOption. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Elasticsearch   File: LocalTranslog.java   View source code 9 votes vote down vote up
private FileChannel openReader(long generationId) throws IOException {
    ensureOpen();
    if (readChannels.containsKey(generationId)) {
        return readChannels.get(generationId);
    }
    try {
        Path translogFilePath = this.translogPath.resolve(getFileNameFromId(tmpTranslogGeneration.get()));
        if (!Files.exists(translogFilePath)) {
            return null;
        }
        // maybe a lot of readers try to open reader and put it to readChannel cache, because read lock is shared
        FileChannel readChannel = FileChannel.open(translogFilePath, StandardOpenOption.READ);
        FileChannel originReadChannel = readChannels.putIfAbsent(generationId, readChannel);
        if (originReadChannel != null) {
            IOUtils.close(readChannel);
            return originReadChannel;
        } else {
            return readChannel;
        }
    } catch (Throwable e) {
        throw e;
    }
}
 
Example 2
Project: MpiTaskFramework   File: SharedSystemData.java   View source code 7 votes vote down vote up
/**
 * Constructor.
 * @throws IOException 
 */
public SharedSystemData(String path, boolean create) throws IOException {
	File f = new File(path);
	
	if (create) {
		if (f.exists()) {
			System.out.println("Existing system detected, deleting");
			f.delete(); // Delete if present.
		}
	} else {
		if (!f.exists()) {
			System.err.println("ERROR, system dont exist");
			System.exit(-1);
		}
	}
	channel = FileChannel.open(f.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
	buffer = channel.map(MapMode.READ_WRITE, 0, 4000);
	
	if (create) {
		setNextTaskId(0);
		setShutdownSignal(false);
	}
}
 
Example 3
Project: Re-Collector   File: ChunkReaderScheduler.java   View source code 7 votes vote down vote up
public void followFile(Path file, FileInput.InitialReadPosition customInitialReadPosition) throws IOException {
    synchronized (this) {
        if (isFollowingFile(file)) {
            log.debug("Not following file {} because it's already followed.", file);
            return;
        }

        log.debug("Following file {}", file);

        final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
        final ChunkReader chunkReader = new ChunkReader(input, file, fileChannel, chunkQueue, readerBufferSize, customInitialReadPosition, this);
        final ScheduledFuture<?> chunkReaderFuture = scheduler.scheduleAtFixedRate(chunkReader, 0, readerInterval, TimeUnit.MILLISECONDS);

        chunkReaderTasks.putIfAbsent(file, new ChunkReaderTask(chunkReaderFuture, fileChannel));
    }
}
 
Example 4
Project: buckaroo   File: DownloadTask.java   View source code 6 votes vote down vote up
public static Observable<DownloadProgress> download(final URI url, final Path target, final boolean overwrite) {

        Preconditions.checkNotNull(url);
        Preconditions.checkNotNull(target);

        return Single.fromCallable(() -> {

            final Path parent = target.getParent();

            if (parent != null && !Files.exists(parent)) {
                Files.createDirectories(parent);
            }

            if (overwrite) {
                return Files.newOutputStream(target, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
            }

            return Files.newOutputStream(target, StandardOpenOption.CREATE_NEW);
        }).flatMapObservable(outputStream -> download(url, outputStream));
    }
 
Example 5
Project: smart-testing   File: NewTestsGitBasedDetectorTest.java   View source code 6 votes vote down vote up
@Test
public void should_find_local_newly_staged_files_as_new() throws IOException, GitAPIException {
    //given
    Configuration configuration = createConfiguration("a4261d5", "1ee4abf");
    final File testFile = gitFolder.newFile("core/src/test/java/org/arquillian/smart/testing/CalculatorTest.java");
    Files.write(testFile.toPath(), getContentsOfClass().getBytes(), StandardOpenOption.APPEND);

    GitRepositoryOperations.addFile(gitFolder.getRoot(), testFile.getAbsolutePath());

    final NewTestsDetector newTestsDetector =
        new NewTestsDetector(new GitChangeResolver(), new NoopStorage(), gitFolder.getRoot(), path -> true, configuration);

    // when
    final Collection<TestSelection> newTests = newTestsDetector.getTests();

    // then
    assertThat(newTests).extracting(TestSelection::getClassName)
        .containsOnly("org.arquillian.smart.testing.CalculatorTest",
            "org.arquillian.smart.testing.vcs.git.NewFilesDetectorTest");
}
 
Example 6
Project: r8   File: JumboString.java   View source code 6 votes vote down vote up
public static void generate() throws IOException {
  int stringsPerFile = (1 << 14);
  for (int fileNumber = 0; fileNumber < 2; fileNumber++) {
    Path path = FileSystems.getDefault().getPath("StringPool" + fileNumber + ".java");
    PrintStream out = new PrintStream(
        Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND));

    out.println(
        "// Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file");
    out.println(
        "// for details. All rights reserved. Use of this source code is governed by a");
    out.println("// BSD-style license that can be found in the LICENSE file.");
    out.println("package jumbostring;");
    out.println();
    out.println("class StringPool" + fileNumber + " {");

    int offset = fileNumber * stringsPerFile;
    for (int i = offset; i < offset + stringsPerFile; i++) {
      out.println("  public static final String s" + i + " = \"" + i + "\";");
    }
    out.println("}");
    out.close();
  }
}
 
Example 7
Project: fuse-nio-adapter   File: OpenOptionsUtil.java   View source code 6 votes vote down vote up
public Set<OpenOption> fuseOpenFlagsToNioOpenOptions(Set<OpenFlags> flags) {
	Set<OpenOption> result = new HashSet<>();
	if (flags.contains(OpenFlags.O_RDONLY) || flags.contains(OpenFlags.O_RDWR)) {
		result.add(StandardOpenOption.READ);
	}
	if (flags.contains(OpenFlags.O_WRONLY) || flags.contains(OpenFlags.O_RDWR)) {
		result.add(StandardOpenOption.WRITE);
	}
	if (flags.contains(OpenFlags.O_APPEND)) {
		result.add(StandardOpenOption.APPEND);
	}
	if (flags.contains(OpenFlags.O_TRUNC)) {
		result.add(StandardOpenOption.TRUNCATE_EXISTING);
	}
	return result;
}
 
Example 8
Project: kafka-0.11.0.0-src-with-comment   File: StateDirectoryTest.java   View source code 6 votes vote down vote up
@Test
public void shouldReleaseTaskStateDirectoryLock() throws Exception {
    final TaskId taskId = new TaskId(0, 0);
    final File taskDirectory = directory.directoryForTask(taskId);

    directory.lock(taskId, 1);
    directory.unlock(taskId);

    try (
        final FileChannel channel = FileChannel.open(
            new File(taskDirectory, StateDirectory.LOCK_FILE_NAME).toPath(),
            StandardOpenOption.CREATE,
            StandardOpenOption.WRITE)
    ) {
        channel.tryLock();
    }
}
 
Example 9
Project: drinkwater-java   File: PropertiesTest.java   View source code 6 votes vote down vote up
@Test
public void shouldWorkWithApplicationPropertiesFormOtherLocation() throws Exception {

    //create an external propertiesfile
    File propertiesFile = folder.newFile("external.properties");

    Files.write(Paths.get(propertiesFile.getPath()),
            "info=info from external properties file".getBytes(),
            StandardOpenOption.APPEND);

    DrinkWaterApplication propertiesApp = DrinkWaterApplication.create("PropertiesTest-application");
    propertiesApp.addServiceBuilder(new PropertiesTestConfiguration("test-external-properties", propertiesFile.getPath()));

    try {
        propertiesApp.start();

        String result = httpGetString(String.format("http://127.0.0.1:%s/test-external-properties/info",
                propertiesApp.getServiceProperty("test-external-properties", RestService.REST_PORT_KEY))).result();
        assertEquals("info from external properties file", result);

    }
    finally {
        propertiesApp.stop();
    }
}
 
Example 10
Project: LotusCloud   File: Database.java   View source code 6 votes vote down vote up
private void initialize() {
    try {
        if (!dbFile.exists()) {
            Files.write(dbFile.toPath(), "".getBytes(), StandardOpenOption.CREATE);
        }
        String dbContent = new String(Files.readAllBytes(dbFile.toPath()), StandardCharsets.UTF_8);
        for (String line : dbContent.split("/-/")) {
            if (line.trim().equals("")) {
                continue;
            }
            String[] keyValue = line.split("=");
            values.put(keyValue[0], new String(Base64.getDecoder().decode(keyValue[1]), StandardCharsets.UTF_8));
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
 
Example 11
Project: mux2fs   File: MirrorFsTest.java   View source code 6 votes vote down vote up
@Test
public void testReleaseClosesOpenFileChannel()
		throws Exception {
	// Given
	FileHandleFiller filler = mock(FileHandleFiller.class);
	ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class);
	doNothing().when(filler).setFileHandle(handleCaptor.capture());
	Path fooBar = mockPath(mirrorRoot, "foo.bar");
	FileChannel fileChannel = mock(FileChannel.class);
	when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel);
	fs.open("foo.bar", filler);
	// When
	int result = fs.release("foo.bar", handleCaptor.getValue());
	// Then
	assertThat(result).isEqualTo(SUCCESS);
	verify(fileChannelCloser).close(fileChannel);
	verifyNoMoreInteractions(fileChannel);
}
 
Example 12
Project: jenkins-client-plugin   File: BaseStep.java   View source code 6 votes vote down vote up
public static boolean withTempInput(String prefix, String content,
        WithTempInputRunnable runnable) throws IOException,
        InterruptedException {
    Path tmp = null;
    try {
        if (content != null) {
            tmp = Files.createTempFile(prefix, ".tmp");
            ArrayList<String> list = new ArrayList<String>(1);
            list.add(content);
            Files.write(tmp, list, StandardCharsets.UTF_8,
                    StandardOpenOption.WRITE);
        }
        return runnable.perform((tmp == null) ? null : tmp.toAbsolutePath()
                .toString());
    } finally {
        if (tmp != null) {
            Files.delete(tmp);
        }
    }
}
 
Example 13
Project: alfresco-repository   File: BulkImportTest.java   View source code 6 votes vote down vote up
private void unpack(Path source, Path destFile)
{
    Path archive = source.resolve("testbulk.gz");
        
    try (GZIPInputStream gzis = new GZIPInputStream(Files.newInputStream(archive));
         OutputStream out = Files.newOutputStream(destFile, StandardOpenOption.CREATE))
    {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = gzis.read(buffer)) > 0) 
        {
            out.write(buffer, 0, len);
        }
    }
    catch (IOException ex)
    {
        ex.printStackTrace();   
    }
}
 
Example 14
Project: jpeek   File: DefaultBaseTest.java   View source code 6 votes vote down vote up
@Test
public void listsFiles() throws IOException {
    final Path temp = Files.createTempDirectory("");
    temp.resolve("a/b/c").toFile().mkdirs();
    Files.write(
        temp.resolve("a/b/c/x.java"), "Hello".getBytes(),
        StandardOpenOption.CREATE_NEW
    );
    Files.write(
        temp.resolve("a/z.class"), "".getBytes(),
        StandardOpenOption.CREATE_NEW
    );
    MatcherAssert.assertThat(
        new DefaultBase(temp).files(),
        Matchers.iterableWithSize(Matchers.greaterThan(2))
    );
}
 
Example 15
Project: centraldogma   File: CommitIdDatabaseTest.java   View source code 6 votes vote down vote up
@Test
public void truncatedDatabase() throws Exception {
    db.put(Revision.INIT, randomCommitId());
    db.close();

    // Truncate the database file.
    try (FileChannel f = FileChannel.open(new File(tmpDir.getRoot(), "commit_ids.dat").toPath(),
                     StandardOpenOption.APPEND)) {

        assertThat(f.size()).isEqualTo(24);
        f.truncate(23);
    }

    assertThatThrownBy(() -> new CommitIdDatabase(tmpDir.getRoot()))
            .isInstanceOf(StorageException.class)
            .hasMessageContaining("incorrect file length");
}
 
Example 16
Project: smart-testing   File: NewTestsGitBasedDetectorTest.java   View source code 6 votes vote down vote up
@Test
public void should_not_find_local_modified_file_as_new_when_using_commit_range() throws IOException {
    //given
    Configuration configuration = createConfiguration("a4261d5", "1ee4abf");
    final Path testFile = Paths.get(gitFolder.getRoot().getAbsolutePath(),
        "core/src/test/java/org/arquillian/smart/testing/FilesTest.java");

    Files.write(testFile, "//This is a test".getBytes(), StandardOpenOption.APPEND);

    final NewTestsDetector newTestsDetector =
        new NewTestsDetector(new GitChangeResolver(), new NoopStorage(), gitFolder.getRoot(), path -> true, configuration);

    // when
    final Collection<TestSelection> newTests = newTestsDetector.getTests();

    // then
    assertThat(newTests).extracting(TestSelection::getClassName)
        .doesNotContain("org.arquillian.smart.testing.FilesTest");
}
 
Example 17
Project: CPUEmulator   File: Compiler.java   View source code 6 votes vote down vote up
@Deprecated
public static void main(String [] args) throws IOException
{
    // Lets the user choose his outputing file
    String filename = "testing.out";
    // Initializes the path to said file
    Path path_to_program = Paths.get(filename);
    // Clears the file by writing nothing
    Files.write(path_to_program, new byte[]{});
    // Actual program in op-codes
    byte[][] instructions = {{CPUMain.PUSH, 0x45}, {CPUMain.POP, 0x00}, {CPUMain.PLACE, 0x03, 0x35}, {CPUMain.DIV, 0x02, 0x03}, {CPUMain.PRINT, 0x02}};
    for (byte[] instruction: instructions)
    {
        // Write to file the desired bytes
        Files.write(path_to_program, instruction, StandardOpenOption.APPEND);
    }
    // Output completion of the process to the user
    System.out.println("Done writing program to " + filename);
}
 
Example 18
Project: openjdk-jdk10   File: CheckZombieLockTest.java   View source code 5 votes vote down vote up
/**
 * Setup all the files and directories needed for the tests
 *
 * @return writable directory created that needs to be deleted when done
 * @throws RuntimeException
 */
private static File setup() throws RuntimeException {
    // First do some setup in the temporary directory (using same logic as
    // FileHandler for %t pattern)
    String tmpDir = System.getProperty("java.io.tmpdir"); // i.e. %t
    if (tmpDir == null) {
        tmpDir = System.getProperty("user.home");
    }
    File tmpOrHomeDir = new File(tmpDir);
    // Create a writable directory here (%t/writable-lockfile-dir)
    File writableDir = new File(tmpOrHomeDir, WRITABLE_DIR);
    if (!createFile(writableDir, true)) {
        throw new RuntimeException("Test setup failed: unable to create"
                + " writable working directory "
                + writableDir.getAbsolutePath() );
    }

    // try to determine whether file locking is supported
    final String uniqueFileName = UUID.randomUUID().toString()+".lck";
    try {
        FileChannel fc = FileChannel.open(Paths.get(writableDir.getAbsolutePath(),
                uniqueFileName),
                StandardOpenOption.CREATE_NEW, StandardOpenOption.APPEND,
                StandardOpenOption.DELETE_ON_CLOSE);
        try {
            fc.tryLock();
        } catch(IOException x) {
            supportsLocking = false;
        } finally {
            fc.close();
        }
    } catch (IOException t) {
        // should not happen
        System.err.println("Failed to create new file " + uniqueFileName +
                " in " + writableDir.getAbsolutePath());
        throw new RuntimeException("Test setup failed: unable to run test", t);
    }
    return writableDir;
}
 
Example 19
Project: tqdev-metrics   File: PrometheusLogReporterTest.java   View source code 5 votes vote down vote up
/**
 * Should remove files.
 *
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Test
public void shouldRemoveFiles() throws IOException {
	registry.add("jdbc.Statement.Duration", "select", 123);
	String line = "jdbc{host=\"localhost\",instance=\"Statement\",type=\"Duration\",type_instance=\"select\"} 123 1510373758000\n";
	Files.createFile(tempPath.resolve("1510373738123.prom"));
	Files.createFile(tempPath.resolve("1510373748123.prom"));
	Files.write(tempPath.resolve("1510373758123.prom"), line.getBytes(), StandardOpenOption.CREATE_NEW);
	boolean success = reporter.report();
	File[] promFiles = tempPath.toFile().listFiles((f, s) -> s.endsWith(".prom"));
	assertThat(success).isTrue();
	assertThat(promFiles.length).isEqualTo(2);
	assertThat(promFiles[0].getName()).isEqualTo("1510373748123.prom");
	assertThat(promFiles[1].getName()).isEqualTo("1510373758123.prom");
}
 
Example 20
Project: openjdk-jdk10   File: ClassAndLibraryNotMatchTest.java   View source code 5 votes vote down vote up
private void writeHelloWorld(String message) {
    String src = HELLO_WORLD_PRE + message + HELLO_WORLD_POST;
    try{
        Files.write(Paths.get(HELLO_WORLD_FILE), src.getBytes(), StandardOpenOption.CREATE);
    } catch (IOException e) {
        throw new Error("Can't write HelloWorld " + e, e);
    }
}
 
Example 21
Project: mux2fs   File: MuxFsTest.java   View source code 5 votes vote down vote up
@Test
public void testReadFromFailedMuxedFile()
		throws Exception {
	// Given
	FileHandleFiller filler = mock(FileHandleFiller.class);
	ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class);
	doNothing().when(filler).setFileHandle(handleCaptor.capture());
	Path mkv = mockPath("file1.mkv");
	Path srt = mockPath("file1.eng.srt", 2893756L);
	mockShuffledDirectoryStream(mirrorRoot, mkv, srt);
	mockAttributes(mkv, 1);
	Muxer muxer = mock(Muxer.class);
	when(muxerFactory.from(mkv, srt, tempDir)).thenReturn(muxer);
	Path muxedFile = mockPath(tempDir, "file1-muxed.mkv");
	when(muxer.getOutput()).thenReturn(Optional.of(muxedFile));
	FileChannel fileChannel = mock(FileChannel.class);
	when(fileSystem.provider().newFileChannel(eq(muxedFile), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel);
	fs.open("file1.mkv", filler);
	Integer fileHandle = handleCaptor.getValue();
	when(muxer.state()).thenReturn(State.FAILED);
	// When
	int result = fs.read("file1.mkv", (data) -> fail(), 128, 64, fileHandle);
	// Then
	assertThat(result).isEqualTo(-ErrorCodes.EIO());
	verify(muxerFactory).from(mkv, srt, tempDir);
	verifyNoMoreInteractions(muxerFactory);
	verify(muxer).start();
	verify(muxer).waitForOutput();
	verify(muxer).getOutput();
	verify(muxer).state();
	verifyNoMoreInteractions(muxer);
	verify(filler).setFileHandle(gt(1));
	verifyNoMoreInteractions(fileChannel);
}
 
Example 22
Project: personium-core   File: SnapshotFile.java   View source code 5 votes vote down vote up
/**
 * Write to data pjson.
 * @param data Data to write
 */
public void writeDataPJson(String data) {
    Path pathInZip = pathMap.get(DATA_PJSON);
    try (BufferedWriter writer = Files.newBufferedWriter(pathInZip, Charsets.UTF_8,
            StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) {
        writer.write(data);
    } catch (IOException e) {
        throw PersoniumCoreException.Common.FILE_IO_ERROR.params("add data pjson to snapshot file").reason(e);
    }
}
 
Example 23
Project: incubator-netbeans   File: Stamps.java   View source code 5 votes vote down vote up
private ByteBuffer asByteBuffer(String cache, boolean direct, boolean mmap) {
    int[] len = new int[1];
    File cacheFile = file(cache, len);
    if (cacheFile == null) {
        return null;
    }
    
    try (FileChannel fc = FileChannel.open(cacheFile.toPath(), StandardOpenOption.READ)){
        ByteBuffer master;
        if (mmap) {
            master = fc.map(FileChannel.MapMode.READ_ONLY, 0, len[0]);
            master.order(ByteOrder.LITTLE_ENDIAN);
        } else {
            master = direct ? ByteBuffer.allocateDirect(len[0]) : ByteBuffer.allocate(len[0]);
            int red = fc.read(master);
            if (red != len[0]) {
                LOG.warning("Read less than expected: " + red + " expected: " + len + " for " + cacheFile); // NOI18N
                return null;
            }
            master.flip();
        }

        return master;
    } catch (IOException | InvalidPathException ex) {
        LOG.log(Level.WARNING, "Cannot read cache " + cacheFile, ex); // NOI18N
        return null;
    }
}
 
Example 24
Project: StreamDeckCore   File: IconHelper.java   View source code 5 votes vote down vote up
public static void createIconPackage(String pathToArchive, String pathToIcon, String[] pathToFrames,
		AnimationStack stack) throws URISyntaxException, IOException {
	Path path = Paths.get(pathToArchive);
	URI uri = new URI("jar", path.toUri().toString(), null);

	Map<String, String> env = new HashMap<>();
	env.put("create", "true");
	try (FileSystem fileSystem = FileSystems.newFileSystem(uri, env)) {
		Path iconPath = fileSystem.getPath("icon.png");
		// save main icon
		Files.copy(Paths.get(pathToIcon), iconPath, StandardCopyOption.REPLACE_EXISTING);
		// save animation, if exists
		Path animationFile = fileSystem.getPath("animation.json");
		if (stack != null) {
			Gson gson = new GsonBuilder().setPrettyPrinting().create();
			String text = gson.toJson(stack);
			Files.write(animationFile, text.getBytes("UTF-8"), StandardOpenOption.TRUNCATE_EXISTING,
					StandardOpenOption.WRITE);
			// save animation frames
			if (pathToFrames != null) {
				for (int i = 0; i < pathToFrames.length; i++) {
					if (pathToFrames[i] != null) {
						Path iconSourcePath = Paths.get(pathToFrames[i]);
						Path iconTargetPath = fileSystem.getPath(i + ".png");
						Files.copy(iconSourcePath, iconTargetPath, StandardCopyOption.REPLACE_EXISTING);
					}
				}
			}
		}
		fileSystem.close();
	}
}
 
Example 25
Project: eadlsync   File: EADLSyncCommand.java   View source code 5 votes vote down vote up
void updateCommitId(String commitId) throws IOException{
    if (YStatementConstants.COMMIT_ID_PATTERN.matcher(commitId).matches()) {
        try {
            Files.write(EADL_REVISION, commitId.getBytes(), StandardOpenOption.CREATE);
            CLI.println(String.format("\tsync id -> %s", commitId));
        } catch (IOException e) {
            LOG.error("Error writing new commit revision to file.", e);
            throw e;
        }
    } else {
        CLI.println(String.format("Commit was rejected by the se-repo\n\t%s", commitId));
    }
}
 
Example 26
Project: openjdk-jdk10   File: IgnoreSourceErrors.java   View source code 5 votes vote down vote up
void emitSample(Path file) throws IOException {
    String[] contents = {
        "/** A java file with errors */",
        "public static class Foo {}"
    };
    Files.write(file, Arrays.asList(contents), StandardOpenOption.CREATE);
}
 
Example 27
Project: Elasticsearch   File: TranslogWriter.java   View source code 5 votes vote down vote up
protected synchronized void checkpoint(long lastSyncPosition, int operationCounter, ChannelReference channelReference) throws IOException {
    try {
        channelReference.getChannel().force(false);
        writeCheckpoint(lastSyncPosition, operationCounter, channelReference.getPath().getParent(), channelReference.getGeneration(), StandardOpenOption.WRITE);
    } catch (Throwable ex) {
        closeWithTragicEvent(ex);
        throw ex;
    }
}
 
Example 28
Project: aidos-node   File: StorageScratchpad.java   View source code 5 votes vote down vote up
@Override
public void init() throws IOException {
    scratchpadChannel = FileChannel.open(Paths.get(SCRATCHPAD_FILE_NAME), StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
    transactionsToRequest = scratchpadChannel.map(FileChannel.MapMode.READ_WRITE, TRANSACTIONS_TO_REQUEST_OFFSET, TRANSACTIONS_TO_REQUEST_SIZE);
    analyzedTransactionsFlags = scratchpadChannel.map(FileChannel.MapMode.READ_WRITE, ANALYZED_TRANSACTIONS_FLAGS_OFFSET, ANALYZED_TRANSACTIONS_FLAGS_SIZE);
    analyzedTransactionsFlagsCopy = scratchpadChannel.map(FileChannel.MapMode.READ_WRITE, ANALYZED_TRANSACTIONS_FLAGS_COPY_OFFSET, ANALYZED_TRANSACTIONS_FLAGS_COPY_SIZE);	
}
 
Example 29
Project: mux2fs   File: MirrorFsTest.java   View source code 5 votes vote down vote up
@Test
public void testRelease()
		throws Exception {
	// Given
	FileHandleFiller filler = mock(FileHandleFiller.class);
	ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class);
	doNothing().when(filler).setFileHandle(handleCaptor.capture());
	Path fooBar = mockPath(mirrorRoot, "foo.bar");
	when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class));
	fs.open("foo.bar", filler);
	// When
	int result = fs.release("foo.bar", handleCaptor.getValue());
	// Then
	assertThat(result).isEqualTo(SUCCESS);
}
 
Example 30
Project: fuse-nio-adapter   File: ReadWriteFileHandler.java   View source code 5 votes vote down vote up
public int truncate(Path path, long size) {
	try (FileChannel fc = FileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
		return 0;
	} catch (IOException e) {
		LOG.error("Truncating file feild.", e);
		return -ErrorCodes.EIO();
	}
}
 
Example 31
Project: jdk8u-jdk   File: KeytoolReaderP12Test.java   View source code 5 votes vote down vote up
/**
 * Decodes the base64 encoded keystore and writes into new file
 * @param name base64 encoded keystore name
 */
private static void convertToPFX(String name) throws IOException{
    File base64File = new File(SOURCE_DIRECTORY, name);
    File pkcs12File = new File(WORKING_DIRECTORY, name);
    byte[] input = Files.readAllBytes(base64File.toPath());
    Files.write(pkcs12File.toPath(), Base64.getMimeDecoder().
            decode(input), StandardOpenOption.CREATE);
}
 
Example 32
Project: maven-git-code-format   File: DefaulExecutable.java   View source code 5 votes vote down vote up
@Override
public Executable truncateWithTemplate(Supplier<InputStream> template, Object... values)
    throws IOException {
  try (InputStream inputStream = template.get()) {
    String rawContent = IOUtils.toString(inputStream);
    Object[] refinedValues = Stream.of(values).map(this::unixifyPath).toArray();
    String content = String.format(rawContent, refinedValues);
    Files.write(file, content.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);
  }
  return this;
}
 
Example 33
Project: reactive-jax-rs   File: CustomerRepository.java   View source code 5 votes vote down vote up
public Publisher<Integer> save(Publisher<Customer> customers) throws IOException {
  AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
  AtomicLong offset = new AtomicLong(0);
  AtomicInteger resultCount = new AtomicInteger(0);
  SingleItemPublisher<Integer> resultPublisher = new SingleItemPublisher<>();
  Semaphore writeSemaphore = new Semaphore(1);
  writeSemaphore.acquireUninterruptibly();
  fileChannel.write(ByteBuffer.wrap("[".getBytes()), 0, resultPublisher,
      andThen((count, s) -> {
        writeSemaphore.release();
        customers.subscribe(pullEach((Customer customer, Subscription subscription) -> {
            String json = String.format("%s{\"firstName\": \"%s\", \"lastName\": \"%s\"}", offset.longValue() == 0 ? "" : ",",
                customer.getFirstName(), customer.getLastName());
            offset.addAndGet(count);
            writeSemaphore.acquireUninterruptibly();
            fileChannel.write(ByteBuffer.wrap(json.getBytes()), offset.get(), resultPublisher,
                andThen((size, c) -> {
                  writeSemaphore.release();
                  offset.addAndGet(size);
                  resultCount.incrementAndGet();
                  subscription.request(1);
                }));
          }).andThen(() -> {
            writeSemaphore.acquireUninterruptibly();
              fileChannel.write(ByteBuffer.wrap("]".getBytes()), offset.longValue(), resultPublisher,
                  andThen((d, e) -> {
                    writeSemaphore.release();
                    try {
                      fileChannel.close();
                      resultPublisher.publish(resultCount.intValue());
                    } catch (IOException error) {
                      resultPublisher.publish(error);
                    }
                  }));
          }).exceptionally(error -> resultPublisher.publish(error)));
      }));
  return resultPublisher;
}
 
Example 34
Project: openjdk-jdk10   File: ListOptionTest.java   View source code 5 votes vote down vote up
public static void main(String[] args) {
    try {
        Files.write(COMPILE_COMMAND_FILE, Arrays.asList(COMPILE_COMMAND),
                StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
    } catch (IOException e) {
        throw new Error("TESTBUG: can't write list file " + e, e);
    }
    OutputAnalyzer oa = JaotcTestHelper.compileLibrary("--compile-commands", COMPILE_COMMAND_FILE.toString(),
            "--class-name", JaotcTestHelper.getClassAotCompilationName(HelloWorldOne.class));
    oa.shouldHaveExitValue(0);
    File compiledLibrary = new File(JaotcTestHelper.DEFAULT_LIB_PATH);
    Asserts.assertTrue(compiledLibrary.exists(), "Compiled library file missing");
    Asserts.assertGT(compiledLibrary.length(), 0L, "Unexpected compiled library size");
    JaotcTestHelper.checkLibraryUsage(TESTED_CLASS_NAME, EXPECTED, UNEXPECTED);
}
 
Example 35
Project: tqdev-metrics   File: InfluxDbFileReporterTest.java   View source code 5 votes vote down vote up
/**
 * Should compress file.
 *
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Test
public void shouldCompressFile() throws IOException {
	registry.add("jdbc.Statement.Duration", "select", 123);
	String line = "jdbc,host=localhost,instance=Statement,type=Duration,type_instance=select value=123i 1510373758000000000\n";
	Files.write(tempPath.resolve("20171110.txt"), line.getBytes(), StandardOpenOption.CREATE_NEW);
	boolean success = reporter.report();
	File[] gzipFiles = tempPath.toFile().listFiles((f, s) -> s.endsWith(".gz"));
	File[] textFiles = tempPath.toFile().listFiles((f, s) -> s.endsWith(".txt"));
	assertThat(success).isTrue();
	assertThat(gzipFiles.length).isEqualTo(1);
	assertThat(gzipFiles[0].getName()).isEqualTo("20171110.txt.gz");
	assertThat(textFiles.length).isEqualTo(1);
	assertThat(textFiles[0].getName()).isEqualTo("20171111.txt");
}
 
Example 36
Project: Meucci   File: ModLoader.java   View source code 5 votes vote down vote up
private void writeTemplates(Modulo mod)throws IOException{
    if(mod.Tca.length==0 && mod.Ttype.length==0)
        return;
    Path p=Paths.get(cpath+"/"+mod.nome+".tin");
    try(ObjectOutputStream out=new ObjectOutputStream(new 
        BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.WRITE, 
            StandardOpenOption.CREATE)))){
        out.writeObject(mod.Ttype);
        out.writeObject(mod.Tca);
    }
}
 
Example 37
Project: Pet-Supply-Store   File: CreatorRunner.java   View source code 5 votes vote down vote up
@Override
public void run() {
	long imgID = ImageIDFactory.ID.getNextImageID();
	Random rand = new Random(productID);
	
	// All products must be added to the database
	imgDB.setImageMapping(productID, imgID, size);

	// Resolve path and create a new image
	Path imgFile = workingDir.resolve(String.valueOf(imgID));
	
	BufferedImage img = ImageCreator.createImage(shapesPerImage, categoryImage, size, rand);
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	
	try {
		ImageIO.write(img, StoreImage.STORE_IMAGE_FORMAT, stream);
		Files.write(imgFile, Base64.getEncoder().encode(stream.toByteArray()), 
				StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
	} catch (IOException ioException) {
		if (!(ioException instanceof ClosedByInterruptException)) {
			log.warn("An IOException occured while writing image with ID " + String.valueOf(imgID) + " to file "
					+ imgFile.toAbsolutePath() + ".", ioException);
		} else {
			log.warn("An exception was thrown during image creation with ID " + String.valueOf(imgID) + " to file "
					+ imgFile.toAbsolutePath() + ".", ioException);
		}
	}
	
	nrOfImagesGenerated.incrementAndGet();
}
 
Example 38
Project: elasticsearch_my   File: ClientYamlTestSuite.java   View source code 5 votes vote down vote up
public static ClientYamlTestSuite parse(String api, Path file) throws IOException {
    if (!Files.isRegularFile(file)) {
        throw new IllegalArgumentException(file.toAbsolutePath() + " is not a file");
    }

    String filename = file.getFileName().toString();
    //remove the file extension
    int i = filename.lastIndexOf('.');
    if (i > 0) {
        filename = filename.substring(0, i);
    }

    //our yaml parser seems to be too tolerant. Each yaml suite must end with \n, otherwise clients tests might break.
    try (FileChannel channel = FileChannel.open(file, StandardOpenOption.READ)) {
        ByteBuffer bb = ByteBuffer.wrap(new byte[1]);
        channel.read(bb, channel.size() - 1);
        if (bb.get(0) != 10) {
            throw new IOException("test suite [" + api + "/" + filename + "] doesn't end with line feed (\\n)");
        }
    }

    try (XContentParser parser = YamlXContent.yamlXContent.createParser(ExecutableSection.XCONTENT_REGISTRY,
            Files.newInputStream(file))) {
        return parse(api, filename, parser);
    } catch(Exception e) {
        throw new IOException("Error parsing " + api + "/" + filename, e);
    }
}
 
Example 39
Project: authlib-injector   File: ClassTransformer.java   View source code 5 votes vote down vote up
private void saveClassFile(String className, byte[] classBuffer) {
	try {
		Files.write(Paths.get(className + "_dump.class"), classBuffer, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
	} catch (IOException e) {
		log("unable to dump class {0}: {1}", className, e);
		e.printStackTrace();
	}
}
 
Example 40
Project: elasticsearch_my   File: TruncateTranslogCommand.java   View source code 5 votes vote down vote up
/**
 * Write a translog containing the given translog UUID to the given location. Returns the number of bytes written.
 */
public static int writeEmptyTranslog(Path filename, String translogUUID) throws IOException {
    final BytesRef translogRef = new BytesRef(translogUUID);
    try (FileChannel fc = FileChannel.open(filename, StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE_NEW);
            OutputStreamDataOutput out = new OutputStreamDataOutput(Channels.newOutputStream(fc))) {
        TranslogWriter.writeHeader(out, translogRef);
        fc.force(true);
    }
    return TranslogWriter.getHeaderLength(translogRef.length);
}