use of java.nio.CharBuffer in project Openfire by igniterealtime.
the class RawPrintFilter method logBuffer.
private void logBuffer(final IoSession session, final IoBuffer ioBuffer, final String receiveOrSend) {
// Keep current position in the buffer
int currentPos = ioBuffer.position();
// Decode buffer
CharBuffer charBuffer = Charset.forName("UTF-8").decode(ioBuffer.buf());
// Print buffer content
System.out.println(messagePrefix(session, receiveOrSend) + ": " + charBuffer);
// Reset to old position in the buffer
ioBuffer.position(currentPos);
}
use of java.nio.CharBuffer in project Openfire by igniterealtime.
the class XMLLightweightParser method read.
/*
* Main reading method
*/
public void read(IoBuffer byteBuffer) throws Exception {
if (buffer == null) {
// exception was thrown before, avoid duplicate exception(s)
// "read" and discard remaining data
byteBuffer.position(byteBuffer.limit());
return;
}
invalidateBuffer();
// we will abort parsing when 1 Mega of queued chars was found.
if (buffer.length() > maxBufferSize) {
// purge the local buffer / free memory
buffer = null;
// processing the exception takes quite long
final ProtocolDecoderException ex = new ProtocolDecoderException("Stopped parsing never ending stanza");
ex.setHexdump("(redacted hex dump of never ending stanza)");
throw ex;
}
CharBuffer charBuffer = CharBuffer.allocate(byteBuffer.capacity());
encoder.reset();
encoder.decode(byteBuffer.buf(), charBuffer, false);
char[] buf = new char[charBuffer.position()];
charBuffer.flip();
charBuffer.get(buf);
int readChar = buf.length;
// Just return if nothing was read
if (readChar == 0) {
return;
}
buffer.append(buf);
// Robot.
char ch;
boolean isHighSurrogate = false;
for (int i = 0; i < readChar; i++) {
ch = buf[i];
if (ch < 0x20 && ch != 0x9 && ch != 0xA && ch != 0xD && ch != 0x0) {
//Unicode characters in the range 0x0000-0x001F other than 9, A, and D are not allowed in XML
//We need to allow the NULL character, however, for Flash XMLSocket clients to work.
buffer = null;
throw new XMLNotWellFormedException("Character is invalid in: " + ch);
}
if (isHighSurrogate) {
if (Character.isLowSurrogate(ch)) {
// Everything is fine. Clean up traces for surrogates
isHighSurrogate = false;
} else {
// Trigger error. Found high surrogate not followed by low surrogate
buffer = null;
throw new Exception("Found high surrogate not followed by low surrogate");
}
} else if (Character.isHighSurrogate(ch)) {
isHighSurrogate = true;
} else if (Character.isLowSurrogate(ch)) {
// Trigger error. Found low surrogate char without a preceding high surrogate
buffer = null;
throw new Exception("Found low surrogate char without a preceding high surrogate");
}
if (status == XMLLightweightParser.TAIL) {
// Looking for the close tag
if (depth < 1 && ch == head.charAt(tailCount)) {
tailCount++;
if (tailCount == head.length()) {
// Close stanza found!
// Calculate the correct start,end position of the message into the buffer
int end = buffer.length() - readChar + (i + 1);
String msg = buffer.substring(startLastMsg, end);
// Add message to the list
foundMsg(msg);
startLastMsg = end;
}
} else {
tailCount = 0;
status = XMLLightweightParser.INSIDE;
}
} else if (status == XMLLightweightParser.PRETAIL) {
if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) {
cdataOffset++;
if (cdataOffset == XMLLightweightParser.CDATA_START.length) {
status = XMLLightweightParser.INSIDE_CDATA;
cdataOffset = 0;
continue;
}
} else {
cdataOffset = 0;
status = XMLLightweightParser.INSIDE;
}
if (ch == '/') {
status = XMLLightweightParser.TAIL;
depth--;
} else if (ch == '!') {
// This is a <! (comment) so ignore it
status = XMLLightweightParser.INSIDE;
} else {
depth++;
}
} else if (status == XMLLightweightParser.VERIFY_CLOSE_TAG) {
if (ch == '>') {
depth--;
status = XMLLightweightParser.OUTSIDE;
if (depth < 1) {
// Found a tag in the form <tag />
int end = buffer.length() - readChar + (i + 1);
String msg = buffer.substring(startLastMsg, end);
// Add message to the list
foundMsg(msg);
startLastMsg = end;
}
} else if (ch == '<') {
status = XMLLightweightParser.PRETAIL;
insideChildrenTag = true;
} else {
status = XMLLightweightParser.INSIDE;
}
} else if (status == XMLLightweightParser.INSIDE_PARAM_VALUE) {
if (ch == '"') {
status = XMLLightweightParser.INSIDE;
}
} else if (status == XMLLightweightParser.INSIDE_CDATA) {
if (ch == XMLLightweightParser.CDATA_END[cdataOffset]) {
cdataOffset++;
if (cdataOffset == XMLLightweightParser.CDATA_END.length) {
status = XMLLightweightParser.OUTSIDE;
cdataOffset = 0;
}
} else if (cdataOffset == XMLLightweightParser.CDATA_END.length - 1 && ch == XMLLightweightParser.CDATA_END[cdataOffset - 1]) {
// if we are looking for the last CDATA_END char, and we instead found an extra ']'
// char, leave cdataOffset as is and proceed to the next char. This could be a case
// where the XML character data ends with multiple square braces. For Example ]]]>
} else {
cdataOffset = 0;
}
} else if (status == XMLLightweightParser.INSIDE) {
if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) {
cdataOffset++;
if (cdataOffset == XMLLightweightParser.CDATA_START.length) {
status = XMLLightweightParser.INSIDE_CDATA;
cdataOffset = 0;
continue;
}
} else {
cdataOffset = 0;
status = XMLLightweightParser.INSIDE;
}
if (ch == '"') {
status = XMLLightweightParser.INSIDE_PARAM_VALUE;
} else if (ch == '>') {
status = XMLLightweightParser.OUTSIDE;
if (insideRootTag && ("stream:stream>".equals(head.toString()) || ("?xml>".equals(head.toString())) || ("flash:stream>".equals(head.toString())))) {
// Found closing stream:stream
int end = buffer.length() - readChar + (i + 1);
// Skip LF, CR and other "weird" characters that could appear
while (startLastMsg < end && '<' != buffer.charAt(startLastMsg)) {
startLastMsg++;
}
String msg = buffer.substring(startLastMsg, end);
foundMsg(msg);
startLastMsg = end;
}
insideRootTag = false;
} else if (ch == '/') {
status = XMLLightweightParser.VERIFY_CLOSE_TAG;
}
} else if (status == XMLLightweightParser.HEAD) {
if (ch == ' ' || ch == '>') {
// Append > to head to allow searching </tag>
head.append('>');
if (ch == '>')
status = XMLLightweightParser.OUTSIDE;
else
status = XMLLightweightParser.INSIDE;
insideRootTag = true;
insideChildrenTag = false;
continue;
} else if (ch == '/' && head.length() > 0) {
status = XMLLightweightParser.VERIFY_CLOSE_TAG;
depth--;
}
head.append(ch);
} else if (status == XMLLightweightParser.INIT) {
if (ch == '<') {
status = XMLLightweightParser.HEAD;
depth = 1;
} else {
startLastMsg++;
}
} else if (status == XMLLightweightParser.OUTSIDE) {
if (ch == '<') {
status = XMLLightweightParser.PRETAIL;
cdataOffset = 1;
insideChildrenTag = true;
}
}
}
if (head.length() > 0 && ("/stream:stream>".equals(head.toString()) || ("/flash:stream>".equals(head.toString())))) {
// Found closing stream:stream
foundMsg("</stream:stream>");
}
}
use of java.nio.CharBuffer in project hudson-2.x by hudson.
the class Util method rawEncode.
/**
* Encode a single path component for use in an HTTP URL.
* Escapes all non-ASCII, general unsafe (space and "#%<>[\]^`{|}~)
* and HTTP special characters (/;:?) as specified in RFC1738.
* (so alphanumeric and !@$&*()-_=+',. are not encoded)
* Note that slash(/) is encoded, so the given string should be a
* single path component used in constructing a URL.
* Method name inspired by PHP's rawurlencode.
*/
public static String rawEncode(String s) {
boolean escaped = false;
StringBuilder out = null;
CharsetEncoder enc = null;
CharBuffer buf = null;
char c;
for (int i = 0, m = s.length(); i < m; i++) {
c = s.charAt(i);
if (c > 122 || uriMap[c]) {
if (!escaped) {
out = new StringBuilder(i + (m - i) * 3);
out.append(s.substring(0, i));
enc = Charset.forName("UTF-8").newEncoder();
buf = CharBuffer.allocate(1);
escaped = true;
}
// 1 char -> UTF8
buf.put(0, c);
buf.rewind();
try {
ByteBuffer bytes = enc.encode(buf);
while (bytes.hasRemaining()) {
byte b = bytes.get();
out.append('%');
out.append(toDigit((b >> 4) & 0xF));
out.append(toDigit(b & 0xF));
}
} catch (CharacterCodingException ex) {
}
} else if (escaped) {
out.append(c);
}
}
return escaped ? out.toString() : s;
}
use of java.nio.CharBuffer in project Android-Terminal-Emulator by jackpal.
the class ShortcutEncryption method decrypt.
/**
* Decrypts a string encrypted using this algorithm and verifies that the
* contents have not been tampered with.
*
* @param encrypted The string to decrypt, in the format described above.
* @param keys The keys to verify and decrypt with.
* @return The decrypted data.
*
* @throws GeneralSecurityException if the data is invalid, verification fails, or an error occurs during decryption.
*/
public static String decrypt(String encrypted, Keys keys) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance(ENC_SYSTEM);
String[] data = COLON.split(encrypted);
if (data.length != 3) {
throw new GeneralSecurityException("Invalid encrypted data!");
}
String mac = data[0];
String iv = data[1];
String cipherText = data[2];
// Verify that the ciphertext and IV haven't been tampered with first
String dataToAuth = iv + ":" + cipherText;
if (!computeMac(dataToAuth, keys.getMacKey()).equals(mac)) {
throw new GeneralSecurityException("Incorrect MAC!");
}
// Decrypt the ciphertext
byte[] ivBytes = decodeBase64(iv);
cipher.init(Cipher.DECRYPT_MODE, keys.getEncKey(), new IvParameterSpec(ivBytes));
byte[] bytes = cipher.doFinal(decodeBase64(cipherText));
// Decode the plaintext bytes into a String
CharsetDecoder decoder = Charset.defaultCharset().newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPORT);
decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
/*
* We are coding UTF-8 (guaranteed to be the default charset on
* Android) to Java chars (UTF-16, 2 bytes per char). For valid UTF-8
* sequences, then:
* 1 byte in UTF-8 (US-ASCII) -> 1 char in UTF-16
* 2-3 bytes in UTF-8 (BMP) -> 1 char in UTF-16
* 4 bytes in UTF-8 (non-BMP) -> 2 chars in UTF-16 (surrogate pair)
* The decoded output is therefore guaranteed to fit into a char
* array the same length as the input byte array.
*/
CharBuffer out = CharBuffer.allocate(bytes.length);
CoderResult result = decoder.decode(ByteBuffer.wrap(bytes), out, true);
if (result.isError()) {
/* The input was supposed to be the result of encrypting a String,
* so something is very wrong if it cannot be decoded into one! */
throw new GeneralSecurityException("Corrupt decrypted data!");
}
decoder.flush(out);
return out.flip().toString();
}
use of java.nio.CharBuffer in project Android-Terminal-Emulator by jackpal.
the class TerminalEmulator method handleUTF8Sequence.
private boolean handleUTF8Sequence(byte b) {
if (mUTF8ToFollow == 0 && (b & 0x80) == 0) {
// ASCII character -- we don't need to handle this
return false;
}
if (mUTF8ToFollow > 0) {
if ((b & 0xc0) != 0x80) {
/* Not a UTF-8 continuation byte (doesn't begin with 0b10)
Replace the entire sequence with the replacement char */
mUTF8ToFollow = 0;
mUTF8ByteBuffer.clear();
emit(UNICODE_REPLACEMENT_CHAR);
/* The Unicode standard (section 3.9, definition D93) requires
* that we now attempt to process this byte as though it were
* the beginning of another possibly-valid sequence */
return handleUTF8Sequence(b);
}
mUTF8ByteBuffer.put(b);
if (--mUTF8ToFollow == 0) {
// Sequence complete -- decode and emit it
ByteBuffer byteBuf = mUTF8ByteBuffer;
CharBuffer charBuf = mInputCharBuffer;
CharsetDecoder decoder = mUTF8Decoder;
byteBuf.rewind();
decoder.reset();
decoder.decode(byteBuf, charBuf, true);
decoder.flush(charBuf);
char[] chars = charBuf.array();
if (chars[0] >= 0x80 && chars[0] <= 0x9f) {
/* Sequence decoded to a C1 control character which needs
to be sent through process() again */
process((byte) chars[0], false);
} else {
emit(chars);
}
byteBuf.clear();
charBuf.clear();
}
} else {
if ((b & 0xe0) == 0xc0) {
// 0b110 -- two-byte sequence
mUTF8ToFollow = 1;
} else if ((b & 0xf0) == 0xe0) {
// 0b1110 -- three-byte sequence
mUTF8ToFollow = 2;
} else if ((b & 0xf8) == 0xf0) {
// 0b11110 -- four-byte sequence
mUTF8ToFollow = 3;
} else {
// Not a valid UTF-8 sequence start -- replace this char
emit(UNICODE_REPLACEMENT_CHAR);
return true;
}
mUTF8ByteBuffer.put(b);
}
return true;
}
Aggregations