List of usage examples for java.nio.channels Channels newInputStream
public static InputStream newInputStream(AsynchronousByteChannel ch)
From source file:Main.java
public static void main(String[] argv) throws Exception { // Create a read/writeable file channel File file = new File("filename"); FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); InputStream is = Channels.newInputStream(channel); // Close the channel is.close();//from w w w. jav a 2 s . com }
From source file:Test.java
private static void serverStart() { try {/*from ww w . j a v a2 s . c o m*/ InetSocketAddress hostAddress = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 2583); AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open() .bind(hostAddress); Future<AsynchronousSocketChannel> serverFuture = serverSocketChannel.accept(); final AsynchronousSocketChannel clientSocket = serverFuture.get(); if ((clientSocket != null) && (clientSocket.isOpen())) { InputStream connectionInputStream = Channels.newInputStream(clientSocket); ObjectInputStream ois = null; ois = new ObjectInputStream(connectionInputStream); while (true) { Object object = ois.readObject(); if (object.equals("EOF")) { clientSocket.close(); break; } System.out.println("Received :" + object); } ois.close(); connectionInputStream.close(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static Document loadDocument(ReadableByteChannel in) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document doc;//w w w . j a v a 2 s .co m DocumentBuilder db; db = dbf.newDocumentBuilder(); doc = db.parse(Channels.newInputStream(in)); return doc; }
From source file:cltestgrid.GetBlob.java
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String userAgent = req.getHeader("User-Agent"); if (userAgent != null && userAgent.contains("Baiduspider")) { resp.setStatus(SC_MOVED_PERMANENTLY); resp.setHeader("Location", "http://www.baidu.com/search/spider.html"); resp.setHeader("X-READ-ME", "Please honor robots.txt and don't waste our resources. http://cl-test-grid.appspot.com/robots.txt"); return;/*from ww w. j a v a 2 s .co m*/ } final String key = req.getParameter("key"); String filename = "/gs/cl-test-grid-logs/" + key; AppEngineFile file = new AppEngineFile(filename); FileReadChannel readChannel = null; InputStream inputStream = null; try { final boolean lock = false; readChannel = FileServiceFactory.getFileService().openReadChannel(file, lock); inputStream = Channels.newInputStream(readChannel); resp.setContentType("text/plain"); // The log files are gzipped, but we can't serve gzipped content, // because GAE gzips servlet output itlself and so logs would end-up gzipped twice. // Therefore we need to ungzip the log. InputStream ungzipper = new GZIPInputStream(new BufferedInputStream(inputStream, 100 * 1024)); IOUtils.copy(ungzipper, resp.getOutputStream()); resp.getOutputStream().flush(); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(readChannel); } }
From source file:cltestgrid.GetBlob2.java
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String userAgent = req.getHeader("User-Agent"); if (userAgent != null && userAgent.contains("Baiduspider")) { resp.setStatus(SC_MOVED_PERMANENTLY); resp.setHeader("Location", "http://www.baidu.com/search/spider.html"); resp.setHeader("X-READ-ME", "Please honor robots.txt and don't waste our resources. http://cl-test-grid.appspot.com/robots.txt"); return;//from w ww. j a v a2 s.c om } final String key = req.getParameter("key"); GcsFilename filename = new GcsFilename("cl-test-grid-logs", key); GcsInputChannel readChannel = null; InputStream inputStream = null; try { final boolean lock = false; //readChannel = FileServiceFactory.getFileService().openReadChannel(file, lock); readChannel = GcsServiceFactory.createGcsService().openReadChannel(filename, 0); inputStream = Channels.newInputStream(readChannel); resp.setContentType("text/plain"); // The log files are gzipped, but the Cloud Storage Client Library ungzips them automatically. // After we return this data, GAE gzips our output in case client accepts 'gzip' contect encoding. IOUtils.copy(new BufferedInputStream(inputStream, 100 * 1024), resp.getOutputStream()); resp.getOutputStream().flush(); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(readChannel); } }
From source file:org.swiftexplorer.swift.instructions.FastSegmentationPlanFile.java
@Override protected InputStream createSegment() throws IOException { InputStream res = new BoundedInputStream( Channels.newInputStream( this.randomAccessFile.getChannel().position(currentSegment * segmentationSize)), segmentationSize);/* w w w . j a v a2 s .c o m*/ ((BoundedInputStream) res).setPropagateClose(false); return res; }
From source file:org.hawkular.metrics.api.undertow.MetricsHandlers.java
public void setup(RoutingHandler commonHandler) { commonHandler.add(Methods.POST, "/{tenantId}/metrics/numeric", new AsyncHttpHandler() { public void handleRequestAsync(HttpServerExchange exchange) throws Exception { @SuppressWarnings("unchecked") Map<String, Object> body = mapper.readValue(Channels.newInputStream(exchange.getRequestChannel()), Map.class); Map<String, Deque<String>> queryParams = exchange.getQueryParameters(); String tenantId = queryParams.get("tenantId").getFirst(); String name = body.get("name").toString(); Integer dataRetention = Integer.parseInt(body.get("dataRetention").toString()); NumericMetric metric = new NumericMetric(tenantId, new MetricId(name), null, dataRetention); ListenableFuture<Void> future = metricsService.createMetric(metric); Futures.addCallback(future, new FutureCallback<Void>() { @Override/*from ww w .j a v a 2s. c o m*/ public void onSuccess(Void result) { exchange.setResponseCode(200); } @Override public void onFailure(Throwable t) { exchange.setResponseCode(501); } }); } }); commonHandler.add(Methods.POST, "/{tenantId}/metrics/numeric/data", new AsyncHttpHandler() { public void handleRequestAsync(HttpServerExchange exchange) throws Exception { List<NumericMetric> metrics = mapper.readValue( Channels.newInputStream(exchange.getRequestChannel()), new TypeReference<List<NumericMetric>>() { }); Map<String, Deque<String>> queryParams = exchange.getQueryParameters(); String tenantId = queryParams.get("tenantId").getFirst(); if (metrics == null || metrics.size() == 0) { exchange.setResponseCode(200); return; } for (NumericMetric metric : metrics) { metric.setTenantId(tenantId); } ListenableFuture<Void> future = metricsService.addNumericData(metrics); Futures.addCallback(future, new FutureCallback<Void>() { @Override public void onSuccess(Void result) { exchange.setResponseCode(200); } @Override public void onFailure(Throwable t) { exchange.setResponseCode(501); } }); } }); }
From source file:org.cryptomator.filesystem.crypto.Masterkeys.java
private static void readMasterKey(File file, Cryptor cryptor, CharSequence passphrase) throws UncheckedIOException, InvalidPassphraseException { try ( // ReadableByteChannel channel = file.openReadable(); // InputStream in = Channels.newInputStream(channel)) { final byte[] fileContents = IOUtils.toByteArray(in); cryptor.readKeysFromMasterkeyFile(fileContents, passphrase); } catch (IOException e) { throw new UncheckedIOException(e); }/*from w ww.j av a2 s. co m*/ }
From source file:org.cryptomator.frontend.webdav.jackrabbitservlet.DavFileWithRange.java
@Override public void spool(OutputContext outputContext) throws IOException { outputContext.setModificationTime(node.lastModified().toEpochMilli()); if (!outputContext.hasStream()) { return;/*from www . j a v a 2 s.c om*/ } final long contentLength = node.size(); final Pair<Long, Long> range = getEffectiveRange(contentLength); if (range.getLeft() < 0 || range.getLeft() > range.getRight() || range.getRight() > contentLength) { outputContext.setProperty(HttpHeader.CONTENT_RANGE.asString(), "bytes */" + contentLength); throw new UncheckedDavException(DavServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, "Valid Range would be in [0, " + contentLength + "]"); } final Long rangeLength = range.getRight() - range.getLeft() + 1; outputContext.setContentLength(rangeLength); outputContext.setProperty(HttpHeader.CONTENT_RANGE.asString(), contentRangeResponseHeader(range.getLeft(), range.getRight(), contentLength)); outputContext.setContentType(CONTENT_TYPE_VALUE); outputContext.setProperty(CONTENT_DISPOSITION_HEADER, CONTENT_DISPOSITION_VALUE); outputContext.setProperty(X_CONTENT_TYPE_OPTIONS_HEADER, X_CONTENT_TYPE_OPTIONS_VALUE); try (ReadableFile src = node.openReadable(); OutputStream out = outputContext.getOutputStream()) { src.position(range.getLeft()); InputStream limitedIn = ByteStreams.limit(Channels.newInputStream(src), rangeLength); ByteStreams.copy(limitedIn, out); } }
From source file:fr.gael.dhus.util.stream.ProductDownloadStreamFactory.java
@Override public synchronized InputStream generateInputStream(ProductInfo productInfo, Source source, SynchronizerRules rules, long skip) { // generate HTTP client int timeout = rules.getTimeout().intValue(); InterruptibleHttpClient client = new InterruptibleHttpClient( new BasicAuthHttpClientProducer(source.getUsername(), source.getPassword(), timeout)); // generate download url String url = productInfo.getDownloadUrl(source.getUrl()); // generate stream boolean canResume; String etag;/*from w ww .j a v a 2 s . co m*/ HttpResponse headers; Thread downloadThread = null; try { headers = client.interruptibleHead(url); // check availability of content if (headers.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { return null; } // retrieve content information if (headers.containsHeader(HTTP_HEADER_ETAG)) { etag = headers.getFirstHeader(HTTP_HEADER_ETAG).getValue(); canResume = headers.containsHeader(HTTP_HEADER_ACCEPT_RANGE); } else { etag = null; canResume = false; } Pipe pipe = Pipe.open(); DownloadTask downloadTask = new DownloadTask(pipe, client, url, etag, skip, productInfo.getSize(), rules.getAttempts(), canResume); downloadThread = new Thread(downloadTask, THREAD_NAME); downloadThread.start(); return Channels.newInputStream(pipe.source()); } catch (InterruptedException | IOException e) { if (downloadThread != null) { downloadThread.interrupt(); } return null; } }