Example usage for java.io UnsupportedEncodingException UnsupportedEncodingException

List of usage examples for java.io UnsupportedEncodingException UnsupportedEncodingException

Introduction

In this page you can find the example usage for java.io UnsupportedEncodingException UnsupportedEncodingException.

Prototype

public UnsupportedEncodingException(String s) 

Source Link

Document

Constructs an UnsupportedEncodingException with a detail message.

Usage

From source file:com.puppycrawl.tools.checkstyle.api.Utils.java

/**
 * Loads the contents of a file in a String array using
 * the named charset./* ww w .j  a v a 2  s.  c  o m*/
 * @return the lines in the file
 * @param fileName the name of the file to load
 * @param charsetName the name of a supported charset
 * @throws IOException error occurred
 * @deprecated consider using {@link FileText} instead
 **/
@Deprecated
public static String[] getLines(String fileName, String charsetName) throws IOException {
    final List<String> lines = Lists.newArrayList();
    final FileInputStream fr = new FileInputStream(fileName);
    LineNumberReader lnr = null;
    try {
        lnr = new LineNumberReader(new InputStreamReader(fr, charsetName));
    } catch (final UnsupportedEncodingException ex) {
        fr.close();
        final String message = "unsupported charset: " + ex.getMessage();
        throw new UnsupportedEncodingException(message);
    }
    try {
        while (true) {
            final String l = lnr.readLine();
            if (l == null) {
                break;
            }
            lines.add(l);
        }
    } finally {
        Utils.closeQuietly(lnr);
    }
    return lines.toArray(new String[lines.size()]);
}

From source file:org.esigate.http.HttpResponseUtils.java

/**
 * Returns the response body as a string or the reason phrase if body is empty.
 * <p>/*  w  w w. j a va2s . c o m*/
 * This methods is similar to EntityUtils#toString() internally, but uncompress the entity first if necessary.
 * <p>
 * This methods also holds an extension point, which can be used to guess the real encoding of the entity, if the
 * HTTP headers set a wrong encoding declaration.
 * 
 * @since 3.0
 * @since 4.1 - Event EventManager.EVENT_READ_ENTITY is fired when calling this method.
 * 
 * @param httpResponse
 * @param eventManager
 * @return The body as string or the reason phrase if body was empty.
 * @throws HttpErrorPage
 */
public static String toString(HttpResponse httpResponse, EventManager eventManager) throws HttpErrorPage {
    HttpEntity httpEntity = httpResponse.getEntity();
    String result;
    if (httpEntity == null) {
        result = httpResponse.getStatusLine().getReasonPhrase();
    } else {
        // Unzip the stream if necessary
        Header contentEncoding = httpEntity.getContentEncoding();
        if (contentEncoding != null) {
            String contentEncodingValue = contentEncoding.getValue();
            if ("gzip".equalsIgnoreCase(contentEncodingValue)
                    || "x-gzip".equalsIgnoreCase(contentEncodingValue)) {
                httpEntity = new GzipDecompressingEntity(httpEntity);
            } else if ("deflate".equalsIgnoreCase(contentEncodingValue)) {
                httpEntity = new DeflateDecompressingEntity(httpEntity);
            } else {
                throw new UnsupportedContentEncodingException(
                        "Content-encoding \"" + contentEncoding + "\" is not supported");
            }
        }

        try {
            byte[] rawEntityContent = EntityUtils.toByteArray(httpEntity);
            ContentType contentType = null;
            Charset charset = null;
            String mimeType = null;
            try {
                contentType = ContentType.getOrDefault(httpEntity);
                mimeType = contentType.getMimeType();
                charset = contentType.getCharset();
            } catch (UnsupportedCharsetException ex) {
                throw new UnsupportedEncodingException(ex.getMessage());
            }

            // Use default charset is no valid information found from HTTP
            // headers
            if (charset == null) {
                charset = HTTP.DEF_CONTENT_CHARSET;
            }

            ReadEntityEvent event = new ReadEntityEvent(mimeType, charset, rawEntityContent);

            // Read using charset based on HTTP headers
            event.setEntityContent(new String(rawEntityContent, charset));

            // Allow extensions to detect document encoding
            if (eventManager != null) {
                eventManager.fire(EventManager.EVENT_READ_ENTITY, event);
            }

            return event.getEntityContent();

        } catch (IOException e) {
            throw new HttpErrorPage(HttpErrorPage.generateHttpResponse(e));
        }
    }

    return removeSessionId(result, httpResponse);
}

From source file:com.navercorp.pinpoint.web.service.AgentEventServiceImpl.java

private Object deserializeEventMessage(AgentEventBo agentEventBo) {
    try {//from w ww .ja v  a  2 s .co m
        if (agentEventBo.getVersion() == 0) {
            return this.agentEventMessageDeserializer.deserialize(agentEventBo.getEventType(),
                    agentEventBo.getEventBody());
        } else if (agentEventBo.getVersion() == AgentEventBo.CURRENT_VERSION) {
            return this.agentEventMessageDeserializerV1.deserialize(agentEventBo.getEventType(),
                    agentEventBo.getEventBody());
        } else {
            throw new UnsupportedEncodingException("invalid version " + agentEventBo.getVersion());
        }
    } catch (UnsupportedEncodingException e) {
        logger.warn("error deserializing event message", e);
        return null;
    }
}

From source file:org.red5.net.websocket.WebSocketConnection.java

/**
 * Sends text to the client./*w  w  w  .  j  a v  a 2  s  . c om*/
 *
 * @param data
 *            string / text data
 * @throws UnsupportedEncodingException
 */
public void send(String data) throws UnsupportedEncodingException {
    log.debug("send message: {}", data);
    // process the incoming string
    if (StringUtils.isNotBlank(data)) {
        if (wsSession != null && isConnected()) {
            // add the data to the queue first
            outputQueue.add(data);
            // check for an existing send future and if there is one, return and let it do its work
            if (sendFuture == null || sendFuture.isDone()) {
                try {
                    // acquire lock and drain the queue
                    if (sendLock.tryAcquire(100L, TimeUnit.MILLISECONDS)) {
                        outputQueue.forEach(output -> {
                            if (isConnected()) {
                                try {
                                    if (useAsync) {
                                        sendFuture = wsSession.getAsyncRemote().sendText(output);
                                        sendFuture.get(20000L, TimeUnit.MILLISECONDS);
                                    } else {
                                        wsSession.getBasicRemote().sendText(output);
                                    }
                                    writtenBytes += output.getBytes().length;
                                } catch (TimeoutException e) {
                                    log.warn("Send timed out");
                                } catch (Exception e) {
                                    log.warn("Send wait interrupted", e);
                                } finally {
                                    outputQueue.remove(output);
                                }
                            }
                        });
                        // release
                        sendLock.release();
                    }
                } catch (InterruptedException e) {
                    log.warn("Send interrupted", e);
                    // release
                    sendLock.release();
                }
            }
        }
    } else {
        throw new UnsupportedEncodingException("Cannot send a null string");
    }
}

From source file:architecture.ee.component.core.lifecycle.ConfigServiceImpl.java

/**
 * @param characterEncoding//from  ww w.j a v  a  2s.c  om
 * @throws UnsupportedEncodingException
 */
public void setCharacterEncoding(String characterEncoding) throws UnsupportedEncodingException {
    if (!LocaleUtils.isValidCharacterEncoding(characterEncoding)) {
        throw new UnsupportedEncodingException((new StringBuilder()).append("Invalid character encoding: ")
                .append(characterEncoding).toString());
    } else {
        setApplicationProperty(ApplicationConstants.LOCALE_CHARACTER_ENCODING_PROP_NAME, characterEncoding);
        resetL10N();
        return;
    }
}

From source file:com.chukong.sdk.serv.support.MimeUtility.java

/**
 * Parse a string using the RFC 2047 rules for an "encoded-word"
 * type.  This encoding has the syntax:/*from   w w w  .ja va2  s .  c o m*/
 *
 * encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
 *
 * @param word   The possibly encoded word value.
 *
 * @return The decoded word.
 * @throws ParseException
 * @throws UnsupportedEncodingException
 */
private static String decodeWord(String word) throws ParseException, UnsupportedEncodingException {
    // encoded words start with the characters "=?".  If this not an encoded word, we throw a
    // ParseException for the caller.

    if (!word.startsWith(ENCODED_TOKEN_MARKER)) {
        throw new ParseException("Invalid RFC 2047 encoded-word: " + word);
    }

    int charsetPos = word.indexOf('?', 2);
    if (charsetPos == -1) {
        throw new ParseException("Missing charset in RFC 2047 encoded-word: " + word);
    }

    // pull out the character set information (this is the MIME name at this point).
    String charset = word.substring(2, charsetPos).toLowerCase();

    // now pull out the encoding token the same way.
    int encodingPos = word.indexOf('?', charsetPos + 1);
    if (encodingPos == -1) {
        throw new ParseException("Missing encoding in RFC 2047 encoded-word: " + word);
    }

    String encoding = word.substring(charsetPos + 1, encodingPos);

    // and finally the encoded text.
    int encodedTextPos = word.indexOf(ENCODED_TOKEN_FINISHER, encodingPos + 1);
    if (encodedTextPos == -1) {
        throw new ParseException("Missing encoded text in RFC 2047 encoded-word: " + word);
    }

    String encodedText = word.substring(encodingPos + 1, encodedTextPos);

    // seems a bit silly to encode a null string, but easy to deal with.
    if (encodedText.length() == 0) {
        return "";
    }

    try {
        // the decoder writes directly to an output stream.
        ByteArrayOutputStream out = new ByteArrayOutputStream(encodedText.length());

        byte[] encodedData = encodedText.getBytes(US_ASCII_CHARSET);

        // Base64 encoded?
        if (encoding.equals(BASE64_ENCODING_MARKER)) {
            Base64Decoder.decode(encodedData, out);
        } else if (encoding.equals(QUOTEDPRINTABLE_ENCODING_MARKER)) { // maybe quoted printable.
            QuotedPrintableDecoder.decode(encodedData, out);
        } else {
            throw new UnsupportedEncodingException("Unknown RFC 2047 encoding: " + encoding);
        }
        // get the decoded byte data and convert into a string.
        byte[] decodedData = out.toByteArray();
        return new String(decodedData, javaCharset(charset));
    } catch (IOException e) {
        throw new UnsupportedEncodingException("Invalid RFC 2047 encoding");
    }
}

From source file:Main.java

/**
 * <p>Turns a codepage number into the equivalent character encoding's
 * name, in either Java NIO or Java Lang canonical naming.</p>
 *
 * @param codepage       The codepage number
 * @param javaLangFormat Should Java Lang or Java NIO naming be used?
 * @return The character encoding's name, in either Java Lang format
 * (eg Cp1251, ISO8859_5) or Java NIO format (eg windows-1252, ISO-8859-9)
 * @throws UnsupportedEncodingException if the specified codepage is
 *                                      less than zero.
 * @see <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html">Supported Encodings</a>
 *///  w w w. ja  v  a  2  s  .  c  om
public static String codepageToEncoding(final int codepage, boolean javaLangFormat)
        throws UnsupportedEncodingException {
    if (codepage <= 0)
        throw new UnsupportedEncodingException("Codepage number may not be " + codepage);

    switch (codepage) {
    case CP_UTF16:
        return "UTF-16";
    case CP_UTF16_BE:
        return "UTF-16BE";
    case CP_UTF8:
        return "UTF-8";
    case CP_037:
        return "cp037";
    case CP_GBK:
        return "GBK";
    case CP_MS949:
        return "ms949";
    case CP_WINDOWS_1250:
        if (javaLangFormat)
            return "Cp1250";
        else
            return "windows-1250";
    case CP_WINDOWS_1251:
        if (javaLangFormat)
            return "Cp1251";
        else
            return "windows-1251";
    case CP_WINDOWS_1252:
    case CP_WINDOWS_1252_BIFF23:
        if (javaLangFormat)
            return "Cp1252";
        else
            return "windows-1252";
    case CP_WINDOWS_1253:
        if (javaLangFormat)
            return "Cp1253";
        else
            return "windows-1253";
    case CP_WINDOWS_1254:
        if (javaLangFormat)
            return "Cp1254";
        else
            return "windows-1254";
    case CP_WINDOWS_1255:
        if (javaLangFormat)
            return "Cp1255";
        else
            return "windows-1255";
    case CP_WINDOWS_1256:
        if (javaLangFormat)
            return "Cp1255";
        else
            return "windows-1256";
    case CP_WINDOWS_1257:
        if (javaLangFormat)
            return "Cp1257";
        else
            return "windows-1257";
    case CP_WINDOWS_1258:
        if (javaLangFormat)
            return "Cp1258";
        else
            return "windows-1258";
    case CP_JOHAB:
        return "johab";
    case CP_MAC_ROMAN:
    case CP_MAC_ROMAN_BIFF23:
        return "MacRoman";
    case CP_MAC_JAPAN:
        return "SJIS";
    case CP_MAC_CHINESE_TRADITIONAL:
        return "Big5";
    case CP_MAC_KOREAN:
        return "EUC-KR";
    case CP_MAC_ARABIC:
        return "MacArabic";
    case CP_MAC_HEBREW:
        return "MacHebrew";
    case CP_MAC_GREEK:
        return "MacGreek";
    case CP_MAC_CYRILLIC:
        return "MacCyrillic";
    case CP_MAC_CHINESE_SIMPLE:
        return "EUC_CN";
    case CP_MAC_ROMANIA:
        return "MacRomania";
    case CP_MAC_UKRAINE:
        return "MacUkraine";
    case CP_MAC_THAI:
        return "MacThai";
    case CP_MAC_CENTRAL_EUROPE:
        return "MacCentralEurope";
    case CP_MAC_ICELAND:
        return "MacIceland";
    case CP_MAC_TURKISH:
        return "MacTurkish";
    case CP_MAC_CROATIAN:
        return "MacCroatian";
    case CP_US_ACSII:
    case CP_US_ASCII2:
        return "US-ASCII";
    case CP_KOI8_R:
        return "KOI8-R";
    case CP_ISO_8859_1:
        if (javaLangFormat)
            return "ISO8859_1";
        else
            return "ISO-8859-1";
    case CP_ISO_8859_2:
        if (javaLangFormat)
            return "ISO8859_2";
        else
            return "ISO-8859-2";
    case CP_ISO_8859_3:
        if (javaLangFormat)
            return "ISO8859_3";
        else
            return "ISO-8859-3";
    case CP_ISO_8859_4:
        if (javaLangFormat)
            return "ISO8859_4";
        else
            return "ISO-8859-4";
    case CP_ISO_8859_5:
        if (javaLangFormat)
            return "ISO8859_5";
        else
            return "ISO-8859-5";
    case CP_ISO_8859_6:
        if (javaLangFormat)
            return "ISO8859_6";
        else
            return "ISO-8859-6";
    case CP_ISO_8859_7:
        if (javaLangFormat)
            return "ISO8859_7";
        else
            return "ISO-8859-7";
    case CP_ISO_8859_8:
        if (javaLangFormat)
            return "ISO8859_8";
        else
            return "ISO-8859-8";
    case CP_ISO_8859_9:
        if (javaLangFormat)
            return "ISO8859_9";
        else
            return "ISO-8859-9";
    case CP_ISO_2022_JP1:
    case CP_ISO_2022_JP2:
    case CP_ISO_2022_JP3:
        return "ISO-2022-JP";
    case CP_ISO_2022_KR:
        return "ISO-2022-KR";
    case CP_EUC_JP:
        return "EUC-JP";
    case CP_EUC_KR:
        return "EUC-KR";
    case CP_GB2312:
        return "GB2312";
    case CP_GB18030:
        return "GB18030";
    case CP_SJIS:
        return "SJIS";
    default:
        return "cp" + codepage;
    }
}

From source file:de.hybris.platform.acceleratorstorefrontcommons.controllers.pages.AbstractPageController.java

/**
 * Checks request URL against properly resolved URL and returns null if url is proper or redirection string if not.
 *
 * @param request//from  ww  w  .  ja va2 s .c  o m
 *           - request that contains current URL
 * @param response
 *           - response to write "301 Moved Permanently" status to if redirected
 * @param resolvedUrlPath
 *           - properly resolved URL
 * @return null if url is properly resolved or redirection string if not
 * @throws UnsupportedEncodingException
 */
protected String checkRequestUrl(final HttpServletRequest request, final HttpServletResponse response,
        final String resolvedUrlPath) throws UnsupportedEncodingException {
    try {
        final String resolvedUrl = response.encodeURL(request.getContextPath() + resolvedUrlPath);
        final String requestURI = URIUtil.decode(request.getRequestURI(), "utf-8");
        final String decoded = URIUtil.decode(resolvedUrl, "utf-8");
        if (StringUtils.isNotEmpty(requestURI) && requestURI.endsWith(decoded)) {
            return null;
        } else {
            //  org.springframework.web.servlet.View.RESPONSE_STATUS_ATTRIBUTE = "org.springframework.web.servlet.View.responseStatus"
            request.setAttribute("org.springframework.web.servlet.View.responseStatus",
                    HttpStatus.MOVED_PERMANENTLY);
            final String queryString = request.getQueryString();
            if (queryString != null && !queryString.isEmpty()) {
                return "redirect:" + resolvedUrlPath + "?" + queryString;
            }
            return "redirect:" + resolvedUrlPath;
        }
    } catch (final URIException e) {
        LOGGER.error("URIException:" + e.getMessage(), e);
        throw new UnsupportedEncodingException(e.getMessage());
    }
}

From source file:org.lockss.util.StreamUtil.java

/** Return an InputStream that uncompresses the data on the input
 * stream (normally an HTTP response stream)
 * @param instr raw InputStream// ww  w .  j  a va  2 s . co m
 * @param contentEncoding value of HTTP Content-Encoding: header
 * @return The wrapped stream, or the original stream if contentEncoding
 * is null or "identity"
 * @throws UnsupportedEncodingException
 */
public static InputStream getUncompressedInputStream(InputStream instr, String contentEncoding)
        throws IOException, UnsupportedEncodingException {
    InputStream res;
    if (StringUtil.isNullString(contentEncoding) || contentEncoding.equalsIgnoreCase("identity")) {
        res = instr;
    } else if (contentEncoding.equalsIgnoreCase("gzip") || contentEncoding.equalsIgnoreCase("x-gzip")) {
        log.debug3("Wrapping in GZIPInputStream");
        res = new GZIPInputStream(instr);
    } else if (contentEncoding.equalsIgnoreCase("deflate")) {
        log.debug3("Wrapping in InflaterInputStream");
        res = new InflaterInputStream(instr);
    } else {
        throw new UnsupportedEncodingException(contentEncoding);
    }
    return res;
}

From source file:com.puppycrawl.tools.checkstyle.Checker.java

/**
 * Sets a named charset.//from w ww .  j a  v a  2s . c  om
 * @param charset the name of a charset
 * @throws UnsupportedEncodingException if charset is unsupported.
 */
public void setCharset(String charset) throws UnsupportedEncodingException {
    if (!Charset.isSupported(charset)) {
        final String message = "unsupported charset: '" + charset + "'";
        throw new UnsupportedEncodingException(message);
    }
    this.charset = charset;
}