// Check if DatagramChannel.send while connected can include // address without throwing private static void test1() throws Exception { DatagramChannel sndChannel = DatagramChannel.open(); sndChannel.socket().bind(null); InetSocketAddress sender = new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort()); DatagramChannel rcvChannel = DatagramChannel.open(); rcvChannel.socket().bind(null); InetSocketAddress receiver = new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort()); rcvChannel.connect(sender); sndChannel.connect(receiver); ByteBuffer bb = ByteBuffer.allocate(256); bb.put("hello".getBytes()); bb.flip(); int sent = sndChannel.send(bb, receiver); bb.clear(); rcvChannel.receive(bb); bb.flip(); CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb); if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed"); rcvChannel.close(); sndChannel.close(); }
protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) { int mark = src.position(); if (needsMark) { if (dst.remaining() < 2) return CoderResult.OVERFLOW; put(BYTE_ORDER_MARK, dst); needsMark = false; } try { while (src.hasRemaining()) { char c = src.get(); if (!Surrogate.is(c)) { if (dst.remaining() < 2) return CoderResult.OVERFLOW; mark++; put(c, dst); continue; } int d = sgp.parse(c, src); if (d < 0) return sgp.error(); if (dst.remaining() < 4) return CoderResult.OVERFLOW; mark += 2; put(Surrogate.high(d), dst); put(Surrogate.low(d), dst); } return CoderResult.UNDERFLOW; } finally { src.position(mark); } }
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 boolean check(CharsetDecoder dec, byte[] bytes, boolean direct, int[] flow) { int inPos = flow[0]; int inLen = flow[1]; int outPos = flow[2]; int outLen = flow[3]; int expedInPos = flow[4]; int expedOutPos = flow[5]; CoderResult expedCR = (flow[6] == 0) ? CoderResult.UNDERFLOW : CoderResult.OVERFLOW; ByteBuffer bbf; CharBuffer cbf; if (direct) { bbf = ByteBuffer.allocateDirect(inPos + bytes.length); cbf = ByteBuffer.allocateDirect((outPos + outLen) * 2).asCharBuffer(); } else { bbf = ByteBuffer.allocate(inPos + bytes.length); cbf = CharBuffer.allocate(outPos + outLen); } bbf.position(inPos); bbf.put(bytes).flip().position(inPos).limit(inPos + inLen); cbf.position(outPos); dec.reset(); CoderResult cr = dec.decode(bbf, cbf, false); if (cr != expedCR || bbf.position() != expedInPos || cbf.position() != expedOutPos) { System.out.printf("Expected(direct=%5b): [", direct); for (int i : flow) System.out.print(" " + i); System.out.println( "] CR=" + cr + ", inPos=" + bbf.position() + ", outPos=" + cbf.position()); return false; } return true; }
// Check if the datagramsocket adaptor can send with a packet // that has not been initialized with an address; the legacy // datagram socket will send in this case private static void test2() throws Exception { DatagramChannel sndChannel = DatagramChannel.open(); sndChannel.socket().bind(null); InetSocketAddress sender = new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort()); DatagramChannel rcvChannel = DatagramChannel.open(); rcvChannel.socket().bind(null); InetSocketAddress receiver = new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort()); rcvChannel.connect(sender); sndChannel.connect(receiver); byte b[] = "hello".getBytes("UTF-8"); DatagramPacket pkt = new DatagramPacket(b, b.length); sndChannel.socket().send(pkt); ByteBuffer bb = ByteBuffer.allocate(256); rcvChannel.receive(bb); bb.flip(); CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb); if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed"); // Check that the pkt got set with the target address; // This is legacy behavior if (!pkt.getSocketAddress().equals(receiver)) throw new RuntimeException("Test failed"); rcvChannel.close(); sndChannel.close(); }
public static void main(String[] args) { ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 'a'}); bb.rewind(); printnb("Byte Buffer "); while (bb.hasRemaining()) printnb(bb.position() + " -> " + bb.get() + ", "); print(); CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer(); printnb("Char Buffer "); while (cb.hasRemaining()) printnb(cb.position() + " -> " + cb.get() + ", "); print(); FloatBuffer fb = ((ByteBuffer) bb.rewind()).asFloatBuffer(); printnb("Float Buffer "); while (fb.hasRemaining()) printnb(fb.position() + " -> " + fb.get() + ", "); print(); IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer(); printnb("Int Buffer "); while (ib.hasRemaining()) printnb(ib.position() + " -> " + ib.get() + ", "); print(); LongBuffer lb = ((ByteBuffer) bb.rewind()).asLongBuffer(); printnb("Long Buffer "); while (lb.hasRemaining()) printnb(lb.position() + " -> " + lb.get() + ", "); print(); ShortBuffer sb = ((ByteBuffer) bb.rewind()).asShortBuffer(); printnb("Short Buffer "); while (sb.hasRemaining()) printnb(sb.position() + " -> " + sb.get() + ", "); print(); DoubleBuffer db = ((ByteBuffer) bb.rewind()).asDoubleBuffer(); printnb("Double Buffer "); while (db.hasRemaining()) printnb(db.position() + " -> " + db.get() + ", "); }
public CharBuffer put(CharBuffer src) { if (src instanceof DirectCharBufferS) { if (src == this) throw new IllegalArgumentException(); DirectCharBufferS sb = (DirectCharBufferS) src; int spos = sb.position(); int slim = sb.limit(); assert (spos <= slim); int srem = (spos <= slim ? slim - spos : 0); int pos = position(); int lim = limit(); assert (pos <= lim); int rem = (pos <= lim ? lim - pos : 0); if (srem > rem) throw new BufferOverflowException(); unsafe.copyMemory(sb.ix(spos), ix(pos), srem << 1); sb.position(spos + srem); position(pos + srem); } else if (!src.isDirect()) { int spos = src.position(); int slim = src.limit(); assert (spos <= slim); int srem = (spos <= slim ? slim - spos : 0); put(src.hb, src.offset + spos, srem); src.position(spos + srem); } else { super.put(src); } return this; }
private String digestToBase64(byte[] digest, int len) { CharBuffer cb = CharBuffer.allocate(); Base64.encode(cb, digest, 0, len); return cb.close(); }
protected long computeEstimatedMemorySize() { long result = 0; if (!textArray.isDirect()) result += (Character.SIZE / 8) * textArray.capacity(); result += (Integer.SIZE / 8) * textIndexArray.length; result += (Double.SIZE / 8) * latlonArray.length; return result; }
static byte[] encode(char[] cc, Charset cs, boolean testDirect, Time t) throws Exception { ByteBuffer bbf; CharBuffer cbf; CharsetEncoder enc = cs.newEncoder(); String csn = cs.name(); if (testDirect) { bbf = ByteBuffer.allocateDirect(cc.length * 4); cbf = ByteBuffer.allocateDirect(cc.length * 2).asCharBuffer(); cbf.put(cc).flip(); } else { bbf = ByteBuffer.allocate(cc.length * 4); cbf = CharBuffer.wrap(cc); } CoderResult cr = null; long t1 = System.nanoTime() / 1000; for (int i = 0; i < iteration; i++) { cbf.rewind(); bbf.clear(); enc.reset(); cr = enc.encode(cbf, bbf, true); } long t2 = System.nanoTime() / 1000; t.t = (t2 - t1) / iteration; if (cr != CoderResult.UNDERFLOW) { System.out.println("ENC-----------------"); int pos = cbf.position(); System.out.printf(" cr=%s, cbf.pos=%d, cc[pos]=%x%n", cr.toString(), pos, cc[pos] & 0xffff); throw new RuntimeException("Encoding err: " + csn); } byte[] bb = new byte[bbf.position()]; bbf.flip(); bbf.get(bb); return bb; }
protected PlaceNameChunk createPlaceNameChunk(PlaceNameService service) { int numChars = this.textArray.length(); CharBuffer textBuffer = newCharBuffer(numChars); textBuffer.put(this.textArray.toString()); textBuffer.rewind(); return new PlaceNameChunk( service, textBuffer, this.textIndexArray, this.latlonArray, this.numEntries); }
/** * Writes all data written up to the moment to out. * * @param out * @throws IOException */ public void writeTo(Writer writer) throws IOException { CharBuffer b = firstBuffer; while (b != null) { writer.write(b.getChars(), 0, b.getUsedSize()); b = b.getNext(); } }
public void getChars(int where, int len, Segment txt) throws BadLocationException { CharBuffer b = buffer; int start = b.getSegment(where, len); if (start < 0) throw new BadLocationException("invalid offset", where); txt.offset = start; txt.array = b.getArray(); txt.count = len; }
public void printTo(ServletOutputStream outputStream) throws IOException { CharBuffer b = firstBuffer; while (b != null) { outputStream.print(new String(b.getChars())); b = b.getNext(); } }
public SwingContent(int initialSize) { CharBuffer b = new CharBuffer(initialSize); // Swing assumes that a Content object is initialized to contain // a single '\n'. This of course is not clearly documented ... b.gapEnd = initialSize - 1; b.getArray()[b.gapEnd] = '\n'; this.buffer = b; }
@NotNull public static IndexedCollection<Character> ofCharacter( @NotNull Collection<Character> intCollection) { CharBuffer vals = CharBuffer.allocate(intCollection.size()); intCollection.forEach(vals::put); vals.flip(); return new CharacterBufferCollection(vals); }
public int read(CharBuffer cb) { if (count-- == 0) return -1; // Indicates end of input cb.append(capitals[rand.nextInt(capitals.length)]); for (int i = 0; i < 4; i++) { cb.append(vowels[rand.nextInt(vowels.length)]); cb.append(lowers[rand.nextInt(lowers.length)]); } cb.append(" "); return 10; // Number of characters appended }
@Override public void forEachRemaining(IntConsumer action) { if (action == null) throw new NullPointerException(); CharBuffer cb = buffer; int i = index; int hi = limit; index = hi; while (i < hi) { action.accept(cb.getUnchecked(i++)); } }
/** * Prints a String to the log. * * @param buffer receiving byte buffer. * @param offset offset into the receiving buffer. * @param s the new string to be logged. * @return the new offset into the byte buffer. */ private int print(byte[] buffer, int offset, String s) { int length = s.length(); _cb.ensureCapacity(length); char[] cBuf = _cb.getBuffer(); s.getChars(0, length, cBuf, 0); for (int i = length - 1; i >= 0; i--) buffer[offset + i] = (byte) cBuf[i]; return offset + length; }
/* * Mon, 17 Jan 1994 11:14:55 -0500 (EST) */ public String printDate() { if (_lastDate != null && _lastTime == _localTimeOfEpoch) return _lastDate; CharBuffer cb = new CharBuffer(); printDate(cb); _lastDate = cb.toString(); _lastTime = _localTimeOfEpoch; return _lastDate; }
public UndoableEdit insertString(int where, String str, boolean beforeMarkers) throws BadLocationException { CharBuffer b = buffer; if (where < 0 || where > b.length()) throw new BadLocationException("bad insert", where); b.insert(where, str, beforeMarkers); GapUndoableEdit undo = new GapUndoableEdit(where); undo.content = this; undo.data = str; undo.nitems = str.length(); undo.isInsertion = true; return undo; }
/** * Draw every char in separate terminal cell to guaranty equal width for different lines. * Nevertheless to improve kerning we draw word characters as one block for monospaced fonts. */ private void drawChars(int x, int y, CharBuffer buf, TextStyle style, Graphics2D gfx) { final int blockLen = 1; int offset = 0; int drawCharsOffset = 0; // workaround to fix Swing bad rendering of bold special chars on Linux // TODO required for italic? CharBuffer renderingBuffer; if (mySettingsProvider.DECCompatibilityMode() && style.hasOption(TextStyle.Option.BOLD)) { renderingBuffer = CharUtils.heavyDecCompatibleBuffer(buf); } else { renderingBuffer = buf; } while (offset + blockLen <= buf.length()) { if (renderingBuffer.getBuf()[buf.getStart() + offset] == CharUtils.DWC) { offset += blockLen; drawCharsOffset += blockLen; continue; // dont' draw second part(fake one) of double width character } Font font = getFontToDisplay(buf.charAt(offset + blockLen - 1), style); // while (myMonospaced && (offset + blockLen < buf.getLength()) && // isWordCharacter(buf.charAt(offset + blockLen - 1)) // && (font == getFontToDisplay(buf.charAt(offset + blockLen - 1), style))) { // blockLen++; // } gfx.setFont(font); int descent = gfx.getFontMetrics(font).getDescent(); int baseLine = (y + 1) * myCharSize.height - descent; int xCoord = (x + drawCharsOffset) * myCharSize.width; int textLength = CharUtils.getTextLengthDoubleWidthAware( buf.getBuf(), buf.getStart() + offset, blockLen, mySettingsProvider.ambiguousCharsAreDoubleWidth()); int yCoord = y * myCharSize.height; gfx.setClip( xCoord, yCoord, Math.min(textLength * myCharSize.width, getWidth() - xCoord), Math.min(myCharSize.height, getHeight() - yCoord)); gfx.setColor(getPalette().getColor(myStyleState.getForeground(style.getForegroundForRun()))); gfx.drawChars(renderingBuffer.getBuf(), buf.getStart() + offset, blockLen, xCoord, baseLine); drawCharsOffset += blockLen; offset += blockLen; } gfx.setClip(null); }
public UndoableEdit remove(int where, int nitems) throws BadLocationException { CharBuffer b = buffer; if (nitems < 0 || where < 0 || where + nitems > b.length()) throw new BadLocationException("invalid remove", where); b.delete(where, nitems); GapUndoableEdit undo = new GapUndoableEdit(where); undo.content = this; undo.data = new String(b.getArray(), b.gapEnd - nitems, nitems); undo.nitems = nitems; undo.isInsertion = false; return undo; }
/** * Writes all data written up to the moment to string buffer. * * @param out * @throws IOException */ public char[] toCharArray() { CharBuffer b = firstBuffer; if (b == null) { return new char[0]; } CharBuffer l = b; while (l.getNext() != null) { l = l.getNext(); } char[] result = new char[l.getTotalSize()]; int index = 0; while (b != null) { int s = b.getUsedSize(); System.arraycopy(b.getChars(), 0, result, index, s); index += s; b = b.getNext(); } return result; }
private int parseInt(CharBuffer cb) throws Exception { int value = 0; int sign = 1; for (int i = 0; i < cb.length(); i++) { int ch = cb.charAt(i); if (i == 0 && ch == '-') sign = -1; else if (i == 0 && ch == '+') { } else if (ch >= '0' && ch <= '9') value = 10 * value + ch - '0'; else throw new Exception(); } return sign * value; }
/** * Creates a string in a specfied character set. * * @param value String constant, must not be null * @param charsetName Name of the character set, may be null * @param collation Collation, may be null * @throws IllegalCharsetNameException If the given charset name is illegal * @throws UnsupportedCharsetException If no support for the named charset is available in this * instance of the Java virtual machine * @throws RuntimeException If the given value cannot be represented in the given charset */ public NlsString(String value, String charsetName, SqlCollation collation) { assert value != null; if (null != charsetName) { charsetName = charsetName.toUpperCase(); this.charsetName = charsetName; String javaCharsetName = SqlUtil.translateCharacterSetName(charsetName); if (javaCharsetName == null) { throw new UnsupportedCharsetException(charsetName); } this.charset = Charset.forName(javaCharsetName); CharsetEncoder encoder = charset.newEncoder(); // dry run to see if encoding hits any problems try { encoder.encode(CharBuffer.wrap(value)); } catch (CharacterCodingException ex) { throw RESOURCE.charsetEncoding(value, javaCharsetName).ex(); } } else { this.charsetName = null; this.charset = null; } this.collation = collation; this.value = value; }
public static void main(String args[]) throws Exception { String s = "abc\uD800\uDC00qrst"; // Valid surrogate char[] c = s.toCharArray(); CharsetEncoder enc = Charset.forName("ISO8859_1").newEncoder().onUnmappableCharacter(CodingErrorAction.REPLACE); /* Process the first 4 characters, including the high surrogate which should be stored */ ByteBuffer bb = ByteBuffer.allocate(10); CharBuffer cb = CharBuffer.wrap(c); cb.limit(4); enc.encode(cb, bb, false); cb.limit(7); enc.encode(cb, bb, true); byte[] first = bb.array(); for (int i = 0; i < 7; i++) System.err.printf("[%d]=%d was %d\n", i, (int) first[i] & 0xffff, (int) c[i] & 0xffff); }
@NotNull public static IndexedCollection<Character> ofCharacter(@NotNull ByteBuffer byteBuffer) { int magic = byteBuffer.getInt(); if (magic != MAGIC) { throw new IllegalArgumentException("bad magic number"); } int version = byteBuffer.getInt(); if (version != VERSION) { throw new IllegalArgumentException("bad version number"); } int size = byteBuffer.getInt(); CharBuffer values = byteBuffer.asCharBuffer(); values.limit(size); byteBuffer.position(byteBuffer.position() + size * Integer.BYTES); return new CharacterBufferCollection(values.slice()); }
/** @see java.io.Writer.write(char cbuf[]) */ public void write(char[] cbuf) throws IOException { if (cbuf == null) { throw new NullPointerException(); } lastBuffer = lastBuffer.append(cbuf, 0, cbuf.length); length += cbuf.length; }
/** * Gets a Reader for a text flavor, decoded, if necessary, for the expected charset (encoding). * The supported representation classes are <code>java.io.Reader</code>, <code>java.lang.String * </code>, <code>java.nio.CharBuffer</code>, <code>[C</code>, <code>java.io.InputStream</code>, * <code>java.nio.ByteBuffer</code>, and <code>[B</code>. * * <p>Because text flavors which do not support the charset parameter are encoded in a * non-standard format, this method should not be called for such flavors. However, in order to * maintain backward-compatibility, if this method is called for such a flavor, this method will * treat the flavor as though it supports the charset parameter and attempt to decode it * accordingly. See <code>selectBestTextFlavor</code> for a list of text flavors which do not * support the charset parameter. * * @param transferable the <code>Transferable</code> whose data will be requested in this flavor * @return a <code>Reader</code> to read the <code>Transferable</code>'s data * @exception IllegalArgumentException if the representation class is not one of the seven listed * above * @exception IllegalArgumentException if the <code>Transferable</code> has <code>null</code> data * @exception NullPointerException if the <code>Transferable</code> is <code>null</code> * @exception UnsupportedEncodingException if this flavor's representation is <code> * java.io.InputStream</code>, <code>java.nio.ByteBuffer</code>, or <code>[B</code> and this * flavor's encoding is not supported by this implementation of the Java platform * @exception UnsupportedFlavorException if the <code>Transferable</code> does not support this * flavor * @exception IOException if the data cannot be read because of an I/O error * @see #selectBestTextFlavor * @since 1.3 */ public Reader getReaderForText(Transferable transferable) throws UnsupportedFlavorException, IOException { Object transferObject = transferable.getTransferData(this); if (transferObject == null) { throw new IllegalArgumentException("getTransferData() returned null"); } if (transferObject instanceof Reader) { return (Reader) transferObject; } else if (transferObject instanceof String) { return new StringReader((String) transferObject); } else if (transferObject instanceof CharBuffer) { CharBuffer buffer = (CharBuffer) transferObject; int size = buffer.remaining(); char[] chars = new char[size]; buffer.get(chars, 0, size); return new CharArrayReader(chars); } else if (transferObject instanceof char[]) { return new CharArrayReader((char[]) transferObject); } InputStream stream = null; if (transferObject instanceof InputStream) { stream = (InputStream) transferObject; } else if (transferObject instanceof ByteBuffer) { ByteBuffer buffer = (ByteBuffer) transferObject; int size = buffer.remaining(); byte[] bytes = new byte[size]; buffer.get(bytes, 0, size); stream = new ByteArrayInputStream(bytes); } else if (transferObject instanceof byte[]) { stream = new ByteArrayInputStream((byte[]) transferObject); } if (stream == null) { throw new IllegalArgumentException( "transfer data is not Reader, String, CharBuffer, char array, InputStream, ByteBuffer, or byte array"); } String encoding = getParameter("charset"); return (encoding == null) ? new InputStreamReader(stream) : new InputStreamReader(stream, encoding); }