Search in sources :

Example 81 with CoderResult

use of java.nio.charset.CoderResult in project grails-core by grails.

the class BoundedCharsAsEncodedBytesCounter method update.

public void update(char[] buf, int off, int len) {
    if (calculationActive && len > 0) {
        try {
            CharBuffer cb = CharBuffer.wrap(buf, off, len);
            ce.reset();
            CoderResult cr = ce.encode(cb, bb, true);
            if (!cr.isUnderflow()) {
                terminateCalculation();
                return;
            }
            cr = ce.flush(bb);
            if (!cr.isUnderflow()) {
                terminateCalculation();
                return;
            }
        } catch (BufferOverflowException e) {
            terminateCalculation();
        } catch (Exception x) {
            terminateCalculation();
        }
    }
}
Also used : CharBuffer(java.nio.CharBuffer) BufferOverflowException(java.nio.BufferOverflowException) BufferOverflowException(java.nio.BufferOverflowException) IOException(java.io.IOException) CoderResult(java.nio.charset.CoderResult)

Example 82 with CoderResult

use of java.nio.charset.CoderResult in project grails-core by grails.

the class StreamByteBuffer method readAsString.

public String readAsString(Charset charset) throws CharacterCodingException {
    int unreadSize = totalBytesUnread();
    if (unreadSize > 0) {
        CharsetDecoder decoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE);
        CharBuffer charbuffer = CharBuffer.allocate(unreadSize);
        ByteBuffer buf = null;
        while (prepareRead() != -1) {
            buf = currentReadChunk.readToNioBuffer();
            boolean endOfInput = (prepareRead() == -1);
            CoderResult result = decoder.decode(buf, charbuffer, endOfInput);
            if (endOfInput) {
                if (!result.isUnderflow()) {
                    result.throwException();
                }
            }
        }
        CoderResult result = decoder.flush(charbuffer);
        if (buf.hasRemaining()) {
            throw new IllegalStateException("There's a bug here, buffer wasn't read fully.");
        }
        if (!result.isUnderflow()) {
            result.throwException();
        }
        charbuffer.flip();
        String str;
        if (charbuffer.hasArray()) {
            int len = charbuffer.remaining();
            char[] ch = charbuffer.array();
            if (len != ch.length) {
                ch = (char[]) GrailsArrayUtils.subarray(ch, 0, len);
            }
            str = StringCharArrayAccessor.createString(ch);
        } else {
            str = charbuffer.toString();
        }
        return str;
    }
    return null;
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) CharBuffer(java.nio.CharBuffer) ByteBuffer(java.nio.ByteBuffer) CoderResult(java.nio.charset.CoderResult)

Example 83 with CoderResult

use of java.nio.charset.CoderResult in project rest.li by linkedin.

the class BufferChain method putUtf8CString.

/**
 * Put string into buffer chain as UTF-8 encoded null-terminated string.
 *
 * @param value provides the string to put.
 * @return {@code this}.
 */
public BufferChain putUtf8CString(String value) throws CharacterCodingException {
    reserve(value.length() * 4);
    _encoder.reset();
    CoderResult result = _encoder.encode(CharBuffer.wrap(value), _currentBuffer, true);
    if (result.isError()) {
        result.throwException();
    }
    _encoder.flush(_currentBuffer);
    put(ZERO_BYTE);
    return this;
}
Also used : CoderResult(java.nio.charset.CoderResult)

Example 84 with CoderResult

use of java.nio.charset.CoderResult in project carat by amplab.

the class FastXmlSerializer method flush.

public void flush() throws IOException {
    // Log.i("PackageManager", "flush mPos=" + mPos);
    if (mPos > 0) {
        if (mOutputStream != null) {
            CharBuffer charBuffer = CharBuffer.wrap(mText, 0, mPos);
            CoderResult result = mCharset.encode(charBuffer, mBytes, true);
            while (true) {
                if (result.isError()) {
                    throw new IOException(result.toString());
                } else if (result.isOverflow()) {
                    flushBytes();
                    result = mCharset.encode(charBuffer, mBytes, true);
                    continue;
                }
                break;
            }
            flushBytes();
            mOutputStream.flush();
        } else {
            mWriter.write(mText, 0, mPos);
            mWriter.flush();
        }
        mPos = 0;
    }
}
Also used : CharBuffer(java.nio.CharBuffer) IOException(java.io.IOException) CoderResult(java.nio.charset.CoderResult)

Example 85 with CoderResult

use of java.nio.charset.CoderResult 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();
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) GeneralSecurityException(java.security.GeneralSecurityException) CharBuffer(java.nio.CharBuffer) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) CoderResult(java.nio.charset.CoderResult)

Aggregations

CoderResult (java.nio.charset.CoderResult)188 CharBuffer (java.nio.CharBuffer)121 ByteBuffer (java.nio.ByteBuffer)70 CharsetDecoder (java.nio.charset.CharsetDecoder)40 IOException (java.io.IOException)33 CharacterCodingException (java.nio.charset.CharacterCodingException)30 CharsetEncoder (java.nio.charset.CharsetEncoder)25 Charset (java.nio.charset.Charset)15 ArrayDecoder (sun.nio.cs.ArrayDecoder)7 ArrayEncoder (sun.nio.cs.ArrayEncoder)7 JSONException (com.alibaba.fastjson.JSONException)3 BufferUnderflowException (java.nio.BufferUnderflowException)3 CloseReason (jakarta.websocket.CloseReason)2 UncheckedIOException (java.io.UncheckedIOException)2 BufferOverflowException (java.nio.BufferOverflowException)2 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)2 UnmappableCharacterException (java.nio.charset.UnmappableCharacterException)2 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)2 CloseReason (javax.websocket.CloseReason)2 InvalidConfigurationException (org.bukkit.configuration.InvalidConfigurationException)2