List of usage examples for java.nio.channels Channels newChannel
public static WritableByteChannel newChannel(OutputStream out)
From source file:org.jboss.tools.openshift.reddeer.requirement.OpenShiftCommandLineToolsRequirement.java
private String downloadArchive(String downloadLink) { if (StringUtils.isEmpty(downloadLink)) { throw new OpenShiftToolsException("Cannot download OpenShift binary. No download known\n"); }/*from w w w.j av a2s. c o m*/ String fileName = null; try { URL downloadUrl = new URL(downloadLink); fileName = getFileName(downloadUrl.getPath()); if (new File(fileName).exists()) { return fileName; } try (FileOutputStream fileOutputStream = new FileOutputStream(fileName); ReadableByteChannel readableByteChannel = Channels.newChannel(downloadUrl.openStream())) { LOGGER.info("Downloading OpenShift binary."); fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE); } catch (IOException ex) { throw new OpenShiftToolsException("Cannot download OpenShift binary.\n" + ex.getMessage()); } } catch (MalformedURLException e) { throw new OpenShiftToolsException(NLS.bind("Could not download \"{0}\". Invalid url.", downloadLink)); } return fileName; }
From source file:com.github.matthesrieke.jprox.JProxViaParameterServlet.java
private void copyStream(InputStream content, ServletOutputStream outputStream) throws IOException { ReadableByteChannel ci = Channels.newChannel(content); WritableByteChannel co = Channels.newChannel(outputStream); copyChannel(ci, co);//from w w w .j a v a2 s . c o m }
From source file:net.bobah.mail.Dupes.java
@Override public void run() { final Multimap<HashCode, File> dupes = Multimaps.newListMultimap(new HashMap<HashCode, Collection<File>>(), new Supplier<List<File>>() { @Override/*from w ww .jav a 2 s .co m*/ public List<File> get() { return new LinkedList<File>(); } }); for (final File dir : dirs) { if (!dir.isDirectory()) { log.warn("{} does not exist or is not a directory, ignored", dir); } final Collection<File> files = findFiles(dir, ""); log.info("found {} files in {}, submitting to analyzer", files.size(), dir.getAbsolutePath()); for (final File file : files) { executor.submit(new Runnable() { @Override public void run() { final ExecutionContext cxt = Dupes.this.cxt.get(); ReadableByteChannel ch = null; try { cxt.sw.start(); // map file, take just 1 meg of data to cxt.hash and calc the function // final HashCode code = Files.hash(file, hashfunc); ch = Channels.newChannel(new FileInputStream(file)); ByteBuffer buf = ByteBuffer.wrap(cxt.buf); final int len = ch.read(buf); if (len == 0) return; final HashCode code = hashfunc.hashBytes(cxt.buf, 0, Ints.checkedCast(len)); synchronized (dupes) { dupes.put(code, file); } cxt.sw.stop(); log.debug("{} -> {} ({}) - {} us", file, code, DateFormat.getInstance().format(file.lastModified()), cxt.sw.elapsed(TimeUnit.MILLISECONDS)); } catch (Exception e) { log.debug("exception", e); } finally { cxt.recycle(); if (ch != null) try { ch.close(); } catch (IOException unused) { } ; } } }); } log.info("done submitting {} to analyzer", dir.getAbsolutePath()); } try { shutdownExecutor(executor, log); } catch (InterruptedException e) { log.debug("exception", e); } for (Collection<File> filez : dupes.asMap().values()) { if (filez.size() == 1) continue; log.info("dupes found: {}", filez); } }
From source file:com.slytechs.capture.StreamFactory.java
public <T extends InputCapture<? extends FilePacket>> T newInput(final Class<T> t, final File file, Filter<ProtocolFilterTarget> filter) throws IOException { final BufferedInputStream b = new BufferedInputStream(new FileInputStream(file)); b.mark(1024); // Buffer first 1K of stream so we can rewind /*/*from www. j a v a 2 s . c o m*/ * Check the stream, without decompression first */ if (formatType(Channels.newChannel(b)) != null) { b.close(); /* * This is a plain uncompressed file, open up a FileChannel. It will be * much faster */ return newInput(t, new RandomAccessFile(file, "rw").getChannel(), filter); } /* * Try with gunziped stream, second */ b.reset(); // Rewind if (formatType(Channels.newChannel(new GZIPInputStream(b))) != null) { b.close(); /* * Now reopen the same file, but this time without the buffered * inputstream in the middle. Try to make things as efficient as possible. * TODO: implement much faster channel based GZIP decompression algorithm */ return newInput(t, Channels.newChannel(new GZIPInputStream(new FileInputStream(file))), filter); } throw new IllegalArgumentException( "File is not any compressed or decompressed known format [" + file.getName() + "]"); }
From source file:de.Keyle.MyPet.util.Updater.java
public void download() { String url = "https://mypet-plugin.de/download/" + plugin + "/"; if (MyPetVersion.isDevBuild()) { url += "dev"; } else {//from ww w . j a v a 2s . c o m url += "release"; } File pluginFile; if (Configuration.Update.REPLACE_OLD) { pluginFile = new File(MyPetApi.getPlugin().getFile().getParentFile().getAbsolutePath(), "update/" + MyPetApi.getPlugin().getFile().getName()); } else { pluginFile = new File(MyPetApi.getPlugin().getFile().getParentFile().getAbsolutePath(), "update/MyPet-" + latest.getVersion() + ".jar"); } String finalUrl = url; thread = new Thread(() -> { try { MyPetApi.getLogger().info(ChatColor.RED + "Start update download: " + ChatColor.RESET + latest); URL website = new URL(finalUrl); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(pluginFile); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); String message = "Finished update download."; if (Configuration.Update.REPLACE_OLD || MyPetApi.getPlugin().getFile().getName() .equals("MyPet-" + latest.getVersion() + ".jar")) { message += " The update will be loaded on the next server start."; } else { message += " The file was stored in the \"update\" folder."; } MyPetApi.getLogger().info(message); } catch (IOException e) { e.printStackTrace(); } }); thread.start(); }
From source file:org.wymiwyg.wrhapi.test.BaseTests.java
private void testSimpleBody(final boolean writeBody) throws Exception { final String body = "This is the content of the body"; WebServer webServer = createServer().startNewWebServer(new Handler() { public void handle(Request request, Response response) throws HandlerException { log.info("handling testSimpleBody"); if (writeBody) { response.setBody(new MessageBody2Write() { public void writeTo(WritableByteChannel out) throws IOException { out.write(ByteBuffer.wrap(body.getBytes())); }/* w ww. ja v a 2 s.co m*/ }); } else { response.setBody(new MessageBody2Read() { public ReadableByteChannel read() throws IOException { return Channels.newChannel(new ByteArrayInputStream(body.getBytes())); } }); } } }, serverBinding); try { URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":" + serverBinding.getPort() + "/"); Reader reader = new InputStreamReader(serverURL.openStream()); StringWriter stringWriter = new StringWriter(); for (int ch = reader.read(); ch != -1; ch = reader.read()) { stringWriter.write(ch); } assertEquals(body, stringWriter.toString()); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { webServer.stop(); } }
From source file:io.druid.segment.data.CompressedVSizeIndexedV3WriterTest.java
private void checkSerializedSizeAndData(int offsetChunkFactor, int valueChunkFactor) throws Exception { int maxValue = vals.size() > 0 ? getMaxValue(vals) : 0; CompressedIntsIndexedWriter offsetWriter = new CompressedIntsIndexedWriter(ioPeon, "offset", offsetChunkFactor, byteOrder, compressionStrategy); CompressedVSizeIntsIndexedWriter valueWriter = new CompressedVSizeIntsIndexedWriter(ioPeon, "value", maxValue, valueChunkFactor, byteOrder, compressionStrategy); CompressedVSizeIndexedV3Writer writer = new CompressedVSizeIndexedV3Writer(offsetWriter, valueWriter); CompressedVSizeIndexedV3Supplier supplierFromIterable = CompressedVSizeIndexedV3Supplier .fromIterable(Iterables.transform(vals, new Function<int[], IndexedInts>() { @Nullable/* w ww. j a va2s.c o m*/ @Override public IndexedInts apply(@Nullable final int[] input) { return new ArrayBasedIndexedInts(input); } }), offsetChunkFactor, maxValue, byteOrder, compressionStrategy); writer.open(); for (int[] val : vals) { writer.add(val); } writer.close(); long writtenLength = writer.getSerializedSize(); final WritableByteChannel outputChannel = Channels.newChannel(ioPeon.makeOutputStream("output")); writer.writeToChannel(outputChannel); outputChannel.close(); assertEquals(writtenLength, supplierFromIterable.getSerializedSize()); // read from ByteBuffer and check values CompressedVSizeIndexedV3Supplier supplierFromByteBuffer = CompressedVSizeIndexedV3Supplier .fromByteBuffer(ByteBuffer.wrap(IOUtils.toByteArray(ioPeon.makeInputStream("output"))), byteOrder); IndexedMultivalue<IndexedInts> indexedMultivalue = supplierFromByteBuffer.get(); assertEquals(indexedMultivalue.size(), vals.size()); for (int i = 0; i < vals.size(); ++i) { IndexedInts subVals = indexedMultivalue.get(i); assertEquals(subVals.size(), vals.get(i).length); for (int j = 0; j < subVals.size(); ++j) { assertEquals(subVals.get(j), vals.get(i)[j]); } } CloseQuietly.close(indexedMultivalue); }
From source file:org.mycore.common.content.MCRContent.java
/** * Returns an readable bytechannel to this content or null if one is not available. *//* ww w . j a v a2 s . c o m*/ public ReadableByteChannel getReadableByteChannel() throws IOException { InputStream inputStream = getInputStream(); return inputStream == null ? null : Channels.newChannel(inputStream); }
From source file:com.alibaba.otter.shared.common.utils.NioUtils.java
/** * ??copy/*w w w . ja v a 2s.com*/ */ public static long copy(InputStream input, OutputStream output) throws IOException { long count = 0; long n = 0; if (input instanceof FileInputStream) { FileChannel inChannel = ((FileInputStream) input).getChannel(); WritableByteChannel outChannel = Channels.newChannel(output); count = inChannel.transferTo(0, inChannel.size(), outChannel); } else if (output instanceof FileOutputStream) { FileChannel outChannel = ((FileOutputStream) output).getChannel(); ReadableByteChannel inChannel = Channels.newChannel(input); do { n = outChannel.transferFrom(inChannel, count, DEFAULT_BUFFER_SIZE); count += n; } while (n > 0); } else { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, (int) n); count += n; } // ReadableByteChannel inChannel = Channels.newChannel(input); // WritableByteChannel outChannel = Channels.newChannel(output); // // //ByteBuffer buffer = new ByteBuffer(DEFAULT_BUFFER_SIZE); // ByteBuffer buffer = ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE); // while (-1 != (n = inChannel.read(buffer))) { // outChannel.write(buffer); // count += n; // } } return count; }
From source file:com.mgmtp.perfload.perfalyzer.util.IoUtilities.java
private static void extractEntry(final ZipFile zf, final ZipEntry entry, final File destDir) throws IOException { File file = new File(destDir, entry.getName()); if (entry.isDirectory()) { file.mkdirs();//from w w w . j a va 2 s . com } else { new File(file.getParent()).mkdirs(); try (InputStream is = zf.getInputStream(entry); FileOutputStream os = new FileOutputStream(file)) { copy(Channels.newChannel(is), os.getChannel()); } // preserve modification time; must be set after the stream is closed file.setLastModified(entry.getTime()); } }