Java Code Examples for java.nio.CharBuffer#append()

The following examples show how to use java.nio.CharBuffer#append() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Request.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
public void copyFrom(Request other) {
    this.postParams.copyFrom(other.postParams);
    this.headers.copyFrom(other.headers);
    this.httpVersion = other.httpVersion;
    this.method = other.method;
    this.socket.copyFrom(other.socket);
    this.url.copyFrom(other.url);
    this.cookies.copyFrom(other.cookies);
    if (other.bodyBuffer != null) {
        final CharBuffer otherBuffer = other.bodyBuffer;
        final CharBuffer thisBuffer = this.withBodyBuffer();
        for (int i = 0; i < otherBuffer.length(); i++) {
            thisBuffer.append(otherBuffer.charAt(i));
        }
        ((Buffer) thisBuffer).flip();
    }
    this.rawBody = other.rawBody;
}
 
Example 2
Source File: ReaderStream.java    From hj-t212-parser with Apache License 2.0 6 votes vote down vote up
public int read(CharBuffer charBuffer) throws IOException {
    int count = 0;
    int len = charBuffer.remaining();

    int i;
    while (len > 0 && !match().isPresent()){
        i = reader.read();
        if(i == -1){
            break;
        }
        charBuffer.append((char) i);
        len--;
        count++;
    }
    return count;
}
 
Example 3
Source File: FastDateFormat.java    From gflogger with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void appendTo(CharBuffer buffer, Calendar calendar) {
	int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
	
	if (offset < 0) {
		buffer.append('-');
		offset = -offset;
	} else {
		buffer.append('+');
	}
	
	int hours = offset / (60 * 60 * 1000);
	buffer.append(BufferFormatter.DIGIT_TENS[hours]);
	buffer.append(BufferFormatter.DIGIT_ONES[hours]);
	
	if (mColon) {
		buffer.append(':');
	}
	
	int minutes = offset / (60 * 1000) - 60 * hours;
	buffer.append(BufferFormatter.DIGIT_TENS[minutes]);
	buffer.append(BufferFormatter.DIGIT_ONES[minutes]);
}
 
Example 4
Source File: HTTPReadHandler.java    From AdditionsAPI with MIT License 6 votes vote down vote up
/**
 * decode content in request's readBuffer, then put it into it's lineBuilder
 */
private void decode(HTTPRequest request)
{
	//read something
	request.readBuffer.flip();
	
	//decode the bytes.
	CharBuffer charBuffer = CharBuffer.allocate(request.readBuffer.remaining());
	server.decoder.reset();
	CoderResult result = server.decoder.decode(request.readBuffer, charBuffer, true);
	server.decoder.flush(charBuffer);

	//replace unmapped characters
	if (result.isUnmappable())
	{
		charBuffer.append('?');
		request.readBuffer.position(request.readBuffer.position() + result.length());
	}
	
	//prepare the readBuffer for next read
	request.readBuffer.compact();
	
	//append decoded string to lineBuilder
	charBuffer.flip();
	request.lineBuilder.append(charBuffer.toString());
}
 
Example 5
Source File: FastDateFormat.java    From gflogger with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void appendTo(CharBuffer buffer, Calendar calendar) {
	if (mTimeZoneForced) {
		if (mTimeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
			buffer.append(mDaylight);
		} else {
			buffer.append(mStandard);
		}
	} else {
		TimeZone timeZone = calendar.getTimeZone();
		if (timeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
			buffer.append(getTimeZoneDisplay(timeZone, true, mStyle, mLocale));
		} else {
			buffer.append(getTimeZoneDisplay(timeZone, false, mStyle, mLocale));
		}
	}
}
 
Example 6
Source File: JTranscCharsetShiftJIS.java    From jtransc with Apache License 2.0 6 votes vote down vote up
@Override
@JTranscAsync
final public void decode(ByteBuffer in, CharBuffer out) {
	ensureTables();
	while(in.hasRemaining() && out.hasRemaining()) {
		int b = in.get() & 0xFF;
		boolean isDoubleWidth = (b >= 0x81 && b <= 0x9F) || (b >= 0xE0 && b <= 0xEF);
		char c;
		if (isDoubleWidth) {
			int b2 = in.get() & 0xFF;
			c = (char)fromSjisToUnicode.getOrDefault((char) ((b << 8) | b2), '?');
		} else {
			c = (char)fromSjisToUnicode.getOrDefault((char) b, '?');
		}
		out.append(c);
	}
}
 
Example 7
Source File: Variable.java    From opennars with MIT License 5 votes vote down vote up
protected static CharSequence newName(final char type, int index) {
    
    final int digits = (index >= 256 ? 3 : ((index >= 16) ? 2 : 1));
    final CharBuffer cb  = CharBuffer.allocate(1 + digits).append(type);
    do {
        cb.append(  Character.forDigit(index % 16, 16) ); index /= 16;
    } while (index != 0);
    return cb.compact().toString();
}
 
Example 8
Source File: NatsConnection.java    From nats.java with Apache License 2.0 5 votes vote down vote up
void sendUnsub(NatsSubscription sub, int after) {
    String sid = sub.getSID();
    CharBuffer protocolBuilder = CharBuffer.allocate(this.options.getMaxControlLine());
    protocolBuilder.append(OP_UNSUB);
    protocolBuilder.append(" ");
    protocolBuilder.append(sid);

    if (after > 0) {
        protocolBuilder.append(" ");
        protocolBuilder.append(String.valueOf(after));
    }
    protocolBuilder.flip();
    NatsMessage unsubMsg = new NatsMessage(protocolBuilder);
    queueInternalOutgoing(unsubMsg);
}
 
Example 9
Source File: JTranscCharsetUTF16Base.java    From jtransc with Apache License 2.0 5 votes vote down vote up
@Override
@JTranscAsync
public void decode(ByteBuffer in, CharBuffer out) {
	for (int n = 0; n < in.remaining() && out.hasRemaining(); n += 2) {
		out.append((char)JTranscBits.readInt16(in, littleEndian));
	}
}
 
Example 10
Source File: ArrayString.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ByteBuffer getDataAsByteBuffer() {
  // Store strings as null terminated character sequences
  int totalsize = 0;
  for (String aStorage : storage)
    totalsize += (aStorage.length() + 1); // 1 for null terminator
  ByteBuffer bb = ByteBuffer.allocate(2 * totalsize);
  CharBuffer cb = bb.asCharBuffer();
  // Concatenate
  for (String s : storage) {
    cb.append(s);
    cb.append('\0');
  }
  return bb;
}
 
Example 11
Source File: FastDateFormat.java    From gflogger with Apache License 2.0 5 votes vote down vote up
@Override
public void appendTo(CharBuffer buffer, int value) {
	if (value < 10) {
		buffer.append(BufferFormatter.DIGIT_ONES[value]);
	} else if (value < 100) {
		buffer.append(BufferFormatter.DIGIT_TENS[value]);
		buffer.append(BufferFormatter.DIGIT_ONES[value]);
	} else {
		BufferFormatter.append(buffer, value);
	}
}
 
Example 12
Source File: FastDateFormat.java    From gflogger with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public final void appendTo(CharBuffer buffer, int value) {
	if (value < 10) {
		buffer.append(BufferFormatter.DIGIT_ONES[value]);
	} else {
		buffer.append(BufferFormatter.DIGIT_TENS[value]);
		buffer.append(BufferFormatter.DIGIT_ONES[value]);
	}
}
 
Example 13
Source File: JTranscCharsetUTF8.java    From jtransc with Apache License 2.0 5 votes vote down vote up
@Override
@JTranscAsync
public void decode(ByteBuffer in, CharBuffer out) {
	while (in.hasRemaining() && out.hasRemaining()) {
		int c = in.get() & 0xFF;

		switch (c >> 4) {
			case 0:
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
			case 7: {
				// 0xxxxxxx
				out.append((char) (c));
				break;
			}
			case 12:
			case 13: {
				// 110x xxxx   10xx xxxx
				if(in.hasRemaining()) {
					out.append((char) (((c & 0x1F) << 6) | (in.get() & 0x3F)));
				}
				break;
			}
			case 14: {
				// 1110 xxxx  10xx xxxx  10xx xxxx
				if(in.hasRemaining()) {
					out.append((char) (((c & 0x0F) << 12) | ((in.get() & 0x3F) << 6) | (in.get() & 0x3F)));
				}
				break;
			}
		}
	}
}
 
Example 14
Source File: JTranscCharsetSingleByte.java    From jtransc with Apache License 2.0 5 votes vote down vote up
@Override
@JTranscAsync
final public void decode(ByteBuffer in, CharBuffer out) {
	while (in.hasRemaining() && out.hasRemaining()) {
		int b = in.get() & 0xFF;
		out.append(decode.charAt(b));
	}
}
 
Example 15
Source File: FastDateFormat.java    From gflogger with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void appendTo(CharBuffer buffer, Calendar calendar) {
	buffer.append(mValues[calendar.get(mField)]);
}
 
Example 16
Source File: BufferFormatterTest.java    From gflogger with Apache License 2.0 4 votes vote down vote up
@Test
	public void testAppendDoubleCharBufferWithPrecision() throws Exception {
		final CharBuffer buffer = ByteBuffer.allocateDirect(100).asCharBuffer();
		{
			final double[] numbers = new double[]{0, 1, 7, 11, 123, 7895, -100, 101, -10007};
			for (int i = 0; i < numbers.length; i++) {
				BufferFormatter.append(buffer, numbers[i], 0);
				buffer.append(' ');
				assertEquals(Double.toString(numbers[i]) + " ", toString(buffer));
				// check
				buffer.clear();
			}
		}

//		final double[] numbers = new double[]{
//			1.025292, 1.0025292, 1.00025292, 1.000025292, 1.0000025292, 1.00000025292,
//			10.025292, 10.0025292, 10.00025292, 10.000025292,
//			-1.025292, -1.0025292, -1.00025292, -1.000025292, -1.0000025292, -1.00000025292,
//			-10.025292, -10.0025292, -10.00025292, -10.000025292,
//			1.4328, -123.9487, -0.5};
//		for (int i = 0; i < numbers.length; i++) {
//			final double number = numbers[i];
//			BufferFormatter.append(buffer, number, 8);
//			buffer.append(' ');
//			assertEquals(
//					String.format(Locale.ENGLISH, "%.8f", number ) + " ",
//					toString(buffer)
//			);
//			// check
//			buffer.clear();
//		}

		final double[] numbers2 = new double[]{1e10, 1e15, 1e18, 5.074e10};
		for (int i = 0; i < numbers2.length; i++) {
			BufferFormatter.append(buffer, numbers2[i], 6);
			buffer.append(' ');
			assertEquals(String.format(Locale.ENGLISH, "%.6f", numbers2[i]) + " ", toString(buffer));
			// check
			buffer.clear();
		}

		final double[] numbers3 = new double[]{1e-5, 1e-10, 1e-18, 5.074e-10, 0.0035};
		for (int i = 0; i < numbers3.length; i++) {
			BufferFormatter.append(buffer, numbers3[i], 20);
			buffer.append(' ');
			assertEquals(String.format(Locale.ENGLISH, "%.20f", numbers3[i]) + " ", toString(buffer));
			// check
			buffer.clear();
		}

		final double[] numbers4 = new double[]{1e-19, 1e19,
			Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY,
			0.0, -0.0};
		for (int i = 0; i < numbers4.length; i++) {
			BufferFormatter.append(buffer, numbers4[i], 20);
			buffer.append(' ');
			assertEquals(Double.toString(numbers4[i]) + " ", toString(buffer));
			// check
			buffer.clear();
		}
	}
 
Example 17
Source File: FastDateFormat.java    From gflogger with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public final void appendTo(CharBuffer buffer, int value) {
	buffer.append(BufferFormatter.DIGIT_TENS[value]);
	buffer.append(BufferFormatter.DIGIT_ONES[value]);
}
 
Example 18
Source File: BufferFormatter.java    From gflogger with Apache License 2.0 4 votes vote down vote up
private static void putAt(final CharBuffer buffer, int pos, char b) {
	buffer.position(pos);
	buffer.append(b);
}
 
Example 19
Source File: XProtocolDecoder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public <T> T decodeDecimal(byte[] bytes, int offset, int length, ValueFactory<T> vf) {
    try {
        CodedInputStream inputStream = CodedInputStream.newInstance(bytes, offset, length);
        // packed BCD format (c.f. wikipedia)
        // TODO: optimization possibilities include using int/long if the digits is < X and scale = 0
        byte scale = inputStream.readRawByte();
        // we allocate an extra char for the sign
        CharBuffer unscaledString = CharBuffer.allocate(2 * inputStream.getBytesUntilLimit());
        unscaledString.position(1);
        byte sign = 0;
        // read until we encounter the sign bit
        while (true) {
            int b = 0xFF & inputStream.readRawByte();
            if ((b >> 4) > 9) {
                sign = (byte) (b >> 4);
                break;
            }
            unscaledString.append((char) ((b >> 4) + '0'));
            if ((b & 0x0f) > 9) {
                sign = (byte) (b & 0x0f);
                break;
            }
            unscaledString.append((char) ((b & 0x0f) + '0'));
        }
        if (inputStream.getBytesUntilLimit() > 0) {
            throw AssertionFailedException
                    .shouldNotHappen("Did not read all bytes while decoding decimal. Bytes left: " + inputStream.getBytesUntilLimit());
        }
        switch (sign) {
            case 0xa:
            case 0xc:
            case 0xe:
            case 0xf:
                unscaledString.put(0, '+');
                break;
            case 0xb:
            case 0xd:
                unscaledString.put(0, '-');
                break;
        }
        // may have filled the CharBuffer or one remaining. need to remove it before toString()
        int characters = unscaledString.position();
        unscaledString.clear(); // reset position
        BigInteger unscaled = new BigInteger(unscaledString.subSequence(0, characters).toString());
        return vf.createFromBigDecimal(new BigDecimal(unscaled, scale));
    } catch (IOException e) {
        throw new DataReadException(e);
    }
}
 
Example 20
Source File: XProtocolDecoder.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
@Override
public <T> T decodeDecimal(byte[] bytes, int offset, int length, ValueFactory<T> vf) {
    try {
        CodedInputStream inputStream = CodedInputStream.newInstance(bytes, offset, length);
        // packed BCD format (c.f. wikipedia)
        // TODO: optimization possibilities include using int/long if the digits is < X and scale = 0
        byte scale = inputStream.readRawByte();
        // we allocate an extra char for the sign
        CharBuffer unscaledString = CharBuffer.allocate(2 * inputStream.getBytesUntilLimit());
        unscaledString.position(1);
        byte sign = 0;
        // read until we encounter the sign bit
        while (true) {
            int b = 0xFF & inputStream.readRawByte();
            if ((b >> 4) > 9) {
                sign = (byte) (b >> 4);
                break;
            }
            unscaledString.append((char) ((b >> 4) + '0'));
            if ((b & 0x0f) > 9) {
                sign = (byte) (b & 0x0f);
                break;
            }
            unscaledString.append((char) ((b & 0x0f) + '0'));
        }
        if (inputStream.getBytesUntilLimit() > 0) {
            throw AssertionFailedException
                    .shouldNotHappen("Did not read all bytes while decoding decimal. Bytes left: " + inputStream.getBytesUntilLimit());
        }
        switch (sign) {
            case 0xa:
            case 0xc:
            case 0xe:
            case 0xf:
                unscaledString.put(0, '+');
                break;
            case 0xb:
            case 0xd:
                unscaledString.put(0, '-');
                break;
        }
        // may have filled the CharBuffer or one remaining. need to remove it before toString()
        int characters = unscaledString.position();
        unscaledString.clear(); // reset position
        BigInteger unscaled = new BigInteger(unscaledString.subSequence(0, characters).toString());
        return vf.createFromBigDecimal(new BigDecimal(unscaled, scale));
    } catch (IOException e) {
        throw new DataReadException(e);
    }
}