List of usage examples for java.nio.channels SeekableByteChannel position
SeekableByteChannel position(long newPosition) throws IOException;
From source file:com.spectralogic.ds3client.helpers.RequestMatchers.java
private static String channelToString(final SeekableByteChannel channel) { try {//from w ww. ja v a 2 s. c o m channel.position(0); return IOUtils.toString(Channels.newReader(channel, "UTF-8")); } catch (final IOException e) { throw new RuntimeException(e); } }
From source file:com.spectralogic.ds3client.helpers.channels.WindowedSeekableByteChannel_Test.java
private static SeekableByteChannel stringToChannel(final String string) throws IOException { final SeekableByteChannel channel = new ByteArraySeekableByteChannel(); writeToChannel(string, channel);//w ww . j a v a 2 s .c o m channel.position(0); return channel; }
From source file:io.neba.core.logviewer.Tail.java
@Override public void run() { SeekableByteChannel channel = null; try {// w w w .java 2s . co m channel = newByteChannel(this.file.toPath(), READ); long availableInByte = this.file.length(); long startingFromInByte = max(availableInByte - this.bytesToTail, 0); channel.position(startingFromInByte); long position = startingFromInByte; long totalBytesRead = 0L; // Read up to this amount of data from the file at once. ByteBuffer readBuffer = allocate(4096); while (!this.stopped) { // The file might be temporarily gone during rotation. Wait, then decide // whether the file is considered gone permanently or whether a rotation has occurred. if (!this.file.exists()) { sleep(AWAIT_FILE_ROTATION_MILLIS); } if (!this.file.exists()) { this.remoteEndpoint.sendString("file not found"); return; } if (position > this.file.length()) { this.remoteEndpoint.sendString("file rotated"); position = 0; closeQuietly(channel); channel = newByteChannel(this.file.toPath(), READ); } int read = channel.read(readBuffer); if (read == -1) { if (mode == TAIL) { // EOF, we are done. return; } // If we are in follow mode, reaching the end of the file might signal a file rotation. Sleep and re-try. sleep(TAIL_CHECK_INTERVAL_MILLIS); continue; } totalBytesRead += read; position = channel.position(); readBuffer.flip(); this.remoteEndpoint.sendBytes(readBuffer); readBuffer.clear(); if (mode == TAIL && totalBytesRead >= this.bytesToTail) { return; } } } catch (IOException e) { this.logger.error("Unable to tail " + this.file.getAbsolutePath() + ".", e); } catch (InterruptedException e) { if (!this.stopped) { this.logger.error("Stopped tailing " + this.file.getAbsolutePath() + ", got interrupted.", e); } } finally { closeQuietly(channel); } }
From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java
@Override public Long decryptedContentLength(SeekableByteChannel encryptedFile) throws IOException { // skip 128bit IV + 256 bit MAC: encryptedFile.position(48);/*from ww w. ja v a 2s .c om*/ // read encrypted value: final ByteBuffer encryptedFileSizeBuffer = ByteBuffer.allocate(AES_BLOCK_LENGTH); final int numFileSizeBytesRead = encryptedFile.read(encryptedFileSizeBuffer); // return "unknown" value, if EOF if (numFileSizeBytesRead != encryptedFileSizeBuffer.capacity()) { return null; } // decrypt size: try { final Cipher sizeCipher = aesEcbCipher(primaryMasterKey, Cipher.DECRYPT_MODE); final byte[] decryptedFileSize = sizeCipher.doFinal(encryptedFileSizeBuffer.array()); final ByteBuffer fileSizeBuffer = ByteBuffer.wrap(decryptedFileSize); return fileSizeBuffer.getLong(); } catch (IllegalBlockSizeException | BadPaddingException e) { throw new IllegalStateException(e); } }
From source file:com.arpnetworking.metrics.common.tailer.StatefulTailer.java
private void resume(final SeekableByteChannel reader, final InitialPosition initialPosition) throws IOException { // Attempt to resume from checkpoint long position = initialPosition.get(reader); // Override position with last known position from store _hash = computeHash(reader, REQUIRED_BYTES_FOR_HASH); if (_hash.isPresent()) { final Optional<Long> storedPosition = _positionStore.getPosition(_hash.get()); if (storedPosition.isPresent()) { // Optionally limit the size of the backlog to process final long fileSize = reader.size(); if (_maximumOffsetOnResume.isPresent() && fileSize - storedPosition.get() > _maximumOffsetOnResume.get()) { position = fileSize - _maximumOffsetOnResume.get(); // TODO(vkoskela): Discard the current potentially partial line [AINT-584] } else { position = storedPosition.get(); }/*from w w w .j a v a2 s .co m*/ } } LOGGER.info().setMessage("Starting tailer").addData("file", _file).addData("position", position).log(); reader.position(position); }
From source file:com.arpnetworking.tsdcore.tailer.StatefulTailer.java
private void fileLoop() throws IOException, InterruptedException { SeekableByteChannel reader = null; InitialPosition nextInitialPosition = _initialPosition; try {/*from w w w . j a va2 s . c o m*/ while (isRunning()) { // Attempt to open the file try { reader = Files.newByteChannel(_file.toPath(), StandardOpenOption.READ); LOGGER.trace(String.format("Opened file; file=%s", _file)); } catch (final NoSuchFileException e) { _listener.fileNotFound(); _trigger.waitOnTrigger(); } if (reader != null) { // Attempt to resume from checkpoint long position = nextInitialPosition.get(reader); // Any subsequent file opens we should start at the beginning nextInitialPosition = InitialPosition.START; _hash = computeHash(reader, REQUIRED_BYTES_FOR_HASH); if (_hash.isPresent()) { position = _positionStore.getPosition(_hash.get()).or(position).longValue(); } LOGGER.trace( String.format("Starting tail; file=%s, position=%d", _file, Long.valueOf(position))); reader.position(position); // Read the file readLoop(reader); // Reset per file state IOUtils.closeQuietly(reader); reader = null; _hash = Optional.absent(); } } } finally { IOUtils.closeQuietly(reader); reader = null; _hash = Optional.absent(); } }
From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java
@Override public boolean authenticateContent(SeekableByteChannel encryptedFile) throws IOException { // init mac:/*from w w w .j a va 2 s . co m*/ final Mac calculatedMac = this.hmacSha256(hMacMasterKey); // read stored mac: encryptedFile.position(16); final ByteBuffer storedMac = ByteBuffer.allocate(calculatedMac.getMacLength()); final int numMacBytesRead = encryptedFile.read(storedMac); // check validity of header: if (numMacBytesRead != calculatedMac.getMacLength()) { throw new IOException("Failed to read file header."); } // read all encrypted data and calculate mac: encryptedFile.position(64); final InputStream in = new SeekableByteChannelInputStream(encryptedFile); final InputStream macIn = new MacInputStream(in, calculatedMac); IOUtils.copyLarge(macIn, new NullOutputStream()); // compare (in constant time): return MessageDigest.isEqual(storedMac.array(), calculatedMac.doFinal()); }
From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java
@Override public Long decryptedFile(SeekableByteChannel encryptedFile, OutputStream plaintextFile) throws IOException { // read iv://from w w w . j ava2 s . c o m encryptedFile.position(0); final ByteBuffer countingIv = ByteBuffer.allocate(AES_BLOCK_LENGTH); final int numIvBytesRead = encryptedFile.read(countingIv); // read file size: final Long fileSize = decryptedContentLength(encryptedFile); // check validity of header: if (numIvBytesRead != AES_BLOCK_LENGTH || fileSize == null) { throw new IOException("Failed to read file header."); } // go to begin of content: encryptedFile.position(64); // generate cipher: final Cipher cipher = this.aesCtrCipher(primaryMasterKey, countingIv.array(), Cipher.DECRYPT_MODE); // read content final InputStream in = new SeekableByteChannelInputStream(encryptedFile); final InputStream cipheredIn = new CipherInputStream(in, cipher); return IOUtils.copyLarge(cipheredIn, plaintextFile, 0, fileSize); }
From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java
@Override public Long decryptRange(SeekableByteChannel encryptedFile, OutputStream plaintextFile, long pos, long length) throws IOException { // read iv:/* w w w .j a v a2 s. com*/ encryptedFile.position(0); final ByteBuffer countingIv = ByteBuffer.allocate(AES_BLOCK_LENGTH); final int numIvBytesRead = encryptedFile.read(countingIv); // check validity of header: if (numIvBytesRead != AES_BLOCK_LENGTH) { throw new IOException("Failed to read file header."); } // seek relevant position and update iv: long firstRelevantBlock = pos / AES_BLOCK_LENGTH; // cut of fraction! long beginOfFirstRelevantBlock = firstRelevantBlock * AES_BLOCK_LENGTH; long offsetInsideFirstRelevantBlock = pos - beginOfFirstRelevantBlock; countingIv.putLong(AES_BLOCK_LENGTH - Long.BYTES, firstRelevantBlock); // fast forward stream: encryptedFile.position(64 + beginOfFirstRelevantBlock); // generate cipher: final Cipher cipher = this.aesCtrCipher(primaryMasterKey, countingIv.array(), Cipher.DECRYPT_MODE); // read content final InputStream in = new SeekableByteChannelInputStream(encryptedFile); final InputStream cipheredIn = new CipherInputStream(in, cipher); return IOUtils.copyLarge(cipheredIn, plaintextFile, offsetInsideFirstRelevantBlock, length); }