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:Main.java

/**
 * Returns the {@code String} instance with detecting the Japanese encoding.
 * @throws UnsupportedEncodingException if it fails to detect the encoding.
 *//*w  ww .j  ava2 s.com*/
static String toStringWithEncodingDetection(ByteBuffer buffer) throws UnsupportedEncodingException {
    for (String encoding : JAPANESE_ENCODING_LIST) {
        buffer.position(0);
        try {
            Charset charset = Charset.forName(encoding);
            CharBuffer result = charset.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
                    .onUnmappableCharacter(CodingErrorAction.REPORT).decode(buffer);
            String str = result.toString();
            if (str.length() > 0 && str.charAt(0) == 0xFEFF) {
                // Remove leading BOM if necessary.
                str = str.substring(1);
            }
            return str;
        } catch (Exception e) {
            // Ignore exceptions, and retry next encoding.
        }
    }

    throw new UnsupportedEncodingException("Failed to detect encoding");
}

From source file:Main.java

public static Charset get(final String name) throws UnsupportedEncodingException {
    if (name == null) {
        return null;
    }//from w  w  w .  j  ava2s .  co  m
    try {
        return Charset.forName(name);
    } catch (final UnsupportedCharsetException ex) {
        throw new UnsupportedEncodingException(name);
    }
}

From source file:net.dv8tion.jda.utils.AvatarUtil.java

public static Avatar getAvatar(File avatarFile) throws UnsupportedEncodingException {
    String[] split = avatarFile.getName().split("\\.");
    String type = split[split.length - 1];
    if (type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("jpeg") || type.equalsIgnoreCase("png")) {
        try {//from  w  w  w  . ja va2 s.c om
            //reading
            BufferedImage img = ImageIO.read(avatarFile);
            return getAvatar(img);
        } catch (IOException e) {
            JDAImpl.LOG.log(e);
        }
    } else {
        throw new UnsupportedEncodingException("Image type " + type + " is not supported!");
    }
    return null;
}

From source file:datacite.oai.provider.util.BOMUtil.java

/**
 * Remove a Byte Order Mark from the beginning of a byte[].
 * @param array The byte[] to remove a BOM from.
 * @param encoding The character encoding to remove the BOM for.
 * @return The original byte[] without BOM.
 *///  w w  w . java2  s. com
public static byte[] removeBOM(byte[] array, String encoding) throws UnsupportedEncodingException {
    if (encoding == null || encoding.trim().length() == 0) {
        throw new UnsupportedEncodingException("Unsupported encoding: " + encoding);
    } else {
        encoding = encoding.toUpperCase().replaceAll("[^A-Z0-9]", "");
        byte[] bom = BOMUtil.BOM_MAP.get(encoding);
        if (bom == null) {
            throw new UnsupportedEncodingException("Unsupported encoding: " + encoding);
        } else {
            return BOMUtil.removeBOM(array, bom);
        }
    }
}

From source file:org.wso2.carbon.pc.analytics.core.generic.clients.AnalyticsRestClient.java

/**
 * Send post request to a DAS rest web service
 * @param url used to locate the webservice functionality
 * @param message is the request message that need to be sent to the web service
 * @return the result as a String//from w w  w.  j  a v a 2 s . c o  m
 */
public static String post(String url, String message) throws IOException, XMLStreamException {
    RegistryUtils.setTrustStoreSystemProperties();
    HttpClient httpClient = new HttpClient();
    PostMethod postRequest = new PostMethod(url);
    postRequest.setRequestHeader("Authorization", AnalyticsUtils.getAuthorizationHeader());
    BufferedReader br = null;
    try {
        StringRequestEntity input = new StringRequestEntity(message, "application/json", "UTF-8");
        postRequest.setRequestEntity(input);

        int returnCode = httpClient.executeMethod(postRequest);

        if (returnCode != HttpStatus.SC_OK) {
            String errorCode = "Failed : HTTP error code : " + returnCode;
            throw new RuntimeException(errorCode);
        }

        InputStreamReader reader = new InputStreamReader((postRequest.getResponseBodyAsStream()));
        br = new BufferedReader(reader);

        String output = null;
        StringBuilder totalOutput = new StringBuilder();

        if (log.isDebugEnabled()) {
            log.debug("Output from Server .... \n");
        }

        while ((output = br.readLine()) != null) {
            totalOutput.append(output);
        }
        return totalOutput.toString();

    } catch (UnsupportedEncodingException e) {
        String errMsg = "Async DAS client unsupported encoding exception.";
        throw new UnsupportedEncodingException(errMsg);
    } catch (UnsupportedOperationException e) {
        String errMsg = "Async DAS client unsupported operation exception.";
        throw new UnsupportedOperationException(errMsg);
    } catch (IOException e) {
        String errMsg = "Async DAS client I/O exception.";
        log.error(errMsg, e);
    } finally {
        postRequest.releaseConnection();
        if (br != null) {
            try {
                br.close();
            } catch (Exception e) {
                String errMsg = "Async DAS rest client BufferedReader close exception.";
                log.error(errMsg, e);
            }
        }
    }
    return null;
}

From source file:org.wso2.ei.bpmn.analytics.core.clients.BPMNAnalyticsCoreRestClient.java

/**
 * Send post request to a DAS rest web service
 * @param url used to locate the webservice functionality
 * @param message is the request message that need to be sent to the web service
 * @return the result as a String/* w ww .  j  a v  a2  s  .  c o  m*/
 */
public static String post(String url, String message) throws IOException, XMLStreamException {
    RegistryUtils.setTrustStoreSystemProperties();
    HttpClient httpClient = new HttpClient();
    PostMethod postRequest = new PostMethod(url);
    postRequest.setRequestHeader("Authorization", BPMNAnalyticsCoreUtils.getAuthorizationHeader());
    BufferedReader br = null;
    try {
        StringRequestEntity input = new StringRequestEntity(message, "application/json", "UTF-8");
        postRequest.setRequestEntity(input);

        int returnCode = httpClient.executeMethod(postRequest);

        if (returnCode != HttpStatus.SC_OK) {
            String errorCode = "Failed : HTTP error code : " + returnCode;
            throw new RuntimeException(errorCode);
        }

        InputStreamReader reader = new InputStreamReader((postRequest.getResponseBodyAsStream()));
        br = new BufferedReader(reader);

        String output = null;
        StringBuilder totalOutput = new StringBuilder();

        if (log.isDebugEnabled()) {
            log.debug("Output from Server .... \n");
        }

        while ((output = br.readLine()) != null) {
            totalOutput.append(output);
        }
        return totalOutput.toString();

    } catch (UnsupportedEncodingException e) {
        String errMsg = "Async DAS client unsupported encoding exception.";
        throw new UnsupportedEncodingException(errMsg);
    } catch (UnsupportedOperationException e) {
        String errMsg = "Async DAS client unsupported operation exception.";
        throw new UnsupportedOperationException(errMsg);
    } catch (IOException e) {
        String errMsg = "Async DAS client I/O exception.";
        log.error(errMsg, e);
    } finally {
        postRequest.releaseConnection();
        if (br != null) {
            try {
                br.close();
            } catch (Exception e) {
                String errMsg = "Async DAS rest client BufferedReader close exception.";
                log.error(errMsg, e);
            }
        }
    }
    return null;
}

From source file:org.wso2.carbon.pc.analytics.core.clients.AnalyticsRestClient.java

/**
 * Send post request to a DAS rest web service
 * @param url used to locate the webservice functionality
 * @param message is the request message that need to be sent to the web service
 * @return the result as a String/*from  w w  w .  j  a  va  2 s  . c o m*/
 */
public static String post(String url, String message) throws IOException, XMLStreamException {
    RegistryUtils.setTrustStoreSystemProperties();
    HttpClient httpClient = new HttpClient();
    PostMethod postRequest = new PostMethod(url);
    postRequest.setRequestHeader("Authorization", AnalyticsUtils.getAuthorizationHeader());
    BufferedReader br = null;
    try {
        StringRequestEntity input = new StringRequestEntity(message, "application/json", "UTF-8");
        postRequest.setRequestEntity(input);

        int returnCode = httpClient.executeMethod(postRequest);

        if (returnCode != HttpStatus.SC_OK) {
            String errorCode = "Failed : HTTP error code : " + returnCode;
            throw new RuntimeException(errorCode);
        }

        InputStreamReader reader = new InputStreamReader((postRequest.getResponseBodyAsStream()));
        br = new BufferedReader(reader);

        String output = null;
        StringBuilder totalOutput = new StringBuilder();

        if (log.isDebugEnabled()) {
            log.debug("Output from Server .... \n");
        }

        while ((output = br.readLine()) != null) {
            totalOutput.append(output);
        }

        if (log.isDebugEnabled()) {
            log.debug("Output = " + totalOutput.toString());
        }

        return totalOutput.toString();

    } catch (UnsupportedEncodingException e) {
        String errMsg = "Async DAS client unsupported encoding exception.";
        throw new UnsupportedEncodingException(errMsg);
    } catch (UnsupportedOperationException e) {
        String errMsg = "Async DAS client unsupported operation exception.";
        throw new UnsupportedOperationException(errMsg);
    } catch (IOException e) {
        String errMsg = "Async DAS client I/O exception.";
        log.error(errMsg, e);
    } finally {
        postRequest.releaseConnection();
        if (br != null) {
            try {
                br.close();
            } catch (Exception e) {
                String errMsg = "Async DAS rest client BufferedReader close exception.";
                log.error(errMsg, e);
            }
        }
    }
    return null;
}

From source file:au.csiro.casda.sodalint.Validator.java

/**
 * Retrieve the content from an address using a GET request.
 *  //from  w  w  w  . ja va 2s.c  o  m
 * @param address The address to be queried.
 * @return The content, or null if no content could be read.
 * @throws HttpResponseException If a non 200 response code is returned.
 * @throws UnsupportedEncodingException If the content does not have an XML format. 
 * @throws IOException If the content could not be read.
 */
protected String getXmlContentFromUrl(String address)
        throws HttpResponseException, UnsupportedEncodingException, IOException {
    Response response = Request.Get(address).execute();
    HttpResponse httpResponse = response.returnResponse();
    StatusLine statusLine = httpResponse.getStatusLine();
    final int statusCodeOk = 200;
    if (statusLine.getStatusCode() != statusCodeOk) {
        throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }
    HttpEntity entity = httpResponse.getEntity();
    if (entity == null) {
        return null;
    }
    ContentType contentType = ContentType.getOrDefault(entity);
    if (!ContentType.APPLICATION_XML.getMimeType().equals(contentType.getMimeType())
            && !ContentType.TEXT_XML.getMimeType().equals(contentType.getMimeType())) {
        throw new UnsupportedEncodingException(contentType.toString());
    }
    String content = readTextContent(entity);
    if (StringUtils.isBlank(content)) {
        return null;
    }

    return content;
}

From source file:org.jenkinsci.plugins.relution_publisher.net.RequestQueryFields.java

/**
 * Specifies the character set to use when encoding strings.
 * @param charsetName The name of the character set to use.
 * @throws IllegalCharsetNameException if the specified name is illegal.
 * @throws UnsupportedEncodingException if the specified character set is unsupported.
 *///from  w  ww. jav  a 2 s.  com
public void setCharset(final String charsetName) throws UnsupportedEncodingException {

    if (!Charset.isSupported(charsetName)) {
        throw new UnsupportedEncodingException("The specified charset is unsupported: " + charsetName);
    }
    this.mCharsetName = charsetName;
}

From source file:TextUtil.java

/**
 *  URL encoder does not handle all characters correctly.
 *  See <A HREF="http://developer.java.sun.com/developer/bugParade/bugs/4257115.html">
 *  Bug parade, bug #4257115</A> for more information.
 *  <P>/*ww w  . j a  v  a2  s.  com*/
 *  Thanks to CJB for this fix.
 *  
 *  @param bytes The byte array containing the bytes of the string
 *  @param encoding The encoding in which the string should be interpreted
 *  @return A decoded String
 *  
 *  @throws UnsupportedEncodingException If the encoding is unknown.
 *  @throws IllegalArgumentException If the byte array is not a valid string.
 */
protected static String urlDecode(byte[] bytes, String encoding)
        throws UnsupportedEncodingException, IllegalArgumentException {
    if (bytes == null) {
        return null;
    }

    byte[] decodeBytes = new byte[bytes.length];
    int decodedByteCount = 0;

    try {
        for (int count = 0; count < bytes.length; count++) {
            switch (bytes[count]) {
            case '+':
                decodeBytes[decodedByteCount++] = (byte) ' ';
                break;

            case '%':
                decodeBytes[decodedByteCount++] = (byte) ((HEX_DIGITS.indexOf(bytes[++count]) << 4)
                        + (HEX_DIGITS.indexOf(bytes[++count])));

                break;

            default:
                decodeBytes[decodedByteCount++] = bytes[count];
            }
        }

    } catch (IndexOutOfBoundsException ae) {
        throw new IllegalArgumentException("Malformed UTF-8 string?");
    }

    String processedPageName = null;

    try {
        processedPageName = new String(decodeBytes, 0, decodedByteCount, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new UnsupportedEncodingException("UTF-8 encoding not supported on this platform");
    }

    return processedPageName;
}