List of usage examples for java.nio ByteBuffer flip
public final Buffer flip()
From source file:net.vexelon.myglob.utils.Utils.java
/** * Reads an input stream into a byte array * @param source//from w w w . ja v a 2 s.c o m * @return Byte array of input stream data * @throws IOException */ public static byte[] read(InputStream source) throws IOException { ReadableByteChannel srcChannel = Channels.newChannel(source); ByteArrayOutputStream baos = new ByteArrayOutputStream( source.available() > 0 ? source.available() : BUFFER_PAGE_SIZE); WritableByteChannel destination = Channels.newChannel(baos); try { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_PAGE_SIZE); while (srcChannel.read(buffer) > 0) { buffer.flip(); while (buffer.hasRemaining()) { destination.write(buffer); } buffer.clear(); } return baos.toByteArray(); } catch (IOException e) { throw e; } finally { try { if (srcChannel != null) srcChannel.close(); } catch (IOException e) { } try { if (source != null) source.close(); } catch (IOException e) { } try { if (destination != null) destination.close(); } catch (IOException e) { } } }
From source file:com.serotonin.bacnet4j.util.sero.StreamUtils.java
public static void transfer(InputStream in, SocketChannel out) throws IOException { byte[] buf = new byte[1024]; ByteBuffer bbuf = ByteBuffer.allocate(1024); int len;/*from ww w . j a v a 2 s .c om*/ while ((len = in.read(buf)) != -1) { bbuf.put(buf, 0, len); bbuf.flip(); while (bbuf.remaining() > 0) out.write(bbuf); bbuf.clear(); } }
From source file:com.openteach.diamond.network.waverider.session.DefaultSession.java
public static Command makeGreetCommand() { String HELLO = "Hello Master"; ByteBuffer buffer = ByteBuffer.allocate(HELLO.getBytes().length); buffer.put(HELLO.getBytes());//from ww w .j a va2s .c o m buffer.flip(); Command command = new Command(1L, buffer); return command; }
From source file:com.mgmtp.perfload.perfalyzer.util.IoUtilities.java
/** * Copies the content from one channel to another. * * @param srcChannel//from w w w . j a v a2 s.c o m * the source channel to copy from * @param destChannel * the destination channel to copy to */ public static void copy(final ReadableByteChannel srcChannel, final WritableByteChannel destChannel) throws IOException { final ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE); while (srcChannel.read(buffer) != -1) { // flip the buffer so it can be written to the destination channel buffer.flip(); // write to the destination channel destChannel.write(buffer); // If partial transfer, shift remainder down so it does not get lost // If buffer is empty, this is the same as calling clear() buffer.compact(); } // EOF will leave buffer in fill state buffer.flip(); // make sure the buffer is fully drained while (buffer.hasRemaining()) { destChannel.write(buffer); } }
From source file:io.blobkeeper.file.util.FileUtils.java
public static boolean isFileEmpty(@NotNull File file, @NotNull IndexElt elt) { ByteBuffer fourBytes = ByteBuffer.allocate(4); try {/*w w w. j a v a 2 s . com*/ file.getFileChannel().read(fourBytes, elt.getOffset()); } catch (IOException e) { log.error("Can't read blob file", e); throw new IllegalArgumentException(e); } fourBytes.flip(); for (byte b : fourBytes.array()) { if (b != 0) { return false; } } return true; }
From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java
private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways) throws IOException, InterruptedException { Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses(); List<DatagramChannel> channels = new ArrayList<>(); final Map<DatagramChannel, InetAddress> bindMap = Collections .synchronizedMap(new HashMap<DatagramChannel, InetAddress>()); final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections .synchronizedMap(new HashMap<InetAddress, InetAddress>()); try {// w ww.j a v a 2 s. co m for (InetAddress localAddress : localAddresses) { DatagramChannel unicastChannel = null; try { unicastChannel = DatagramChannel.open(); unicastChannel.configureBlocking(false); unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0)); } catch (IOException ioe) { IOUtils.closeQuietly(unicastChannel); throw ioe; } channels.add(unicastChannel); bindMap.put(unicastChannel, localAddress); } } catch (IOException ioe) { for (DatagramChannel channel : channels) { IOUtils.closeQuietly(channel); } throw ioe; } UdpCommunicator communicator = null; try { communicator = new UdpCommunicator(channels); communicator.startAsync().awaitRunning(); communicator.addListener(new UdpCommunicatorListener() { @Override public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { // make sure version is 2 and error isn't ADDRESS_MISMATCH and we're good to go if (packet.remaining() < 4 || packet.get(0) == 2 && packet.get(4) == PcpResultCode.ADDRESS_MISMATCH.ordinal()) { return; } InetAddress localAddress = bindMap.get(channel); if (localAddress == null) { return; } localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress()); } }); for (DatagramChannel channel : bindMap.keySet()) { for (InetAddress gateway : gateways) { ByteBuffer outBuf = ByteBuffer.allocate(1100); MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0, InetAddress.getByName("::"), 0L); mpr.dump(outBuf, bindMap.get(channel)); outBuf.flip(); communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer()); } } Thread.sleep(5000L); } finally { if (communicator != null) { communicator.stopAsync().awaitTerminated(); } } return new HashMap<>(localAddrToGatewayAddrMap); }
From source file:com.unister.semweb.drums.TestUtils.java
/** * This function checks, if the file with the given filename contains exactly the given LinkData-objects. * /*from w ww . ja va2 s . c o m*/ * @param dbFileName * the name of the file * @param linkDataList * the array, containing LinkData * @throws IOException * @throws FileLockException */ public static boolean checkContentFile(String dbFileName, DummyKVStorable[] linkDataList) throws IOException, FileLockException { // load file DummyKVStorable prototype = gp.getPrototype(); HeaderIndexFile<DummyKVStorable> dbfile = new HeaderIndexFile<DummyKVStorable>(dbFileName, 1, TestUtils.gp); ByteBuffer buffer = ByteBuffer.allocate(prototype.getSize()); long offset = 0; int k = 0; while (offset < dbfile.getFilledUpFromContentStart()) { dbfile.read(offset, buffer); buffer.flip(); DummyKVStorable newLinkData = (DummyKVStorable) prototype.fromByteBuffer(buffer); if (!newLinkData.equals(linkDataList[k])) { return false; } k++; offset += buffer.limit(); buffer.clear(); } dbfile.close(); return true; }
From source file:gridool.memcached.gateway.BinaryCommandProxy.java
private static void xferResponse(final byte opcode, final SocketChannel src, final Channel dst, final String key) throws IOException { ByteBuffer headerBuf = ByteBuffer.allocate(BinaryProtocol.HEADER_LENGTH); int headerRead = NIOUtils.readFully(src, headerBuf, BinaryProtocol.HEADER_LENGTH); assert (headerRead == BinaryProtocol.HEADER_LENGTH) : headerRead; headerBuf.flip(); if (BinaryProtocol.surpressSuccessResponse(opcode)) { // piggyback will never happens final short status = headerBuf.getShort(6); if (status == 0) { return; }/* w w w . j av a2 s. c om*/ } ChannelBuffer res; int totalBody = headerBuf.getInt(8); if (totalBody > 0) { ByteBuffer bodyBuf = ByteBuffer.allocate(totalBody); int bodyRead = NIOUtils.readFully(src, bodyBuf, totalBody); assert (bodyRead == totalBody) : "bodyRead (" + bodyRead + ") != totalBody (" + totalBody + ")"; bodyBuf.flip(); res = ChannelBuffers.wrappedBuffer(headerBuf, bodyBuf); } else { res = ChannelBuffers.wrappedBuffer(headerBuf); } String opname = BinaryProtocol.resolveName(headerBuf.get(1)); if (LOG.isDebugEnabled()) { Header header = new Header(); header.decode(headerBuf); LOG.debug( "Start sending memcached response [" + opname + "] " + res.readableBytes() + " bytes for key '" + key + "'\n" + header + '\n' + Arrays.toString(res.toByteBuffer().array())); } dst.write(res).addListener(new VerboseListener("sendResponse [" + opname + "] for key: " + key)); }
From source file:de.bluepair.sci.client.SHAUtils.java
public static <T> Map<String, String> sha512(Path path, Predicate<T> gard, T testValue, long blockSizePref, boolean forceBlockSize) { if (Files.notExists(path)) { return null; }/*from w ww . jav a 2 s . c o m*/ MessageDigest md = getDigest(); MessageDigest md1 = getDigest(); if (!gard.test(testValue)) { return null; } long blockSize = blockSizePref; long size = -1; try { size = Files.size(path); if (!forceBlockSize) {// maximal 10 hashsummen // sonst hab ich zu viele in der datei // stehen! while (size / blockSize > 10) { blockSize += blockSizePref; } } } catch (IOException e) { blockSize = blockSizePref; return null; } Map<String, String> map = new HashMap<>(); long lastStart = 0; long stepDown = blockSize; try (final SeekableByteChannel fileChannel = Files.newByteChannel(path, StandardOpenOption.READ);) { final ByteBuffer buffer = ByteBuffer.allocateDirect(8192); int last; do { if (!gard.test(testValue) || Files.notExists(path)) { return null; } buffer.clear(); last = fileChannel.read(buffer); buffer.flip(); md.update(buffer); // calc 2checksups buffer.flip(); md1.update(buffer); if (last > 0) { stepDown -= last; } // wenn ich ein 100mb netzwerk habe // ~ca. 5MB bertragung // also bei abbruch kann wiederaufgesetzt werden wenn die summen // bekannt sind. // ~hnlich Blcke berechen also // 0-5 c1 // 0-10 c2 // 5-10 c3 ... if (stepDown <= 0 || (last <= 0)) { long len = (blockSize + Math.abs(stepDown)); if (stepDown > 0) { // kottektur wenn last <0 len = blockSize - stepDown; } stepDown = blockSize; map.put("sha512_" + lastStart + "_" + len, Hex.encodeHexString(md1.digest())); lastStart += len; md1.reset(); } } while (last > 0); } catch (IOException ex) { Logger.getLogger(FileAnalysis.class.getName()).log(Level.SEVERE, null, ex); return null; } final byte[] sha1hash = md.digest(); map.put("sha512", Hex.encodeHexString(sha1hash)); return map; }
From source file:com.meltmedia.cadmium.core.FileSystemManager.java
public static void streamCopy(InputStream streamIn, OutputStream streamOut, boolean leaveOutputOpen) throws IOException { ReadableByteChannel input = Channels.newChannel(streamIn); WritableByteChannel output = Channels.newChannel(streamOut); ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024); while (input.read(buffer) != -1) { buffer.flip(); output.write(buffer);//from w w w.j av a 2 s . c o m buffer.compact(); } buffer.flip(); // Make sure the buffer is empty while (buffer.hasRemaining()) { output.write(buffer); } input.close(); if (!leaveOutputOpen) { output.close(); } }