Java Code Examples for java.nio.charset.CharacterCodingException

The following examples show how to use java.nio.charset.CharacterCodingException. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
private boolean writeBuffer(final ByteBuffer buffer, final IoCallback callback) {
    StringBuilder builder = new StringBuilder();
    try {
        builder.append(charsetDecoder.decode(buffer));
    } catch (CharacterCodingException e) {
        callback.onException(exchange, this, e);
        return false;
    }
    String data = builder.toString();
    writer.write(data);
    if (writer.checkError()) {
        callback.onException(exchange, this, new IOException());
        return false;
    }
    return true;
}
 
Example 2
Source Project: ion-java   Source File: _Private_Utils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Decodes a byte sequence into a string, given a {@link Charset}.
 * <p>
 * This method is preferred to {@link Charset#decode(ByteBuffer)} and
 * {@link String#String(byte[], Charset)} (<em>etc.</em>)
 * since those methods will replace or ignore bad input, and here we throw
 * an exception.
 *
 * @param bytes the data to decode.
 *
 * @return the decoded string, not null.
 *
 * @throws IonException if there's a {@link CharacterCodingException}.
 */
public static String decode(byte[] bytes, Charset charset)
{
    CharsetDecoder decoder = charset.newDecoder();
    try
    {
        CharBuffer buffer = decoder.decode(ByteBuffer.wrap(bytes));
        return buffer.toString();
    }
    catch (CharacterCodingException e)
    {
        String message =
            "Input is not valid " + charset.displayName() + " data";
        throw new IonException(message, e);
    }
}
 
Example 3
Source Project: qpid-proton-j   Source File: CompositeReadableBufferTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEqualsOnSameBackingBuffer() throws CharacterCodingException {
    CompositeReadableBuffer buffer1 = new CompositeReadableBuffer();
    CompositeReadableBuffer buffer2 = new CompositeReadableBuffer();
    CompositeReadableBuffer buffer3 = new CompositeReadableBuffer();

    byte[] data = new byte[] {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};

    buffer1.append(data);
    buffer2.append(data);
    buffer3.append(data);

    assertEquals(buffer1, buffer2);
    assertEquals(buffer2, buffer3);
    assertEquals(buffer3, buffer1);

    assertEquals(0, buffer1.position());
    assertEquals(0, buffer2.position());
    assertEquals(0, buffer3.position());
}
 
Example 4
Source Project: j2objc   Source File: OldCharset_AbstractTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test_CodecDynamic () throws CharacterCodingException {
    encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
    decoder.onMalformedInput(CodingErrorAction.REPORT);
    CharBuffer inputCB = CharBuffer.allocate(65536);
    for (int code = 32; code <= 65533; ++code) {
        // icu4c seems to accept any surrogate as a sign that "more is coming",
        // even for charsets like US-ASCII. http://b/10310751
        if (code >= 0xd800 && code <= 0xdfff) {
            continue;
        }
        if (encoder.canEncode((char) code)) {
            inputCB.put((char) code);
        }
    }
    inputCB.rewind();
    ByteBuffer intermediateBB = encoder.encode(inputCB);
    inputCB.rewind();
    intermediateBB.rewind();
    CharBuffer outputCB = decoder.decode(intermediateBB);
    outputCB.rewind();
    assertEqualCBs("decode(encode(A)) must be identical with A!",
            inputCB, outputCB);
}
 
Example 5
Source Project: hbase   Source File: ParseFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
* Checks if the current index of filter string we are on is the beginning of the keyword 'SKIP'
* <p>
* @param filterStringAsByteArray filter string given by the user
* @param indexOfSkip index at which an 'S' was read
* @return true if the keyword 'SKIP' is at the current index
*/
 public static boolean checkForSkip (byte [] filterStringAsByteArray, int indexOfSkip)
   throws CharacterCodingException {

   try {
     if (filterStringAsByteArray[indexOfSkip] == ParseConstants.S &&
         filterStringAsByteArray[indexOfSkip+1] == ParseConstants.K &&
         filterStringAsByteArray[indexOfSkip+2] == ParseConstants.I &&
         filterStringAsByteArray[indexOfSkip+3] == ParseConstants.P &&
         (indexOfSkip == 0 ||
          filterStringAsByteArray[indexOfSkip-1] == ParseConstants.WHITESPACE ||
          filterStringAsByteArray[indexOfSkip-1] == ParseConstants.RPAREN ||
          filterStringAsByteArray[indexOfSkip-1] == ParseConstants.LPAREN) &&
         (filterStringAsByteArray[indexOfSkip+4] == ParseConstants.WHITESPACE ||
          filterStringAsByteArray[indexOfSkip+4] == ParseConstants.LPAREN)) {
       return true;
     } else {
       return false;
     }
   } catch (ArrayIndexOutOfBoundsException e) {
     return false;
   }
 }
 
Example 6
Source Project: secor   Source File: Message.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Message key and payload may be arbitrary binary strings, so we should make sure we don't throw
 * when logging them by using a CharsetDecoder which replaces bad data. (While in practice `new String(bytes)`
 * does the same thing, the documentation for that method leaves that behavior unspecified.)
 * Additionally, in contexts where Message.toString() will be logged at a high level (including exception
 * messages), we truncate long keys and payloads, which may be very long binary data.
 */
private String bytesToString(byte[] bytes, boolean truncate) {
    CharsetDecoder decoder = Charset.defaultCharset()
            .newDecoder()
            .onMalformedInput(CodingErrorAction.REPLACE)
            .onUnmappableCharacter(CodingErrorAction.REPLACE);
    ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
    CharBuffer charBuffer;
    try {
        charBuffer = decoder.decode(byteBuffer);
    } catch (CharacterCodingException e) {
        // Shouldn't happen due to choosing REPLACE above, but Java makes us catch it anyway.
        throw new RuntimeException(e);
    }
    String s = charBuffer.toString();
    if (truncate && s.length() > TRUNCATED_STRING_MAX_LEN) {
        return new StringBuilder().append(s, 0, TRUNCATED_STRING_MAX_LEN).append("[...]").toString();
    } else {
        return s;
    }
}
 
Example 7
Source Project: BigApp_Discuz_Android   Source File: IOUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void decode(CharsetDecoder charsetDecoder, ByteBuffer byteBuf, CharBuffer charByte) {
    try {
        CoderResult cr = charsetDecoder.decode(byteBuf, charByte, true);

        if (!cr.isUnderflow()) {
            cr.throwException();
        }

        cr = charsetDecoder.flush(charByte);

        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        // Substitution is always enabled,
        // so this shouldn't happen
        throw new JSONException(x.getMessage(), x);
    }
}
 
Example 8
Source Project: hugegraph   Source File: GremlinAPI.java    License: Apache License 2.0 6 votes vote down vote up
public String name() {
    // Get the first line of script as the name
    String firstLine = this.gremlin.split("\r\n|\r|\n", 2)[0];
    final Charset charset = Charset.forName(CHARSET);
    final byte[] bytes = firstLine.getBytes(charset);
    if (bytes.length <= MAX_NAME_LENGTH) {
        return firstLine;
    }

    /*
     * Reference https://stackoverflow.com/questions/3576754/truncating-strings-by-bytes
     */
    CharsetDecoder decoder = charset.newDecoder();
    decoder.onMalformedInput(CodingErrorAction.IGNORE);
    decoder.reset();

    ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, MAX_NAME_LENGTH);
    try {
        return decoder.decode(buffer).toString();
    } catch (CharacterCodingException e) {
        throw new HugeException("Failed to decode truncated bytes of " +
                                "gremlin first line", e);
    }
}
 
Example 9
Source Project: netbeans   Source File: DatabaseConnectionConvertor.java    License: Apache License 2.0 6 votes vote down vote up
static String decodePassword(byte[] bytes) throws CharacterCodingException {
    CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(); // NOI18N
    ByteBuffer input = ByteBuffer.wrap(bytes);
    int outputLength = (int)(bytes.length * (double)decoder.maxCharsPerByte());
    if (outputLength == 0) {
        return ""; // NOI18N
    }
    char[] chars = new char[outputLength];
    CharBuffer output = CharBuffer.wrap(chars);
    CoderResult result = decoder.decode(input, output, true);
    if (!result.isError() && !result.isOverflow()) {
        result = decoder.flush(output);
    }
    if (result.isError() || result.isOverflow()) {
        throw new CharacterCodingException();
    } else {
        return new String(chars, 0, output.position());
    }
}
 
Example 10
Source Project: sailfish-core   Source File: NTGVisitorDecode.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(String fieldName, LocalDateTime value, IFieldStructure fldStruct, boolean isDefault) {
    validateAttributesMap(fieldName, LocalDateTime.class, fldStruct);
    
    int length = getAttributeValue(fldStruct, NTGProtocolAttribute.Length.toString());
    int offset = getAttributeValue(fldStruct, NTGProtocolAttribute.Offset.toString());
    String dateTimeFormat = getAttributeValue(fldStruct, NTGProtocolAttribute.DateTimeFormat.toString());
    
    validateOffset(fieldName, accumulatedLength, offset);
    
    DateTimeFormatter dateTimeFormatter = DateTimeUtility.createFormatter(dateTimeFormat);
    byte[] array = new byte[length];
    buffer.get(array);
    try {
        String asciiDate = DECODER.get().decode(ByteBuffer.wrap(array)).toString().trim();
        TemporalAccessor dateTime = dateTimeFormatter.parse(asciiDate);
        message.addField(fieldName, DateTimeUtility.toLocalDateTime(dateTime));
        accumulatedLength += length;
    } catch (CharacterCodingException e) {
        throw new EPSCommonException("Problem with decoding the asciiDate = \"" + Arrays.toString(array) + "\"", e);
    }
}
 
Example 11
Source Project: aion   Source File: Slices.java    License: MIT License 6 votes vote down vote up
public static String decodeString(ByteBuffer src, Charset charset) {
    CharsetDecoder decoder = getDecoder(charset);
    CharBuffer dst =
            CharBuffer.allocate((int) ((double) src.remaining() * decoder.maxCharsPerByte()));
    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = decoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    return dst.flip().toString();
}
 
Example 12
public byte[] convertFromJavaString(String sourceString, Agent agent)
        throws SqlException {
    try {
        ByteBuffer buf = encoder.encode(CharBuffer.wrap(sourceString));

        if (buf.limit() == buf.capacity()) {
            // The length of the encoded representation of the string
            // matches the length of the returned buffer, so just return
            // the backing array.
            return buf.array();
        }

        // Otherwise, copy the interesting bytes into an array with the
        // correct length.
        byte[] bytes = new byte[buf.limit()];
        buf.get(bytes);
        return bytes;
    } catch (CharacterCodingException cce) {
        throw new SqlException(agent.logWriter_,
                new ClientMessageId(SQLState.CANT_CONVERT_UNICODE_TO_UTF8),
                cce);
    }
}
 
Example 13
Source Project: aws-big-data-blog   Source File: ParseReferrerBolt.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Tuple input,  BasicOutputCollector collector) {
    Record record = (Record)input.getValueByField(DefaultKinesisRecordScheme.FIELD_RECORD);
    ByteBuffer buffer = record.getData();
    String data = null; 
    try {
        data = decoder.decode(buffer).toString();
        JSONObject jsonObject = new JSONObject(data);

        String referrer = jsonObject.getString("referrer");

        int firstIndex = referrer.indexOf('.');
        int nextIndex = referrer.indexOf('.',firstIndex+1);
        collector.emit(new Values(referrer.substring(firstIndex+1,nextIndex)));

    } catch (CharacterCodingException|JSONException|IllegalStateException e) {
        LOG.error("Exception when decoding record ", e);
    }
}
 
Example 14
Source Project: hadoop-gpu   Source File: Text.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts the provided String to bytes using the
 * UTF-8 encoding. If <code>replace</code> is true, then
 * malformed input is replaced with the
 * substitution character, which is U+FFFD. Otherwise the
 * method throws a MalformedInputException.
 * @return ByteBuffer: bytes stores at ByteBuffer.array() 
 *                     and length is ByteBuffer.limit()
 */
public static ByteBuffer encode(String string, boolean replace)
  throws CharacterCodingException {
  CharsetEncoder encoder = ENCODER_FACTORY.get();
  if (replace) {
    encoder.onMalformedInput(CodingErrorAction.REPLACE);
    encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
  }
  ByteBuffer bytes = 
    encoder.encode(CharBuffer.wrap(string.toCharArray()));
  if (replace) {
    encoder.onMalformedInput(CodingErrorAction.REPORT);
    encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
  }
  return bytes;
}
 
Example 15
Source Project: datawave   Source File: EdgeKeyDecoder.java    License: Apache License 2.0 6 votes vote down vote up
public static STATS_TYPE determineStatsType(Text colFam) {
    int offset = STATS_BYTES.length + 1;
    int secondSlashIndex = 0;
    int numCharsToCheck = Math.min(offset + 1 + STATS_TYPE.getMaxLength(), colFam.getLength());
    
    // faster to just compare bytes with STATS/statsType/ for each statsType
    
    for (int i = offset; i < numCharsToCheck; i++) {
        secondSlashIndex = i;
        if (colFam.getBytes()[i] == COL_SEPARATOR_BYTE) {
            break;
        }
    }
    int count = (secondSlashIndex > offset ? secondSlashIndex - offset : offset);
    try {
        return STATS_TYPE.getStatsType(Text.decode(colFam.getBytes(), offset, count));
    } catch (CharacterCodingException e) {
        // same behavior as EdgeKey.getParts
        throw new RuntimeException("Edge key column encoding exception", e);
    }
}
 
Example 16
Source Project: Bytecoder   Source File: StringCoding.java    License: Apache License 2.0 5 votes vote down vote up
byte[] encode(byte coder, byte[] val) {
    // fastpath for ascii compatible
    if (coder == LATIN1 && isASCIICompatible &&
        !hasNegatives(val, 0, val.length)) {
        return Arrays.copyOf(val, val.length);
    }
    int len = val.length >> coder;  // assume LATIN1=0/UTF16=1;
    int en = scale(len, ce.maxBytesPerChar());
    byte[] ba = new byte[en];
    if (len == 0) {
        return ba;
    }
    if (ce instanceof ArrayEncoder) {
        int blen = (coder == LATIN1 ) ? ((ArrayEncoder)ce).encodeFromLatin1(val, 0, len, ba)
                                      : ((ArrayEncoder)ce).encodeFromUTF16(val, 0, len, ba);
        if (blen != -1) {
            return safeTrim(ba, blen, isTrusted);
        }
    }
    char[] ca = (coder == LATIN1 ) ? StringLatin1.toChars(val)
                                   : StringUTF16.toChars(val);
    ce.reset();
    ByteBuffer bb = ByteBuffer.wrap(ba);
    CharBuffer cb = CharBuffer.wrap(ca, 0, len);
    try {
        CoderResult cr = ce.encode(cb, bb, true);
        if (!cr.isUnderflow())
            cr.throwException();
        cr = ce.flush(bb);
        if (!cr.isUnderflow())
            cr.throwException();
    } catch (CharacterCodingException x) {
        // Substitution is always enabled,
        // so this shouldn't happen
        throw new Error(x);
    }
    return safeTrim(ba, bb.position(), isTrusted);
}
 
Example 17
Source Project: openjdk-jdk8u   Source File: StringCoding.java    License: GNU General Public License v2.0 5 votes vote down vote up
static byte[] encode(Charset cs, char[] ca, int off, int len) {
    CharsetEncoder ce = cs.newEncoder();
    int en = scale(len, ce.maxBytesPerChar());
    byte[] ba = new byte[en];
    if (len == 0)
        return ba;
    boolean isTrusted = false;
    if (System.getSecurityManager() != null) {
        if (!(isTrusted = (cs.getClass().getClassLoader0() == null))) {
            ca =  Arrays.copyOfRange(ca, off, off + len);
            off = 0;
        }
    }
    ce.onMalformedInput(CodingErrorAction.REPLACE)
      .onUnmappableCharacter(CodingErrorAction.REPLACE)
      .reset();
    if (ce instanceof ArrayEncoder) {
        int blen = ((ArrayEncoder)ce).encode(ca, off, len, ba);
        return safeTrim(ba, blen, cs, isTrusted);
    } else {
        ByteBuffer bb = ByteBuffer.wrap(ba);
        CharBuffer cb = CharBuffer.wrap(ca, off, len);
        try {
            CoderResult cr = ce.encode(cb, bb, true);
            if (!cr.isUnderflow())
                cr.throwException();
            cr = ce.flush(bb);
            if (!cr.isUnderflow())
                cr.throwException();
        } catch (CharacterCodingException x) {
            throw new Error(x);
        }
        return safeTrim(ba, bb.position(), cs, isTrusted);
    }
}
 
Example 18
Source Project: datawave   Source File: TextUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts a UTF-8 encoded byte array back into a String.
 *
 * @param bytes
 * @return string
 */
public static String fromUtf8(byte[] bytes) {
    try {
        return Text.decode(bytes);
    } catch (CharacterCodingException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 19
private void convertCharArray() {
    try {

        // Possible optimization of directly converting into the CDR buffer.
        // However, that means the CDR code would have to reserve
        // a 4 byte string length ahead of time, and we'd need a
        // confusing partial conversion scheme for when we couldn't
        // fit everything in the buffer but needed to know the
        // converted length before proceeding due to fragmentation.
        // Then there's the issue of the chunking code.
        //
        // For right now, this is less messy and basic tests don't
        // show more than a 1 ms penalty worst case.  Less than a
        // factor of 2 increase.

        // Convert the characters
        buffer = ctb.encode(CharBuffer.wrap(chars,0,numChars));

        // ByteBuffer returned by the encoder will set its limit
        // to byte immediately after the last written byte.
        numBytes = buffer.limit();

    } catch (IllegalStateException ise) {
        // an encoding operation is already in progress
        throw wrapper.ctbConverterFailure( ise ) ;
    } catch (MalformedInputException mie) {
        // There were illegal Unicode char pairs
        throw wrapper.badUnicodePair( mie ) ;
    } catch (UnmappableCharacterException uce) {
        // A character doesn't map to the desired code set
        // CORBA formal 00-11-03.
        throw omgWrapper.charNotInCodeset( uce ) ;
    } catch (CharacterCodingException cce) {
        // If this happens, then some other encoding error occured
        throw wrapper.ctbConverterFailure( cce ) ;
    }
}
 
Example 20
Source Project: qpid-broker-j   Source File: TypedBytesContentReader.java    License: Apache License 2.0 5 votes vote down vote up
public String readLengthPrefixedUTF() throws TypedBytesFormatException
{
    try
    {
        short length = readShortImpl();
        if(length == 0)
        {
            return "";
        }
        else
        {
            _charsetDecoder.reset();
            ByteBuffer encodedString = _data.slice();
            encodedString.limit(length);
            _data.position(_data.position()+length);
            CharBuffer string = _charsetDecoder.decode(encodedString);

            return string.toString();
        }
    }
    catch(CharacterCodingException e)
    {
        TypedBytesFormatException jmse = new TypedBytesFormatException("Error decoding byte stream as a UTF8 string: " + e);
        jmse.initCause(e);
        throw jmse;
    }
}
 
Example 21
/**
 * @see org.jetel.data.DataField#toByteBuffer(org.jetel.util.bytes.CloverBuffer, java.nio.charset.CharsetEncoder, int)
 */
@Override
public int toByteBuffer(CloverBuffer dataBuffer, CharsetEncoder encoder, int maxLength)
		throws CharacterCodingException {
	if (isValid()) {
		return dataField.toByteBuffer(dataBuffer, encoder, maxLength);
	} else {
		throw new DataFieldInvalidStateException();
	}
}
 
Example 22
/**
 * Writes data into formatter and sets byte and record counters.
 * 
 * @param record
 * @throws IOException
 */
private final void writeRecord2CurrentTarget(DataRecord record) throws IOException {
	try {
		int size = currentFormatter.write(record);
		incrementCounters(size);
	} catch (RuntimeException e) {
		if (e.getCause() instanceof CharacterCodingException) {
			throw new IOException("Converting exception in the record: " + counter + ". ", e);
		} else {
			throw e;
		}
	}
}
 
Example 23
Source Project: qpid-jms   Source File: AmqpReadableBufferTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReadString() throws CharacterCodingException {
    String testString = "test-string-1";
    byte[] asUtf8bytes = testString.getBytes(StandardCharsets.UTF_8);
    ByteBuf byteBuffer = Unpooled.wrappedBuffer(asUtf8bytes);

    AmqpReadableBuffer buffer = new AmqpReadableBuffer(byteBuffer);

    assertEquals(testString, buffer.readString(StandardCharsets.UTF_8.newDecoder()));
}
 
Example 24
/**
 * @see org.jetel.data.DataField#fromByteBuffer(java.nio.ByteBuffer, java.nio.charset.CharsetDecoder)
 */
@Deprecated
@Override
public void fromByteBuffer(ByteBuffer dataBuffer, CharsetDecoder decoder) throws CharacterCodingException {
	dataField.fromByteBuffer(dataBuffer, decoder);
	needsToBeLoaded = false;
}
 
Example 25
Source Project: etherjar   Source File: StringType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String decode(HexData data) {
    ByteBuffer buffer = ByteBuffer.wrap(
            DynamicBytesType.DEFAULT.decode(data));

    try {
        return UTF8_CHARSET.newDecoder().decode(buffer).toString();
    } catch (CharacterCodingException e) {
        throw new RuntimeException(
                "Incorrect 'UTF-8' character encoding: " + data, e);
    }
}
 
Example 26
Source Project: AndroidComponentPlugin   Source File: StringCoding.java    License: Apache License 2.0 5 votes vote down vote up
char[] decode(byte[] ba, int off, int len) {
    int en = scale(len, cd.maxCharsPerByte());
    char[] ca = new char[en];
    if (len == 0)
        return ca;
    if (cd instanceof ArrayDecoder) {
        int clen = ((ArrayDecoder)cd).decode(ba, off, len, ca);
        return safeTrim(ca, clen, cs, isTrusted);
    } else {
        cd.reset();
        ByteBuffer bb = ByteBuffer.wrap(ba, off, len);
        CharBuffer cb = CharBuffer.wrap(ca);
        try {
            CoderResult cr = cd.decode(bb, cb, true);
            if (!cr.isUnderflow())
                cr.throwException();
            cr = cd.flush(cb);
            if (!cr.isUnderflow())
                cr.throwException();
        } catch (CharacterCodingException x) {
            // Substitution is always enabled,
            // so this shouldn't happen
            throw new Error(x);
        }
        return safeTrim(ca, cb.position(), cs, isTrusted);
    }
}
 
Example 27
Source Project: gcs   Source File: BaseParser.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Returns true if a byte sequence is valid UTF-8.
 */
private boolean isValidUTF8(byte[] input)
{
    try
    {
        utf8Decoder.decode(ByteBuffer.wrap(input));
        return true;
    }
    catch (CharacterCodingException e)
    {
        return false;
    }
}
 
Example 28
Source Project: jdk8u-dev-jdk   Source File: StringCoding.java    License: GNU General Public License v2.0 5 votes vote down vote up
byte[] encode(char[] ca, int off, int len) {
    int en = scale(len, ce.maxBytesPerChar());
    byte[] ba = new byte[en];
    if (len == 0)
        return ba;
    if (ce instanceof ArrayEncoder) {
        int blen = ((ArrayEncoder)ce).encode(ca, off, len, ba);
        return safeTrim(ba, blen, cs, isTrusted);
    } else {
        ce.reset();
        ByteBuffer bb = ByteBuffer.wrap(ba);
        CharBuffer cb = CharBuffer.wrap(ca, off, len);
        try {
            CoderResult cr = ce.encode(cb, bb, true);
            if (!cr.isUnderflow())
                cr.throwException();
            cr = ce.flush(bb);
            if (!cr.isUnderflow())
                cr.throwException();
        } catch (CharacterCodingException x) {
            // Substitution is always enabled,
            // so this shouldn't happen
            throw new Error(x);
        }
        return safeTrim(ba, bb.position(), cs, isTrusted);
    }
}
 
Example 29
private boolean check(String line, Dictionary dictionary) throws CharacterCodingException {
    int pos = line.indexOf("\t");
    String word = pos > 0 ? line.substring(0, pos) : line;
    try {
        CharSequence baseform = dictionary.lookup(word);
    } catch (StackOverflowError e) {
        // if stack overflow error occurs, we have faulty entries
        return false;
    }
    return true;
}
 
Example 30
Source Project: rya   Source File: ColumnPrefixes.java    License: Apache License 2.0 5 votes vote down vote up
private static Text concat(Text prefix, String str) {
	Text temp = new Text(prefix);

	try {
		ByteBuffer buffer = Text.encode(str, false);
		temp.append(buffer.array(), 0, buffer.limit());
	} catch (CharacterCodingException cce) {
		throw new IllegalArgumentException(cce);
	}

	return temp;
}