Search in sources :

Example 26 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project SmartAndroidSource by jaychou2012.

the class DataUtil method getCharsetFromContentType.

/**
 * Parse out a charset from a content type header. If the charset is not
 * supported, returns null (so the default will kick in.)
 *
 * @param contentType
 *            e.g. "text/html; charset=EUC-JP"
 * @return "EUC-JP", or null if not found. Charset is trimmed and
 *         uppercased.
 */
static String getCharsetFromContentType(String contentType) {
    if (contentType == null)
        return null;
    Matcher m = charsetPattern.matcher(contentType);
    if (m.find()) {
        String charset = m.group(1).trim();
        charset = charset.replace("charset=", "");
        if (charset.isEmpty())
            return null;
        try {
            if (Charset.isSupported(charset))
                return charset;
            charset = charset.toUpperCase(Locale.ENGLISH);
            if (Charset.isSupported(charset))
                return charset;
        } catch (IllegalCharsetNameException e) {
            // default
            return null;
        }
    }
    return null;
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) Matcher(java.util.regex.Matcher)

Example 27 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project Asqatasun by Asqatasun.

the class CSSJsoupPhlocContentAdapterImpl method createNewExternalStyleSheet.

/**
 * @param cssAbsolutePath
 * @return
 */
private StylesheetContent createNewExternalStyleSheet(String cssAbsolutePath) {
    LOGGER.debug("createNewExternalStyleSheet " + cssAbsolutePath);
    String cssSourceCode;
    try {
        cssSourceCode = HttpRequestHandler.getInstance().getHttpContent(cssAbsolutePath);
    } catch (URISyntaxException ex) {
        LOGGER.debug("the resource " + cssAbsolutePath + " can't be retrieved : URISyntaxException");
        cssSourceCode = CSS_ON_ERROR;
    } catch (UnknownHostException uhe) {
        LOGGER.debug("the resource " + cssAbsolutePath + " can't be retrieved : UnknownHostException");
        cssSourceCode = CSS_ON_ERROR;
    } catch (IOException ioe) {
        LOGGER.debug("the resource " + cssAbsolutePath + " can't be retrieved : IOException");
        try {
            cssSourceCode = FileUtils.readFileToString(new File(cssAbsolutePath));
        } catch (IOException ioe2) {
            LOGGER.debug("the resource " + cssAbsolutePath + " can't be retrieved : IOException");
            cssSourceCode = CSS_ON_ERROR;
        }
    } catch (IllegalCharsetNameException icne) {
        LOGGER.debug("the resource " + cssAbsolutePath + " can't be retrieved : IllegalCharsetNameException");
        cssSourceCode = CSS_ON_ERROR;
    } catch (IllegalStateException ise) {
        LOGGER.debug("the resource " + cssAbsolutePath + " can't be retrieved : IllegalStateException");
        cssSourceCode = CSS_ON_ERROR;
    }
    if (StringUtils.isBlank(cssSourceCode)) {
        LOGGER.debug("the resource " + cssAbsolutePath + " has an empty content");
        cssSourceCode = CSS_ON_ERROR;
    }
    StylesheetContent cssContent = getContentDataService().getStylesheetContent(new Date(), cssAbsolutePath, getSSP(), cssSourceCode, 200);
    cssContent.setAudit(getSSP().getAudit());
    externalCssSet.add(cssContent);
    // Some stylesheet may be retrieved during the adaptation. In this case
    // these new css are added "manually" to the externalCssRetriever which
    // is supposed to request the bdd once at the beginning of the adapting
    // phasis.
    externalCSSRetriever.addNewStylesheetContent(getSSP(), cssContent);
    return cssContent;
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) StylesheetContent(org.asqatasun.entity.audit.StylesheetContent) UnknownHostException(java.net.UnknownHostException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) File(java.io.File)

Example 28 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException 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 29 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException in project guava by hceylan.

the class MediaTypeTest method testGetCharset_illegalCharset.

public void testGetCharset_illegalCharset() {
    MediaType mediaType = MediaType.parse("text/plain; charset=\"!@#$%^&*()\"");
    try {
        mediaType.charset();
        fail();
    } catch (IllegalCharsetNameException expected) {
    }
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) MediaType(com.google.common.net.MediaType)

Example 30 with IllegalCharsetNameException

use of java.nio.charset.IllegalCharsetNameException 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)

Aggregations

IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)69 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)44 Charset (java.nio.charset.Charset)34 IOException (java.io.IOException)13 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10 File (java.io.File)9 ByteBuffer (java.nio.ByteBuffer)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 InputStream (java.io.InputStream)6 CharacterCodingException (java.nio.charset.CharacterCodingException)6 CoreException (org.eclipse.core.runtime.CoreException)6 IStatus (org.eclipse.core.runtime.IStatus)6 Status (org.eclipse.core.runtime.Status)6 HistoricallyNamedCharset (sun.nio.cs.HistoricallyNamedCharset)6 CharsetEncoder (java.nio.charset.CharsetEncoder)5 UnmappableCharacterException (java.nio.charset.UnmappableCharacterException)5 SequenceInputStream (java.io.SequenceInputStream)4 XmlPullParserException (org.codehaus.plexus.util.xml.pull.XmlPullParserException)4 CharArrayWriter (java.io.CharArrayWriter)3 FileInputStream (java.io.FileInputStream)3