Search in sources :

Example 51 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project j2objc by google.

the class UnsupportedCharsetExceptionTest method testConstructor.

public void testConstructor() {
    UnsupportedCharsetException ex = new UnsupportedCharsetException("impossible");
    assertTrue(ex instanceof IllegalArgumentException);
    assertNull(ex.getCause());
    assertEquals(ex.getCharsetName(), "impossible");
    assertTrue(ex.getMessage().indexOf("impossible") != -1);
    ex = new UnsupportedCharsetException("ascii");
    assertNull(ex.getCause());
    assertEquals(ex.getCharsetName(), "ascii");
    assertTrue(ex.getMessage().indexOf("ascii") != -1);
    ex = new UnsupportedCharsetException("");
    assertNull(ex.getCause());
    assertEquals(ex.getCharsetName(), "");
    ex.getMessage();
    ex = new UnsupportedCharsetException(null);
    assertNull(ex.getCause());
    assertNull(ex.getCharsetName());
    assertTrue(ex.getMessage().indexOf("null") != -1);
}
Also used : UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException)

Example 52 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project j2objc by google.

the class URLEncoder method encode.

/**
 * Translates a string into {@code application/x-www-form-urlencoded}
 * format using a specific encoding scheme. This method uses the
 * supplied encoding scheme to obtain the bytes for unsafe
 * characters.
 * <p>
 * <em><strong>Note:</strong> The <a href=
 * "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
 * World Wide Web Consortium Recommendation</a> states that
 * UTF-8 should be used. Not doing so may introduce
 * incompatibilities.</em>
 *
 * @param   s   {@code String} to be translated.
 * @param   enc   The name of a supported
 *    <a href="../lang/package-summary.html#charenc">character
 *    encoding</a>.
 * @return  the translated {@code String}.
 * @exception  UnsupportedEncodingException
 *             If the named encoding is not supported
 * @see URLDecoder#decode(java.lang.String, java.lang.String)
 * @since 1.4
 */
public static String encode(String s, String enc) throws UnsupportedEncodingException {
    boolean needToChange = false;
    StringBuffer out = new StringBuffer(s.length());
    Charset charset;
    CharArrayWriter charArrayWriter = new CharArrayWriter();
    if (enc == null)
        throw new NullPointerException("charsetName");
    try {
        charset = Charset.forName(enc);
    } catch (IllegalCharsetNameException e) {
        throw new UnsupportedEncodingException(enc);
    } catch (UnsupportedCharsetException e) {
        throw new UnsupportedEncodingException(enc);
    }
    for (int i = 0; i < s.length(); ) {
        int c = (int) s.charAt(i);
        // System.out.println("Examining character: " + c);
        if (dontNeedEncoding.get(c)) {
            if (c == ' ') {
                c = '+';
                needToChange = true;
            }
            // System.out.println("Storing: " + c);
            out.append((char) c);
            i++;
        } else {
            // convert to external encoding before hex conversion
            do {
                charArrayWriter.write(c);
                /*
                     * If this character represents the start of a Unicode
                     * surrogate pair, then pass in two characters. It's not
                     * clear what should be done if a bytes reserved in the
                     * surrogate pairs range occurs outside of a legal
                     * surrogate pair. For now, just treat it as if it were
                     * any other character.
                     */
                if (c >= 0xD800 && c <= 0xDBFF) {
                    /*
                          System.out.println(Integer.toHexString(c)
                          + " is high surrogate");
                        */
                    if ((i + 1) < s.length()) {
                        int d = (int) s.charAt(i + 1);
                        /*
                              System.out.println("\tExamining "
                              + Integer.toHexString(d));
                            */
                        if (d >= 0xDC00 && d <= 0xDFFF) {
                            /*
                                  System.out.println("\t"
                                  + Integer.toHexString(d)
                                  + " is low surrogate");
                                */
                            charArrayWriter.write(d);
                            i++;
                        }
                    }
                }
                i++;
            } while (i < s.length() && !dontNeedEncoding.get((c = (int) s.charAt(i))));
            charArrayWriter.flush();
            String str = new String(charArrayWriter.toCharArray());
            byte[] ba = str.getBytes(charset);
            for (int j = 0; j < ba.length; j++) {
                out.append('%');
                char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
                // the hex value if ch is a letter.
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
                ch = Character.forDigit(ba[j] & 0xF, 16);
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
            }
            charArrayWriter.reset();
            needToChange = true;
        }
    }
    return (needToChange ? out.toString() : s);
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CharArrayWriter(java.io.CharArrayWriter)

Example 53 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project tomcat by apache.

the class TestRequest method doTestGetReader.

private void doTestGetReader(String userAgentCharacterEncoding, boolean expect200) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Tomcat.addServlet(ctx, "servlet", new Bug61264GetReaderServlet());
    ctx.addServletMappingDecoded("/", "servlet");
    tomcat.start();
    Charset charset = StandardCharsets.ISO_8859_1;
    try {
        charset = Charset.forName(userAgentCharacterEncoding);
    } catch (UnsupportedCharsetException e) {
    // Ignore - use default set above
    }
    byte[] body = "Test".getBytes(charset);
    ByteChunk bc = new ByteChunk();
    Map<String, List<String>> reqHeaders = new HashMap<>();
    reqHeaders.put("Content-Type", Arrays.asList(new String[] { "text/plain;charset=" + userAgentCharacterEncoding }));
    int rc = postUrl(body, "http://localhost:" + getPort() + "/", bc, reqHeaders, null);
    if (expect200) {
        Assert.assertEquals(200, rc);
    } else {
        Assert.assertEquals(500, rc);
    }
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) HashMap(java.util.HashMap) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Charset(java.nio.charset.Charset) ArrayList(java.util.ArrayList) List(java.util.List)

Example 54 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project ceylon-compiler by ceylon.

the class BaseFileManager method decode.

public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
    String encodingName = getEncodingName();
    CharsetDecoder decoder;
    try {
        decoder = getDecoder(encodingName, ignoreEncodingErrors);
    } catch (IllegalCharsetNameException e) {
        log.error("unsupported.encoding", encodingName);
        return (CharBuffer) CharBuffer.allocate(1).flip();
    } catch (UnsupportedCharsetException e) {
        log.error("unsupported.encoding", encodingName);
        return (CharBuffer) CharBuffer.allocate(1).flip();
    }
    // slightly overestimate the buffer size to avoid reallocation.
    float factor = decoder.averageCharsPerByte() * 0.8f + decoder.maxCharsPerByte() * 0.2f;
    CharBuffer dest = CharBuffer.allocate(10 + (int) (inbuf.remaining() * factor));
    while (true) {
        CoderResult result = decoder.decode(inbuf, dest, true);
        dest.flip();
        if (result.isUnderflow()) {
            // make sure there is at least one extra character
            if (dest.limit() == dest.capacity()) {
                dest = CharBuffer.allocate(dest.capacity() + 1).put(dest);
                dest.flip();
            }
            return dest;
        } else if (result.isOverflow()) {
            // buffer too small; expand
            int newCapacity = 10 + dest.capacity() + (int) (inbuf.remaining() * decoder.maxCharsPerByte());
            dest = CharBuffer.allocate(newCapacity).put(dest);
        } else if (result.isMalformed() || result.isUnmappable()) {
            // report coding error (warn only pre 1.5)
            if (!getSource().allowEncodingErrors()) {
                log.error(new SimpleDiagnosticPosition(dest.limit()), "illegal.char.for.encoding", charset == null ? encodingName : charset.name());
            } else {
                log.warning(new SimpleDiagnosticPosition(dest.limit()), "illegal.char.for.encoding", charset == null ? encodingName : charset.name());
            }
            // skip past the coding error
            inbuf.position(inbuf.position() + result.length());
            // undo the flip() to prepare the output buffer
            // for more translation
            dest.position(dest.limit());
            dest.limit(dest.capacity());
            // backward compatible
            dest.put((char) 0xfffd);
        } else {
            throw new AssertionError(result);
        }
    }
// unreached
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) CharsetDecoder(java.nio.charset.CharsetDecoder) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) CharBuffer(java.nio.CharBuffer) SimpleDiagnosticPosition(com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition) CoderResult(java.nio.charset.CoderResult)

Example 55 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project RoboZombie by sahan.

the class EntityUtils method toString.

/**
 * Get the entity content as a String, using the provided default character set
 * if none is found in the entity.
 * If defaultCharset is null, the default "ISO-8859-1" is used.
 *
 * @param entity must not be null
 * @param defaultCharset character set to be applied if none found in the entity
 * @return the entity content as a String. May be null if
 *   {@link HttpEntity#getContent()} is null.
 * @throws ParseException if header elements cannot be deserialized
 * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
 * @throws IOException if an error occurs reading the input stream
 */
public static String toString(final HttpEntity entity, final Charset defaultCharset) throws IOException, ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    InputStream instream = entity.getContent();
    if (instream == null) {
        return null;
    }
    try {
        if (entity.getContentLength() > Integer.MAX_VALUE) {
            throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
        }
        int i = (int) entity.getContentLength();
        if (i < 0) {
            i = 4096;
        }
        Charset charset = null;
        try {
            ContentType contentType = ContentType.getOrDefault(entity);
            charset = contentType.getCharset();
        } catch (UnsupportedCharsetException ex) {
            throw new UnsupportedEncodingException(ex.getMessage());
        }
        if (charset == null) {
            charset = defaultCharset;
        }
        if (charset == null) {
            charset = HTTP.DEF_CONTENT_CHARSET;
        }
        Reader reader = new InputStreamReader(instream, charset);
        CharArrayBuffer buffer = new CharArrayBuffer(i);
        char[] tmp = new char[1024];
        int l;
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
        return buffer.toString();
    } finally {
        instream.close();
    }
}
Also used : ContentType(org.apache.http42.entity.ContentType) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) CharArrayBuffer(org.apache.http.util.CharArrayBuffer) Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader)

Aggregations

UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)116 Charset (java.nio.charset.Charset)55 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)43 IOException (java.io.IOException)35 File (java.io.File)11 ByteBuffer (java.nio.ByteBuffer)11 InputStream (java.io.InputStream)10 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10 CoreException (org.eclipse.core.runtime.CoreException)10 CharacterCodingException (java.nio.charset.CharacterCodingException)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 HashMap (java.util.HashMap)7 MediaType (okhttp3.MediaType)7 Request (okhttp3.Request)7 Response (okhttp3.Response)7 ResponseBody (okhttp3.ResponseBody)7 Buffer (okio.Buffer)7 BufferedSource (okio.BufferedSource)7 InputStreamReader (java.io.InputStreamReader)6 OutputStream (java.io.OutputStream)6