Example usage for java.nio.channels FileChannel open

List of usage examples for java.nio.channels FileChannel open

Introduction

In this page you can find the example usage for java.nio.channels FileChannel open.

Prototype

public static FileChannel open(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs)
        throws IOException 

Source Link

Document

Opens or creates a file, returning a file channel to access the file.

Usage

From source file:fr.gael.dhus.sync.impl.ODataProductSynchronizer.java

/**
 * Uses the given `http_client` to download `url` into `out_tmp`.
 * Renames `out_tmp` to the value of the filename param of the Content-Disposition header field.
 * Returns a path to the renamed file./*from   ww w .  j  a va2s . com*/
 *
 * @param http_client synchronous interruptible HTTP client.
 * @param out_tmp download destination file on disk (will be created if does not exist).
 * @param url what to download.
 * @return Path to file with its actual name.
 * @throws IOException Anything went wrong (with IO or network, or if the HTTP header field
 *       Content-Disposition is missing).
 * @throws InterruptedException Thread has been interrupted.
 */
private DownloadResult downloadValidateRename(InterruptibleHttpClient http_client, Path out_tmp, String url)
        throws IOException, InterruptedException {
    try (FileChannel output = FileChannel.open(out_tmp, StandardOpenOption.CREATE_NEW,
            StandardOpenOption.WRITE)) {

        HttpResponse response = http_client.interruptibleGet(url, output);

        // If the response's status code is not 200, something wrong happened
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Formatter ff = new Formatter();
            ff.format(
                    "Synchronizer#%d cannot download product at %s,"
                            + " remote dhus returned message '%s' (HTTP%d)",
                    getId(), url, response.getStatusLine().getReasonPhrase(),
                    response.getStatusLine().getStatusCode());
            throw new IOException(ff.out().toString());
        }

        // Gets the filename from the HTTP header field `Content-Disposition'
        Pattern pat = Pattern.compile("filename=\"(.+?)\"", Pattern.CASE_INSENSITIVE);
        String contdis = response.getFirstHeader("Content-Disposition").getValue();
        Matcher m = pat.matcher(contdis);
        if (!m.find()) {
            throw new IOException("Synchronizer#" + getId()
                    + " Missing HTTP header field `Content-Disposition` that determines the filename");
        }
        String filename = m.group(1);
        if (filename == null || filename.isEmpty()) {
            throw new IOException(
                    "Synchronizer#" + getId() + " Invalid filename in HTTP header field `Content-Disposition`");
        }

        // Renames the downloaded file
        output.close();
        Path dest = out_tmp.getParent().resolve(filename);
        Files.move(out_tmp, dest, StandardCopyOption.ATOMIC_MOVE);

        DownloadResult res = new DownloadResult(dest, response.getEntity().getContentType().getValue(),
                response.getEntity().getContentLength());

        return res;
    } finally {
        if (Files.exists(out_tmp)) {
            Files.delete(out_tmp);
        }
    }
}

From source file:io.druid.segment.realtime.appenderator.AppenderatorImpl.java

private void lockBasePersistDirectory() {
    if (basePersistDirLock == null) {
        try {/*from w w  w  .  ja va 2  s .c om*/
            basePersistDirLockChannel = FileChannel.open(computeLockFile().toPath(), StandardOpenOption.CREATE,
                    StandardOpenOption.WRITE);

            basePersistDirLock = basePersistDirLockChannel.tryLock();
            if (basePersistDirLock == null) {
                throw new ISE("Cannot acquire lock on basePersistDir: %s", computeLockFile());
            }
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
}

From source file:edu.wustl.lookingglass.community.CommunityRepository.java

private void lockRepo() throws IOException {
    this.syncLockChannel = FileChannel.open(Paths.get(syncLockPath), StandardOpenOption.WRITE,
            StandardOpenOption.CREATE);
    FileLock lock = this.syncLockChannel.lock(); // gets an exclusive lock
    assert lock.isValid();
    this.syncLockChannel.write(ByteBuffer.wrap(ManagementFactory.getRuntimeMXBean().getName().getBytes()));
}

From source file:com.joyent.manta.client.crypto.AbstractMantaEncryptedObjectInputStreamTest.java

protected void willThrowExceptionWhenCiphertextIsAltered(SupportedCipherDetails cipherDetails,
        Class<? extends ReadBytes> strategy) throws IOException {
    SecretKey key = SecretKeyUtils.generate(cipherDetails);
    EncryptedFile encryptedFile = encryptedFile(key, cipherDetails, this.plaintextSize);

    try (FileChannel fc = (FileChannel.open(encryptedFile.file.toPath(), READ, WRITE))) {
        fc.position(2);//from w ww. j av a2s .co  m
        ByteBuffer buff = ByteBuffer.wrap(new byte[] { 20, 20 });
        fc.write(buff);
    }

    long ciphertextSize = encryptedFile.file.length();

    boolean thrown = false;

    FileInputStream in = new FileInputStream(encryptedFile.file);
    final FileInputStream inSpy = Mockito.spy(in);

    MantaEncryptedObjectInputStream min = createEncryptedObjectInputStream(key, inSpy, ciphertextSize,
            cipherDetails, encryptedFile.cipher.getIV(), true, (long) this.plaintextSize);

    try {
        byte[] actual = new byte[plaintextSize];
        ReadBytesFactory.build(strategy, encryptedFile.file.length()).readBytes(min, actual);
        min.close();
    } catch (MantaClientEncryptionCiphertextAuthenticationException e) {
        thrown = true;
        Mockito.verify(inSpy, Mockito.atLeastOnce()).close();
    }

    Assert.assertTrue(thrown, "Ciphertext authentication exception wasn't thrown");
}

From source file:com.joyent.manta.client.crypto.MantaEncryptedObjectInputStreamTest.java

private void willThrowExceptionWhenCiphertextIsAltered(SupportedCipherDetails cipherDetails,
        ReadBytes readBytes) throws IOException {
    SecretKey key = SecretKeyUtils.generate(cipherDetails);
    EncryptedFile encryptedFile = encryptedFile(key, cipherDetails, this.plaintextSize);

    try (FileChannel fc = (FileChannel.open(encryptedFile.file.toPath(), READ, WRITE))) {
        fc.position(2);/*w  w  w  .  j  a  v a 2s.  c o  m*/
        ByteBuffer buff = ByteBuffer.wrap(new byte[] { 20, 20 });
        fc.write(buff);
    }

    long ciphertextSize = encryptedFile.file.length();

    boolean thrown = false;

    FileInputStream in = new FileInputStream(encryptedFile.file);
    MantaEncryptedObjectInputStream min = createEncryptedObjectInputStream(key, in, ciphertextSize,
            cipherDetails, encryptedFile.cipher.getIV(), true, (long) this.plaintextSize);

    try {
        byte[] actual = new byte[plaintextSize];
        readBytes.readAll(min, actual);
        min.close();
    } catch (MantaClientEncryptionCiphertextAuthenticationException e) {
        thrown = true;
    }

    Assert.assertTrue(thrown, "Ciphertext authentication exception wasn't thrown");
}

From source file:org.cryptomator.cryptofs.CryptoFileSystemImpl.java

void createDirectory(CryptoPath cleartextDir, FileAttribute<?>... attrs) throws IOException {
    CryptoPath cleartextParentDir = cleartextDir.getParent();
    if (cleartextParentDir == null) {
        return;//from w  w w.  ja  va2 s  . c  om
    }
    Path ciphertextParentDir = cryptoPathMapper.getCiphertextDirPath(cleartextParentDir);
    if (!Files.exists(ciphertextParentDir)) {
        throw new NoSuchFileException(cleartextParentDir.toString());
    }
    Path ciphertextFile = cryptoPathMapper.getCiphertextFilePath(cleartextDir, CiphertextFileType.FILE);
    if (Files.exists(ciphertextFile)) {
        throw new FileAlreadyExistsException(cleartextDir.toString());
    }
    Path ciphertextDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextDir, CiphertextFileType.DIRECTORY);
    boolean success = false;
    try {
        Directory ciphertextDir = cryptoPathMapper.getCiphertextDir(cleartextDir);
        try (FileChannel channel = FileChannel.open(ciphertextDirFile,
                EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE), attrs)) {
            channel.write(ByteBuffer.wrap(ciphertextDir.dirId.getBytes(UTF_8)));
        }
        Files.createDirectories(ciphertextDir.path);
        success = true;
    } finally {
        if (!success) {
            Files.delete(ciphertextDirFile);
            dirIdProvider.delete(ciphertextDirFile);
        }
    }
}

From source file:org.cyclop.service.common.FileStorage.java

private FileChannel openForRead(Path histPath) throws IOException {
    File file = histPath.toFile();
    if (!file.exists() || !file.canRead()) {
        LOG.debug("History file not found: " + histPath);
        return null;
    }/*from w  w w .  j a v a  2 s  .  c o m*/
    FileChannel byteChannel = FileChannel.open(histPath, StandardOpenOption.READ, StandardOpenOption.WRITE);
    FileChannel lockChannel = lock(histPath, byteChannel);
    return lockChannel;
}

From source file:org.kalypso.grid.BinaryGeoGrid.java

/**
 * Opens an existing grid for read-only access.<br>
 * Dispose the grid after it is no more needed in order to release the given resource.
 * /*ww  w . j  av a2s. com*/
 * @param writeable
 *          If <code>true</code>, the grid is opened for writing and a {@link IWriteableGeoGrid} is returned.
 */
public static BinaryGeoGrid openGrid(final URL url, final Coordinate origin, final Coordinate offsetX,
        final Coordinate offsetY, final String sourceCRS, final boolean writeable) throws IOException {
    /* Tries to find a file from the given url. */
    File fileFromUrl = ResourceUtilities.findJavaFileFromURL(url);
    File binFile = null;
    if (fileFromUrl == null)
        fileFromUrl = FileUtils.toFile(url);

    if (fileFromUrl == null) {
        /*
         * If url cannot be converted to a file, write its contents to a temporary file which will be deleted after the
         * grid gets disposed.
         */
        fileFromUrl = File.createTempFile("local", ".bin");
        fileFromUrl.deleteOnExit();
        FileUtils.copyURLToFile(url, fileFromUrl);
        binFile = fileFromUrl; // set in order to delete on dispose
    }

    FileChannel channel;
    if (writeable)
        channel = FileChannel.open(fileFromUrl.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ);
    else
        channel = FileChannel.open(fileFromUrl.toPath(), StandardOpenOption.READ);

    return new BinaryGeoGrid(channel, binFile, origin, offsetX, offsetY, sourceCRS);
}

From source file:org.kalypso.kalypsosimulationmodel.core.wind.BinaryGeoGridWrapperForPairsModel.java

/**
 * Opens an existing grid.<br>//from   w  w  w.  j  a v a2 s. com
 * Dispose the grid after it is no more needed in order to release the given resource.
 *
 * @param writeable
 *          If <code>true</code>, the grid is opened for writing and a {@link IWriteableGeoGrid} is returned.
 */
public static BinaryGeoGridWrapperForPairsModel openGrid(final URL url, final Coordinate origin,
        final Coordinate offsetX, final Coordinate offsetY, final String sourceCRS, final boolean writeable)
        throws IOException {
    /* Tries to find a file from the given url. */
    File fileFromUrl = ResourceUtilities.findJavaFileFromURL(url);
    File binFile = null;
    if (fileFromUrl == null)
        fileFromUrl = FileUtils.toFile(url);

    if (fileFromUrl == null) {
        /*
         * If url cannot be converted to a file, write its contents to a temporary file which will be deleted after the
         * grid gets disposed.
         */
        fileFromUrl = File.createTempFile("local", ".bin"); //$NON-NLS-1$ //$NON-NLS-2$
        fileFromUrl.deleteOnExit();
        FileUtils.copyURLToFile(url, fileFromUrl);
        binFile = fileFromUrl; // set in order to delete on dispose
    }

    FileChannel channel;
    if (writeable)
        channel = FileChannel.open(fileFromUrl.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ);
    else
        channel = FileChannel.open(fileFromUrl.toPath(), StandardOpenOption.READ);

    return new BinaryGeoGridWrapperForPairsModel(channel, binFile, origin, offsetX, offsetY, sourceCRS);
}

From source file:org.linagora.linshare.webservice.uploadrequest.impl.FlowUploaderRestServiceImpl.java

@Path("/")
@POST//from  w w  w  .j av a 2 s .co  m
@Consumes("multipart/form-data")
@Override
public Response uploadChunk(@Multipart(CHUNK_NUMBER) long chunkNumber,
        @Multipart(TOTAL_CHUNKS) long totalChunks, @Multipart(CHUNK_SIZE) long chunkSize,
        @Multipart(TOTAL_SIZE) long totalSize, @Multipart(IDENTIFIER) String identifier,
        @Multipart(FILENAME) String filename, @Multipart(RELATIVE_PATH) String relativePath,
        @Multipart(FILE) InputStream file, MultipartBody body,
        @Multipart(REQUEST_URL_UUID) String uploadRequestUrlUuid, @Multipart(PASSWORD) String password)
        throws BusinessException {

    logger.debug("upload chunk number : " + chunkNumber);
    identifier = cleanIdentifier(identifier);
    Validate.isTrue(isValid(chunkNumber, chunkSize, totalSize, identifier, filename));
    try {
        logger.debug("writing chunk number : " + chunkNumber);
        java.nio.file.Path tempFile = getTempFile(identifier);
        FileChannel fc = FileChannel.open(tempFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        byte[] byteArray = IOUtils.toByteArray(file);
        fc.write(ByteBuffer.wrap(byteArray), (chunkNumber - 1) * chunkSize);
        fc.close();
        chunkedFiles.get(identifier).addChunk(chunkNumber);
        if (isUploadFinished(identifier, chunkSize, totalSize)) {
            logger.debug("upload finished ");
            InputStream inputStream = Files.newInputStream(tempFile, StandardOpenOption.READ);
            File tempFile2 = getTempFile(inputStream, "rest-flowuploader", filename);
            try {
                uploadRequestUrlFacade.addUploadRequestEntry(uploadRequestUrlUuid, password, tempFile2,
                        filename);
            } finally {
                deleteTempFile(tempFile2);
            }
            ChunkedFile remove = chunkedFiles.remove(identifier);
            Files.deleteIfExists(remove.getPath());
            return Response.ok("upload success").build();
        } else {
            logger.debug("upload pending ");
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Response.ok("upload success").build();
}