static void toHexString(String header, ByteBuffer buf) { sb.delete(0, sb.length()); for (int index = 0; index < buf.limit(); index++) { String hex = Integer.toHexString(0x0100 + (buf.get(index) & 0x00FF)).substring(1); sb.append((hex.length() < 2 ? "0" : "") + hex + " "); } LOG.debug( "hex->" + header + ": position,limit,capacity " + buf.position() + "," + buf.limit() + "," + buf.capacity()); LOG.debug("hex->" + sb.toString()); }
public void write(Tag tag, RandomAccessFile raf, RandomAccessFile tempRaf) throws CannotWriteException, IOException { FileChannel fc = raf.getChannel(); int oldTagSize = 0; if (tagExists(fc)) { // read the length if (!canOverwrite(raf)) throw new CannotWriteException("Overwritting of this kind of ID3v2 tag not supported yet"); fc.position(6); ByteBuffer buf = ByteBuffer.allocate(4); fc.read(buf); oldTagSize = (buf.get(0) & 0xFF) << 21; oldTagSize += (buf.get(1) & 0xFF) << 14; oldTagSize += (buf.get(2) & 0xFF) << 7; oldTagSize += buf.get(3) & 0xFF; oldTagSize += 10; // System.err.println("Old tag size: "+oldTagSize); int newTagSize = tc.getTagLength(tag); if (oldTagSize >= newTagSize) { // replace // System.err.println("Old ID32v Tag found, replacing the old // tag"); fc.position(0); fc.write(tc.convert(tag, oldTagSize - newTagSize)); // ID3v2 Tag Written return; } } // create new tag with padding // System.err.println("Creating a new ID3v2 Tag"); fc.position(oldTagSize); if (fc.size() > 15 * 1024 * 1024) { FileChannel tempFC = tempRaf.getChannel(); tempFC.position(0); tempFC.write(tc.convert(tag, Id3v2TagCreator.DEFAULT_PADDING)); tempFC.transferFrom(fc, tempFC.position(), fc.size() - oldTagSize); fc.close(); } else { ByteBuffer[] content = new ByteBuffer[2]; content[1] = ByteBuffer.allocate((int) fc.size()); fc.read(content[1]); content[1].rewind(); content[0] = tc.convert(tag, Id3v2TagCreator.DEFAULT_PADDING); fc.position(0); fc.write(content); } }
public static void main(String args[]) throws Exception { ByteBuffer buffer = ByteBuffer.allocate(10); for (int i = 0; i < buffer.capacity(); ++i) { buffer.put((byte) i); } buffer.position(3); buffer.limit(7); ByteBuffer slice = buffer.slice(); for (int i = 0; i < slice.capacity(); ++i) { byte b = slice.get(i); b *= 11; slice.put(i, b); } buffer.position(0); buffer.limit(buffer.capacity()); while (buffer.hasRemaining()) { System.out.println(buffer.get()); } }
private void recv(SocketChannel sc, ClientInfo ci) throws IOException { ci.channel.read(ci.inBuf); ByteBuffer tmpBuf = ci.inBuf.duplicate(); tmpBuf.flip(); int bytesProcessed = 0; boolean doneLoop = false; while (!doneLoop) { byte b; try { b = tmpBuf.get(); } catch (BufferUnderflowException bue) { // Processed all data in buffer ci.inBuf.clear(); doneLoop = true; break; } switch (b) { case TypeServerConstants.WELCOME: bytesProcessed++; break; case TypeServerConstants.GET_STRING_REQUEST: bytesProcessed++; if (ci.outputPending) { // Client is backed up. We can't append to // the byte buffer because it's in the wrong // state. We could allocate another buffer // here and change our send method to know // about multiple buffers, but we'll just // assume that the client is dead break; } ci.outBuf.put(TypeServerConstants.GET_STRING_RESPONSE); ByteBuffer strBuf = encoder.encode(testString); ci.outBuf.putShort((short) strBuf.remaining()); ci.outBuf.put(strBuf); ci.outBuf.flip(); send(sc, ci); break; case TypeServerConstants.GET_STRING_RESPONSE: int startPos = tmpBuf.position(); try { int nBytes = tmpBuf.getInt(); byte[] buf = new byte[nBytes]; tmpBuf.get(buf); bytesProcessed += buf.length + 5; String s = new String(buf); // Send the string to the GUI break; } catch (BufferUnderflowException bue) { // Processed all available data ci.inBuf.position(ci.inBuf.position() + bytesProcessed); doneLoop = true; } break; } } }
static byte[] extractByteString(ByteBuffer buf) { int len = buf.getInt(); byte[] str = null; if (len > 0) { str = new byte[len]; buf.get(str, 0, len); buf.get(); // trailing null } else str = new byte[0]; return str; }
static String extractString(ByteBuffer buf) throws java.io.UnsupportedEncodingException { int len = buf.getInt(); byte[] str = null; if (len > 0) { str = new byte[len - 1]; ; buf.get(str, 0, len - 1); buf.get(); // trailing null } else str = new byte[0]; return new String(str, "UTF-8"); }
public static void main(String[] arguments) { try { // read byte data into a byte buffer String data = "friends.dat"; FileInputStream inData = new FileInputStream(data); FileChannel inChannel = inData.getChannel(); long inSize = inChannel.size(); ByteBuffer source = ByteBuffer.allocate((int) inSize); inChannel.read(source, 0); source.position(0); System.out.println("Original byte data:"); for (int i = 0; source.remaining() > 0; i++) { System.out.print(source.get() + " "); } // convert byte data into character data source.position(0); Charset ascii = Charset.forName("US-ASCII"); CharsetDecoder toAscii = ascii.newDecoder(); CharBuffer destination = toAscii.decode(source); destination.position(0); System.out.println("\n\nNew character data:"); for (int i = 0; destination.remaining() > 0; i++) { System.out.print(destination.get()); } System.out.println(); } catch (FileNotFoundException fne) { System.out.println(fne.getMessage()); } catch (IOException ioe) { System.out.println(ioe.getMessage()); } }
static byte[] extractByteArray(ByteBuffer buf) { int len = buf.getInt(); if (len > 0) { byte[] a = new byte[len]; buf.get(a, 0, len); return a; } else return new byte[0]; }
private static WAVData readFromStream(AudioInputStream aIn) throws UnsupportedAudioFileException, IOException { ReadableByteChannel aChannel = Channels.newChannel(aIn); AudioFormat fmt = aIn.getFormat(); int numChannels = fmt.getChannels(); int bits = fmt.getSampleSizeInBits(); int format = AL_FORMAT_MONO8; if ((bits == 8) && (numChannels == 1)) { format = AL_FORMAT_MONO8; } else if ((bits == 16) && (numChannels == 1)) { format = AL_FORMAT_MONO16; } else if ((bits == 8) && (numChannels == 2)) { format = AL_FORMAT_STEREO8; } else if ((bits == 16) && (numChannels == 2)) { format = AL_FORMAT_STEREO16; } int freq = Math.round(fmt.getSampleRate()); int size = aIn.available(); ByteBuffer buffer = ByteBuffer.allocateDirect(size); while (buffer.remaining() > 0) { aChannel.read(buffer); } buffer.rewind(); // Must byte swap on big endian platforms // Thanks to swpalmer on javagaming.org forums for hint at fix if ((bits == 16) && (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN)) { int len = buffer.remaining(); for (int i = 0; i < len; i += 2) { byte a = buffer.get(i); byte b = buffer.get(i + 1); buffer.put(i, b); buffer.put(i + 1, a); } } WAVData result = new WAVData(buffer, format, size, freq, false); aIn.close(); return result; }
public void run() { try { // Exclusive lock with no overlap: FileLock fl = fc.lock(start, end, false); System.out.println("Locked: " + start + " to " + end); // Perform modification: while (buff.position() < buff.limit() - 1) buff.put((byte) (buff.get() + 1)); fl.release(); System.out.println("Released: " + start + " to " + end); } catch (IOException e) { throw new RuntimeException(e); } }
public static void main(String args[]) throws Exception { FileInputStream fin = new FileInputStream("readandshow.txt"); FileChannel fc = fin.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); fc.read(buffer); buffer.flip(); int i = 0; while (buffer.remaining() > 0) { byte b = buffer.get(); System.out.println("Character " + i + ": " + ((char) b)); i++; } fin.close(); }
protected synchronized Message receiveMessage() throws IOException { if (messageBuffer.size() > 0) { Message m = (Message) messageBuffer.get(0); messageBuffer.remove(0); return m; } try { InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer); if (remoteAddress != null) { int len = receiveBuffer.position(); receiveBuffer.rewind(); receiveBuffer.get(buf, 0, len); try { IP address = IP.fromInetAddress(remoteAddress.getAddress()); int port = remoteAddress.getPort(); extractor.appendData(buf, 0, len, new SocketDescriptor(address, port)); receiveBuffer.clear(); extractor.updateAvailableMessages(); return extractor.nextMessage(); } catch (EOFException exc) { exc.printStackTrace(); System.err.println(buf.length + ", " + len); } catch (InvocationTargetException exc) { exc.printStackTrace(); } catch (IllegalAccessException exc) { exc.printStackTrace(); } catch (InstantiationException exc) { exc.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvalidCompressionMethodException e) { e.printStackTrace(); } } } catch (ClosedChannelException exc) { if (isKeepAlive()) { throw exc; } } return null; }
public static void main(String args[]) { int count; Path filepath = null; // First, obtain a path to the file. try { filepath = Paths.get("test.txt"); } catch (InvalidPathException e) { System.out.println("Path Error " + e); return; } // Next, obtain a channel to that file within a try-with-resources block. try (SeekableByteChannel fChan = Files.newByteChannel(filepath)) { // Allocate a buffer. ByteBuffer mBuf = ByteBuffer.allocate(128); do { // Read a buffer. count = fChan.read(mBuf); // Stop when end of file is reached. if (count != -1) { // Rewind the buffer so that it can be read. mBuf.rewind(); // Read bytes from the buffer and show // them on the screen as characters. for (int i = 0; i < count; i++) System.out.print((char) mBuf.get()); } } while (count != -1); System.out.println(); } catch (IOException e) { System.out.println("I/O Error " + e); } }
public RandomAccessFile delete(RandomAccessFile raf, RandomAccessFile tempRaf) throws IOException { FileChannel fc = raf.getChannel(); fc.position(0); if (!tagExists(fc)) return raf; fc.position(6); ByteBuffer b = ByteBuffer.allocate(4); fc.read(b); b.rewind(); int tagSize = (b.get() & 0xFF) << 21; tagSize += (b.get() & 0xFF) << 14; tagSize += (b.get() & 0xFF) << 7; tagSize += b.get() & 0xFF; FileChannel tempFC = tempRaf.getChannel(); tempFC.position(0); fc.position(tagSize + 10); // Here we will try to skip eventual trash afer the tag and before the // audio data b = ByteBuffer.allocate(4); int skip = 0; while (fc.read(b) != -1) { if ((b.get(0) & 0xFF) == 0xFF && (b.get(1) & 0xE0) == 0xE0 && (b.get(1) & 0x06) != 0 && (b.get(2) & 0xF0) != 0xF0 && (b.get(2) & 0x08) != 0x08) { fc.position(fc.position() - 4); break; } fc.position(fc.position() - 3); b.rewind(); skip++; } tempFC.transferFrom(fc, 0, fc.size() - tagSize - 10 - skip); return tempRaf; }
public static void main(String[] argv) { if (argv.length != 3) { usage(); } String tempFile = argv[0]; String testFile = argv[1]; int fileSize = Integer.valueOf(argv[2]).intValue(); int exitcode = 0; int numRead; int numThisBuf; int numWritten; if ((fileSize <= 0) || (fileSize % 4096 != 0)) { System.out.println("Error: size is not a multiple of 4096!!!!!!"); System.out.println(); usage(); } try { int bufSize = 4096; byte[] inBytes = new byte[bufSize]; byte[] outBytes = new byte[bufSize]; Random ioRandom = new Random(2006); ioRandom.nextBytes(outBytes); ByteBuffer inBuf = ByteBuffer.allocate(bufSize); ByteBuffer outBuf = ByteBuffer.wrap(outBytes); // // Loop forever // while (true) { // // Write the temporary file // FileOutputStream fos = new FileOutputStream(tempFile); FileChannel foc = fos.getChannel(); numWritten = 0; while (numWritten < fileSize) { outBuf.clear(); // sets limit to capacity & position to zero while (outBuf.hasRemaining()) { numWritten += foc.write(outBuf); } } // // Move to permanent location // FileChannel srcChannel = new FileInputStream(tempFile).getChannel(); FileChannel dstChannel = new FileOutputStream(testFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); boolean success = (new File(tempFile)).delete(); if (!success) { System.out.println("Warning: unable to delete temporary file"); } // // Read and compare // FileInputStream fis = new FileInputStream(testFile); FileChannel fic = fis.getChannel(); for (numRead = 0, numThisBuf = 0; numRead < fileSize; numThisBuf = 0) { inBuf.rewind(); // Set the buffer position to 0 numThisBuf = fic.read(inBuf); while (numThisBuf < bufSize) { numThisBuf += fic.read(inBuf); } numRead += bufSize; inBuf.rewind(); // Set the buffer position to 0 inBuf.get(inBytes); boolean same = Arrays.equals(inBytes, outBytes); if (same = false) { System.out.println("Data read does not equal data written at " + numRead + " bytes"); } } } } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(System.err); exitcode = 1; // break; } catch (SecurityException se) { se.printStackTrace(System.err); exitcode = 1; // break; } catch (Throwable t) { t.printStackTrace(System.err); exitcode = 1; } System.exit(exitcode); }
public static void main(String[] args) { try { System.out.println("CliTest.java"); // create TCP socket channel SocketChannel channel = SocketChannel.open(); System.out.println("CliTest.java: channel created"); channel.connect(new InetSocketAddress("localhost", PORT)); System.out.println("CliTest.java: channel socket connected"); System.out.println(); // create & send a login message byte[] bytes = LoginMessage.getLoginMessage("user1", "password1"); System.out.println("CliTest.java: login message created"); System.out.println(LoginMessage.getMessageString(bytes)); System.out.printf("CliTest.java: login message length in bytes: %d\n", bytes.length); ByteBuffer buf = ByteBuffer.allocate(4096); buf.put(bytes); buf.flip(); // System.out.printf("CliTest.java: buf.remaining before channel.write(): %d\n", // buf.remaining()); int numwritten = channel.write(buf); System.out.printf( "CliTest.java: login mesage written: number of bytes written: %d\n", numwritten); // read reply message buf.clear(); int numread = channel.read(buf); bytes = new byte[numread]; buf.flip(); buf.get(bytes); if (LoginMessage.isLoginSuccessMessage(bytes)) { System.out.printf( "CliTest.java: first message read: Success Message: number of bytes read: %d\n", numread); // get remote port number from success message int port = LoginMessage.getPort(bytes); System.out.printf("Port Number: %d\n", port); byte playerid = LoginMessage.getPlayerId(bytes); System.out.printf("Player id: %d\n", playerid); String mcastString = LoginMessage.getMulticastAddress(bytes); System.out.printf("Multicast Address: %s\n", mcastString); // create datagram channel & connect to rem port DatagramChannel dchannel = DatagramChannel.open(); dchannel.socket().bind(new InetSocketAddress(0)); dchannel.socket().connect(new InetSocketAddress(channel.socket().getInetAddress(), port)); // get localport of datagram socket int localport = dchannel.socket().getLocalPort(); System.out.printf("UDP local port: %d\n", localport); // send success message to send port number to server bytes = LoginMessage.getLoginSuccessMessage(playerid, null, localport); buf.clear(); buf.put(bytes); buf.flip(); channel.write(buf); DeathMessage dm = new DeathMessage((byte) 1, (byte) 1); bytes = dm.getByteMessage(); buf.clear(); buf.put(bytes); buf.flip(); channel.write(buf); } else { System.out.printf( "CliTest.java: first message read: NOT Success Message: number of bytes read: %d\n", numread); } channel.close(); } catch (Exception e) { e.printStackTrace(); } }
private void readMessage(SelectionKey sk, SocketChannel readChannel, TcpAddress incomingAddress) throws IOException { // note that socket has been used SocketEntry entry = (SocketEntry) sockets.get(incomingAddress); if (entry != null) { entry.used(); ByteBuffer readBuffer = entry.getReadBuffer(); if (readBuffer != null) { readChannel.read(readBuffer); if (readBuffer.hasRemaining()) { readChannel.register(selector, SelectionKey.OP_READ, entry); } else { dispatchMessage(incomingAddress, readBuffer, readBuffer.capacity()); } return; } } ByteBuffer byteBuffer = ByteBuffer.wrap(buf); byteBuffer.limit(messageLengthDecoder.getMinHeaderLength()); long bytesRead = readChannel.read(byteBuffer); if (logger.isDebugEnabled()) { logger.debug("Reading header " + bytesRead + " bytes from " + incomingAddress); } MessageLength messageLength = new MessageLength(0, Integer.MIN_VALUE); if (bytesRead == messageLengthDecoder.getMinHeaderLength()) { messageLength = messageLengthDecoder.getMessageLength(ByteBuffer.wrap(buf)); if (logger.isDebugEnabled()) { logger.debug("Message length is " + messageLength); } if ((messageLength.getMessageLength() > getMaxInboundMessageSize()) || (messageLength.getMessageLength() <= 0)) { logger.error( "Received message length " + messageLength + " is greater than inboundBufferSize " + getMaxInboundMessageSize()); synchronized (entry) { entry.getSocket().close(); logger.info("Socket to " + entry.getPeerAddress() + " closed due to an error"); } } else { byteBuffer.limit(messageLength.getMessageLength()); bytesRead += readChannel.read(byteBuffer); if (bytesRead == messageLength.getMessageLength()) { dispatchMessage(incomingAddress, byteBuffer, bytesRead); } else { byte[] message = new byte[byteBuffer.limit()]; byteBuffer.flip(); byteBuffer.get(message, 0, byteBuffer.limit() - byteBuffer.remaining()); entry.setReadBuffer(ByteBuffer.wrap(message)); } readChannel.register(selector, SelectionKey.OP_READ, entry); } } else if (bytesRead < 0) { logger.debug("Socket closed remotely"); sk.cancel(); readChannel.close(); TransportStateEvent e = new TransportStateEvent( DefaultTcpTransportMapping.this, incomingAddress, TransportStateEvent.STATE_DISCONNECTED_REMOTELY, null); fireConnectionStateChanged(e); } }