List of usage examples for java.nio.file StandardOpenOption READ
StandardOpenOption READ
To view the source code for java.nio.file StandardOpenOption READ.
Click Source Link
From source file:io.undertow.server.handlers.SenderTestCase.java
@BeforeClass public static void setup() { HttpHandler lotsOfSendsHandler = new HttpHandler() { @Override//from w ww . j a v a 2 s .co m public void handleRequest(final HttpServerExchange exchange) throws Exception { boolean blocking = exchange.getQueryParameters().get("blocking").getFirst().equals("true"); if (blocking) { if (exchange.isInIoThread()) { exchange.startBlocking(); exchange.dispatch(this); return; } } final Sender sender = exchange.getResponseSender(); class SendClass implements Runnable, IoCallback { int sent = 0; @Override public void run() { sent++; sender.send("a", this); } @Override public void onComplete(final HttpServerExchange exchange, final Sender sender) { if (sent++ == SENDS) { sender.close(); return; } sender.send("a", this); } @Override public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) { exception.printStackTrace(); exchange.endExchange(); } } new SendClass().run(); } }; HttpHandler lotsOfTransferHandler = new HttpHandler() { @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { boolean blocking = exchange.getQueryParameters().get("blocking").getFirst().equals("true"); if (blocking) { if (exchange.isInIoThread()) { exchange.startBlocking(); exchange.dispatch(this); return; } } URI uri = SenderTestCase.class.getResource(SenderTestCase.class.getSimpleName() + ".class").toURI(); Path file = Paths.get(uri); final FileChannel channel = FileChannel.open(file, StandardOpenOption.READ); exchange.setResponseContentLength(channel.size() * TXS); final Sender sender = exchange.getResponseSender(); class SendClass implements Runnable, IoCallback { int sent = 0; @Override public void run() { sent++; try { channel.position(0); } catch (IOException e) { } sender.transferFrom(channel, this); } @Override public void onComplete(final HttpServerExchange exchange, final Sender sender) { if (sent++ == TXS) { sender.close(); return; } try { channel.position(0); } catch (IOException e) { } sender.transferFrom(channel, this); } @Override public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) { exception.printStackTrace(); exchange.endExchange(); } } new SendClass().run(); } }; final HttpHandler fixedLengthSender = new HttpHandler() { @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { exchange.getResponseSender().send(HELLO_WORLD); } }; PathHandler handler = new PathHandler().addPrefixPath("/lots", lotsOfSendsHandler) .addPrefixPath("/fixed", fixedLengthSender).addPrefixPath("/transfer", lotsOfTransferHandler); DefaultServer.setRootHandler(handler); }
From source file:org.cryptomator.ui.UnlockController.java
@FXML private void didClickUnlockButton(ActionEvent event) { setControlsDisabled(true);//from w w w . j av a 2 s.co m final String masterKeyFileName = usernameBox.getValue() + Aes256Cryptor.MASTERKEY_FILE_EXT; final Path masterKeyPath = directory.getPath().resolve(masterKeyFileName); final CharSequence password = passwordField.getCharacters(); InputStream masterKeyInputStream = null; try { progressIndicator.setVisible(true); masterKeyInputStream = Files.newInputStream(masterKeyPath, StandardOpenOption.READ); directory.setVerifyFileIntegrity(checkIntegrity.isSelected()); directory.getCryptor().decryptMasterKey(masterKeyInputStream, password); if (!directory.startServer()) { messageLabel.setText(rb.getString("unlock.messageLabel.startServerFailed")); directory.getCryptor().swipeSensitiveData(); return; } directory.setUnlocked(true); final Future<Boolean> futureMount = FXThreads.runOnBackgroundThread(directory::mount); FXThreads.runOnMainThreadWhenFinished(futureMount, this::didUnlockAndMount); FXThreads.runOnMainThreadWhenFinished(futureMount, (result) -> { setControlsDisabled(false); }); } catch (DecryptFailedException | IOException ex) { setControlsDisabled(false); progressIndicator.setVisible(false); messageLabel.setText(rb.getString("unlock.errorMessage.decryptionFailed")); LOG.error("Decryption failed for technical reasons.", ex); } catch (WrongPasswordException e) { setControlsDisabled(false); progressIndicator.setVisible(false); messageLabel.setText(rb.getString("unlock.errorMessage.wrongPassword")); Platform.runLater(passwordField::requestFocus); } catch (UnsupportedKeyLengthException ex) { setControlsDisabled(false); progressIndicator.setVisible(false); messageLabel.setText(rb.getString("unlock.errorMessage.unsupportedKeyLengthInstallJCE")); LOG.warn("Unsupported Key-Length. Please install Oracle Java Cryptography Extension (JCE).", ex); } finally { passwordField.swipe(); IOUtils.closeQuietly(masterKeyInputStream); } }
From source file:org.opencb.opencga.server.rest.utils.FileRanges.java
@GET @Path("/ranges/{file}") @ApiOperation(value = "Fetchs alignment files using HTTP Ranges protocol") @Produces("text/plain") public Response getRanges(@Context HttpHeaders headers, @ApiParam(value = "File id, name or path") @PathParam("file") String fileIdStr, @ApiParam(value = "Study [[user@]project:]study where study and project can be either the id or alias") @QueryParam("study") String studyStr) { DataInputStream stream = null; try {/*from w w w .j a v a2s . c o m*/ AbstractManager.MyResourceId resource = catalogManager.getFileManager().getId(fileIdStr, studyStr, sessionId); catalogManager.getAuthorizationManager().checkFilePermission(resource.getResourceId(), resource.getUser(), FileAclEntry.FilePermissions.DOWNLOAD); QueryResult<File> queryResult = catalogManager.getFile(resource.getResourceId(), this.queryOptions, sessionId); File file = queryResult.getResult().get(0); List<String> rangeList = headers.getRequestHeader("range"); if (rangeList != null) { long from; long to; String[] acceptedRanges = rangeList.get(0).split("=")[1].split("-"); from = Long.parseLong(acceptedRanges[0]); to = Long.parseLong(acceptedRanges[1]); int length = (int) (to - from) + 1; ByteBuffer buf = ByteBuffer.allocate(length); logger.debug("from: {} , to: {}, length:{}", from, to, length); StopWatch t = StopWatch.createStarted(); java.nio.file.Path filePath = Paths.get(file.getUri()); try (FileChannel fc = (FileChannel.open(filePath, StandardOpenOption.READ))) { fc.position(from); fc.read(buf); } t.stop(); logger.debug("Skip {}B and read {}B in {}s", from, length, t.getTime(TimeUnit.MILLISECONDS) / 1000.0); return Response.ok(buf.array(), MediaType.APPLICATION_OCTET_STREAM_TYPE) .header("Accept-Ranges", "bytes").header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Headers", "x-requested-with, content-type, range") .header("Access-Control-Allow-Credentials", "true") .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") .header("Content-Range", "bytes " + from + "-" + to + "/" + file.getSize()) .header("Content-length", to - from + 1).status(Response.Status.PARTIAL_CONTENT).build(); } else { stream = catalogManager.downloadFile(resource.getResourceId(), sessionId); return createOkResponse(stream, MediaType.APPLICATION_OCTET_STREAM_TYPE, file.getName()); } } catch (Exception e) { if (stream != null) { try { stream.close(); } catch (IOException ignore) { } } return createErrorResponse(e); } }
From source file:com.github.technosf.posterer.models.KeyStoreBean.java
/** * Instantiates a {@code KeyStoreBean} wrapping the given keystore * <p>//from w w w . j a v a2 s . c o m * Loads the Key Store file into a {@code KeyStore} and checks the password. If the Key Store * can be accessed successfully, validation is successful.. * * @param file * the KeyStore file * @param password * the Key Store password * @throws KeyStoreBeanException * Thrown when a {@code KeyStoreBean} cannot be created. */ public KeyStoreBean(final File keyStoreFile, final String keyStorePassword) throws KeyStoreBeanException { file = keyStoreFile; password = keyStorePassword; InputStream inputStream = null; /* * Check file existence */ if (keyStoreFile == null || !keyStoreFile.exists() || !keyStoreFile.canRead()) // Key Store File cannot be read { throw new KeyStoreBeanException("Cannot read Key Store file"); } try // to get the file input stream { inputStream = Files.newInputStream(keyStoreFile.toPath(), StandardOpenOption.READ); } catch (IOException e) { throw new KeyStoreBeanException("Error reading Key Store file", e); } // Get the file name and extension fileName = FilenameUtils.getName(keyStoreFile.getName()); String fileExtension = FilenameUtils.getExtension(keyStoreFile.getName().toLowerCase()); /* * Identify keystore type, and create an instance */ try { switch (fileExtension) { case "p12": keyStore = KeyStore.getInstance("PKCS12"); break; case "jks": keyStore = KeyStore.getInstance("JKS"); break; default: throw new KeyStoreBeanException(String.format("Unknown keystore extention: [%1$s]", fileExtension)); } } catch (KeyStoreException e) { throw new KeyStoreBeanException("Cannot get keystore instance"); } /* * Load the keystore data into the keystore instance */ try { keyStore.load(inputStream, password.toCharArray()); } catch (NoSuchAlgorithmException | CertificateException | IOException e) { throw new KeyStoreBeanException("Cannot load the KeyStore", e); } /* * Key store loaded, so config the bean */ try { type = keyStore.getType(); size = keyStore.size(); Enumeration<String> aliasIterator = keyStore.aliases(); while (aliasIterator.hasMoreElements()) { String alias = aliasIterator.nextElement(); certificates.put(alias, keyStore.getCertificate(alias)); } } catch (KeyStoreException e) { throw new KeyStoreBeanException("Cannot process the KeyStore", e); } }
From source file:com.github.technosf.posterer.models.impl.KeyStoreBean.java
/** * Instantiates a {@code KeyStoreBean} wrapping the given keystore * <p>//from ww w.ja va 2 s . c o m * Loads the Key Store file into a {@code KeyStore} and checks the password. * If the Key Store * can be accessed successfully, validation is successful.. * * @param file * the KeyStore file * @param password * the Key Store password * @throws KeyStoreBeanException * Thrown when a {@code KeyStoreBean} cannot be created. */ @SuppressWarnings("null") public KeyStoreBean(final File keyStoreFile, final String keyStorePassword) throws KeyStoreBeanException { file = keyStoreFile; password = keyStorePassword; InputStream inputStream = null; /* * Check file existence */ if (keyStoreFile == null || !keyStoreFile.exists() || !keyStoreFile.canRead()) // Key Store File cannot be read { throw new KeyStoreBeanException("Cannot read Key Store file"); } try // to get the file input stream { inputStream = Files.newInputStream(keyStoreFile.toPath(), StandardOpenOption.READ); } catch (IOException e) { throw new KeyStoreBeanException("Error reading Key Store file", e); } // Get the file name and extension fileName = FilenameUtils.getName(keyStoreFile.getName()); String fileExtension = FilenameUtils.getExtension(keyStoreFile.getName().toLowerCase()); /* * Identify keystore type, and create an instance */ try { switch (fileExtension) { case "p12": keyStore = KeyStore.getInstance("PKCS12"); break; case "jks": keyStore = KeyStore.getInstance("JKS"); break; default: throw new KeyStoreBeanException(String.format("Unknown keystore extention: [%1$s]", fileExtension)); } } catch (KeyStoreException e) { throw new KeyStoreBeanException("Cannot get keystore instance"); } /* * Load the keystore data into the keystore instance */ try { keyStore.load(inputStream, password.toCharArray()); valid = true; } catch (NoSuchAlgorithmException | CertificateException | IOException e) { throw new KeyStoreBeanException("Cannot load the KeyStore", e); } /* * Key store loaded, so config the bean */ try { type = keyStore.getType(); size = keyStore.size(); Enumeration<String> aliasIterator = keyStore.aliases(); while (aliasIterator.hasMoreElements()) { String alias = aliasIterator.nextElement(); certificates.put(alias, keyStore.getCertificate(alias)); } } catch (KeyStoreException e) { throw new KeyStoreBeanException("Cannot process the KeyStore", e); } }
From source file:org.apache.marmotta.platform.ldp.services.LdpBinaryStoreServiceImpl.java
@Override public InputStream read(String resource) throws IOException { try {//ww w.j a v a2 s .com Path file = getFile(resource); if (Files.exists(file)) { return Files.newInputStream(file, StandardOpenOption.READ); } else { log.warn("{} not found in binary storage ({})", resource, file); return null; } } catch (URISyntaxException e) { log.error("Error reading resource {}: {}", resource, e.getMessage()); return null; } }
From source file:com.arpnetworking.tsdcore.tailer.StatefulTailer.java
private void fileLoop() throws IOException, InterruptedException { SeekableByteChannel reader = null; InitialPosition nextInitialPosition = _initialPosition; try {//from w ww . j a v a 2 s . co 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.webdav.jackrabbit.resources.EncryptedFile.java
@Override protected void determineProperties() { final Path path = ResourcePathUtils.getPhysicalPath(this); if (Files.exists(path)) { SeekableByteChannel channel = null; try {/*from w w w. java2 s.c o m*/ channel = Files.newByteChannel(path, StandardOpenOption.READ); final Long contentLength = cryptor.decryptedContentLength(channel); properties.add(new DefaultDavProperty<Long>(DavPropertyName.GETCONTENTLENGTH, contentLength)); final BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); properties.add(new DefaultDavProperty<String>(DavPropertyName.CREATIONDATE, FileTimeUtils.toRfc1123String(attrs.creationTime()))); properties.add(new DefaultDavProperty<String>(DavPropertyName.GETLASTMODIFIED, FileTimeUtils.toRfc1123String(attrs.lastModifiedTime()))); properties.add(new HttpHeaderProperty(HttpHeader.ACCEPT_RANGES.asString(), HttpHeaderValue.BYTES.asString())); } catch (IOException e) { LOG.error("Error determining metadata " + path.toString(), e); throw new IORuntimeException(e); } finally { IOUtils.closeQuietly(channel); } } }
From source file:burstcoin.jminer.core.reader.task.ReaderLoadDriveTask.java
private boolean load(PlotFile plotFile) { try (SeekableByteChannel sbc = Files.newByteChannel(plotFile.getFilePath(), EnumSet.of(StandardOpenOption.READ))) { long currentScoopPosition = scoopNumber * plotFile.getStaggeramt() * MiningPlot.SCOOP_SIZE; long partSize = plotFile.getStaggeramt() / plotFile.getNumberOfParts(); ByteBuffer partBuffer = ByteBuffer.allocate((int) (partSize * MiningPlot.SCOOP_SIZE)); // optimized plotFiles only have one chunk! for (int chunkNumber = 0; chunkNumber < plotFile.getNumberOfChunks(); chunkNumber++) { long currentChunkPosition = chunkNumber * plotFile.getStaggeramt() * MiningPlot.PLOT_SIZE; sbc.position(currentScoopPosition + currentChunkPosition); for (int partNumber = 0; partNumber < plotFile.getNumberOfParts(); partNumber++) { sbc.read(partBuffer);// ww w .j ava 2s .c o m if (Reader.blockNumber != blockNumber) { LOG.trace("loadDriveThread stopped!"); partBuffer.clear(); sbc.close(); return true; } else { long chunkPartStartNonce = plotFile.getStartnonce() + (chunkNumber * plotFile.getStaggeramt()) + (partNumber * partSize); final byte[] scoops = partBuffer.array(); publisher.publishEvent(new ReaderLoadedPartEvent(blockNumber, scoops, chunkPartStartNonce)); } partBuffer.clear(); } } sbc.close(); } catch (NoSuchFileException exception) { LOG.error("File not found ... please restart to rescan plot-files, maybe set rescan to 'true': " + exception.getMessage()); } catch (ClosedByInterruptException e) { // we reach this, if we do not wait for task on shutdown - ByteChannel closed by thread interruption LOG.trace("reader stopped cause of new block ..."); } catch (IOException e) { LOG.error("IOException: " + e.getMessage()); } return false; }
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. * /*from w w w .ja va2 s . co m*/ * @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); }