Example usage for java.io UnsupportedEncodingException getMessage

List of usage examples for java.io UnsupportedEncodingException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:addresspager.com.licenseinandroid.MainActivity.java

@Override
protected String doInBackground(String... te) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://10.0.2.2/ksource/index.php");
    List<NameValuePair> valobj = new ArrayList<NameValuePair>(2);
    valobj.add(new BasicNameValuePair("email", "sriram@gmail.com"));
    valobj.add(new BasicNameValuePair("user", "praveen.com"));
    try {//  w ww  . j a v a  2  s.c om
        this.log("backend server connection started");
        post.setEntity(new UrlEncodedFormEntity(valobj));
        HttpResponse ree = client.execute(post);
        String t = EntityUtils.toString(ree.getEntity());
        this.result = t;
        this.log("backend server connection ok..");
    } catch (UnsupportedEncodingException e) {
        this.result = "encoding exception";
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        this.result = "protocal exception";
        e.printStackTrace();
    } catch (IOException e) {
        this.result = "IO exception " + e.getMessage();
        e.printStackTrace();
    }
    return null;
}

From source file:com.serena.rlc.provider.artifactory.client.ArtifactoryClient.java

/**
 * Execute a post request to Artifactory.
 *
 * @param path  the path for the specific request
 * @param parameters  parameters to send with the query
 * @param body  the body to send with the request
 * @return String containing the response body
 * @throws ArtifactoryClientException/* ww w  . j  a  v a  2s  . c  om*/
 */
public String processPost(String path, String parameters, String body) throws ArtifactoryClientException {
    String uri = createUrl(path, parameters);

    logger.debug("Start executing Artifactory POST request to url=\"{}\" with data: {}", uri, body);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(uri);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getArtifactoryUsername(),
            getArtifactoryPassword());
    postRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    postRequest.addHeader(HttpHeaders.CONTENT_TYPE, DEFAULT_HTTP_CONTENT_TYPE);
    postRequest.addHeader(HttpHeaders.ACCEPT, DEFAULT_HTTP_CONTENT_TYPE);

    try {
        postRequest.setEntity(new StringEntity(body, "UTF-8"));
    } catch (UnsupportedEncodingException ex) {
        logger.error(ex.getMessage(), ex);
        throw new ArtifactoryClientException("Error creating body for POST request", ex);
    }
    String result = "";

    try {
        HttpResponse response = httpClient.execute(postRequest);
        if (response.getStatusLine().getStatusCode() != org.apache.commons.httpclient.HttpStatus.SC_OK
                && response.getStatusLine()
                        .getStatusCode() != org.apache.commons.httpclient.HttpStatus.SC_CREATED
                && response.getStatusLine()
                        .getStatusCode() != org.apache.commons.httpclient.HttpStatus.SC_ACCEPTED) {
            throw createHttpError(response);
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        StringBuilder sb = new StringBuilder(1024);
        String output;
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }
        result = sb.toString();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new ArtifactoryClientException("Server not available", e);
    }

    logger.debug("End executing Artifactory POST request to url=\"{}\" and received this result={}", uri,
            result);

    return result;
}

From source file:de.mango.business.GoogleSearchProvider.java

public Vector<String> search(String query, int count, int page) {
    Vector<String> results = new Vector<String>();
    // Prepare the query
    try {/*from  w w  w  .ja v  a2  s  .co  m*/
        query = "http://ajax.googleapis.com/ajax/services/search/images?" + GoogleSearchProvider.searchArguments
                + this.hostLanguage + "&q="
                + URLEncoder.encode(
                        GoogleSearchProvider.restrictToOpenClipart ? query + GoogleSearchProvider.openClipart
                                : query,
                        "UTF-8")
                + "&start=";
    } catch (UnsupportedEncodingException e) {
        if (DEBUG) {
            Log.w(TAG, "Unsupported Encoding Exception:" + e.getMessage());
            Log.w(TAG, Log.getStackTraceString(e));
        }
        return results;
    }

    // start argument to pass to google
    int firstindex = count * page;
    // count of results to skip before adding them to the result array
    int skip = 0;
    // start indices > 56 are skipped by Google, so we
    // ask for results from 56, but skip the unwanted $skip indices
    if (firstindex > 63)
        return results;
    if (firstindex > 56) {
        skip = firstindex - 56;
        firstindex = 56;
    }

    boolean readMore = true; // do we need more queries and are they
    // possible?
    while (readMore) {
        // add start index to the query
        String currentQuery = query + firstindex;
        if (DEBUG)
            Log.d(TAG, "Searching: " + currentQuery);
        try {
            // prepare the connection
            URL url = new URL(currentQuery);
            URLConnection connection = url.openConnection();
            connection.addRequestProperty("Referer", GoogleSearchProvider.refererUrl);

            connection.setConnectTimeout(2000);
            connection.setReadTimeout(2000);
            connection.connect();

            // receive the results
            StringBuilder builder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            // parse the results
            JSONObject json = new JSONObject(builder.toString());
            int responseStatus = json.getInt("responseStatus");
            if (responseStatus == 200)// successful search
            {
                json = json.getJSONObject("responseData");
                JSONArray res = json.getJSONArray("results");
                if (res.length() == 0)
                    return results;
                String s;
                int limit = Math.min(res.length(), count - results.size() + skip);
                for (int i = skip; i < limit; i++) {
                    s = res.getJSONObject(i).getString("unescapedUrl");
                    if (s != null)
                        results.addElement(s);
                }
                // see if there are "more Results"
                JSONObject cursor = json.getJSONObject("cursor");
                JSONArray pages = cursor.getJSONArray("pages");
                int pageCount = pages.length();
                int currentPageIndex = cursor.getInt("currentPageIndex");
                this.moreResults = readMore = (pageCount - 1) > currentPageIndex;
            } else {
                if (DEBUG)
                    Log.w(TAG, "Goole Search Error (Code " + responseStatus + "):"
                            + json.getString("responseDetails"));
                this.moreResults = readMore = false;// prevent for (;;) loop
                // on errors
            }
        } catch (MalformedURLException e) {
            if (DEBUG) {
                Log.w(TAG, "MalformedURLException:" + e.getMessage());
                Log.w(TAG, Log.getStackTraceString(e));
            }
            this.moreResults = readMore = false;
        } catch (IOException e) {
            if (DEBUG) {
                Log.w(TAG, "IOException:" + e.getMessage());
                Log.w(TAG, Log.getStackTraceString(e));
            }
            this.moreResults = readMore = false;
        } catch (JSONException e) {
            if (DEBUG) {
                Log.w(TAG, "JSONException:" + e.getMessage());
                Log.w(TAG, Log.getStackTraceString(e));
            }
            this.moreResults = readMore = false;
        }

        // read more only if we can read more AND want to have more
        readMore = readMore && results.size() < count;
        if (readMore) {
            firstindex += 8;
            if (firstindex > 56)// the last pages always need to start
            // querying at index 56 (or google returns
            // errors)
            {
                skip = firstindex - 56;
                firstindex = 56;
            }
        }
    }
    return results;
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * Create a url encoded form//ww  w  . j a  va  2  s.c om
 * 
 * @param request
 *            Request object
 * @param enc
 *            Request body encoding, default is utf8
 * @param keyVals
 *            Key and value pairs, the even(begins with 0) position params
 *            are key and the odds are values
 * @return
 */
public static HttpPost urlEncodedForm(HttpPost request, Encoding enc, Object... keyVals) {
    if (request == null || ValidationUtils.isEmpty(keyVals))
        return request;
    ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
    for (int i = 0; i < keyVals.length; i += 2) {
        pairs.add(new BasicNameValuePair(ShenStrings.str(keyVals[i]),
                i + 1 < keyVals.length ? ShenStrings.str(keyVals[i + 1]) : StringUtils.EMPTY));
    }
    try {
        request.setEntity(new UrlEncodedFormEntity(pairs, enc.code));
    } catch (UnsupportedEncodingException e) {
        LOG.warn("[urlEncodedForm]Fill data to form entity failed. Caused by {}", e.getMessage());
    }
    return request;
}

From source file:ch.entwine.weblounge.cache.impl.CacheableHttpServletResponse.java

/**
 * Returns the modified writer that enables the <code>CacheManager</cache>
 * to copy the response to the cache./*from w w  w  . jav  a2  s  .  c o m*/
 * 
 * @return a PrintWriter object that can return character data to the client
 * @throws IOException
 *           if the writer could not be allocated
 * @see javax.servlet.ServletResponse#getWriter()
 * @see ch.entwine.weblounge.OldCacheManager.cache.CacheManager
 */
@Override
public PrintWriter getWriter() throws IOException {
    // Check whether there's already a writer allocated
    if (out != null)
        return out;

    // Check whether getOutputStream() has already been called
    if (osCalled)
        throw new IllegalStateException("An output stream has already been allocated");

    // Get the character encoding
    String encoding = getCharacterEncoding();
    if (encoding == null) {
        encoding = DEFAULT_ENCODING;
        setCharacterEncoding(encoding);
    }

    // Allocate a new writer. If there is a transaction, the output is written
    // to both the original response and the cache output stream.
    try {
        if (tx == null || tx.getFilter() == null)
            out = new PrintWriter(new OutputStreamWriter(super.getOutputStream(), encoding));
        else
            out = new PrintWriter(new BufferedWriter(new FilterWriter(
                    new OutputStreamWriter(new TeeOutputStream(super.getOutputStream(), tx.getOutputStream()),
                            encoding),
                    tx.getFilter(), contentType)));
    } catch (UnsupportedEncodingException e) {
        throw new IOException(e.getMessage());
    }

    // Check whether the new writer is usable
    if (out == null)
        throw new IOException("Unable to allocate writer");

    // Return the new writer
    return out;
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * Create a url encoded form/*w  w w .ja va  2  s.c o m*/
 * 
 * @param request
 *            Request object
 * @param enc
 *            Request body encoding, default is utf8
 * @param keyVals
 *            Key and value pairs, the even(begins with 0) position params
 *            are key and the odds are values
 * @return
 */
public static <K, V> HttpPost urlEncodedFormByMap(HttpPost request, Encoding enc, Map<K, V> keyVals) {
    if (request == null || ValidationUtils.isEmpty(keyVals))
        return request;
    ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
    for (Object key : keyVals.keySet()) {
        pairs.add(new BasicNameValuePair(ShenStrings.str(key), ShenStrings.str(keyVals.get(key))));
    }
    try {
        if (LOG.isDebugEnabled())
            LOG.debug("[urlEncodedFormByMap] enc:{} pairs:{}", new Object[] { enc.code, pairs });
        request.setEntity(new UrlEncodedFormEntity(pairs, enc.code));
    } catch (UnsupportedEncodingException e) {
        LOG.warn("[urlEncodedForm]Fill data to form entity failed. Caused by {}", e.getMessage());
    }
    return request;
}

From source file:com.xunlei.util.codec.Hex.java

/**
 * Converts an array of character bytes representing hexadecimal values into an array of bytes of those same values. The returned array will be half the length of the passed array, as it takes two
 * characters to represent any given byte. An exception is thrown if the passed char array has an odd number of elements.
 * //from w w w .j  a  v a2  s .co  m
 * @param array An array of character bytes containing hexadecimal digits
 * @return A byte array containing binary data decoded from the supplied byte array (representing characters).
 * @throws DecoderException Thrown if an odd number of characters is supplied to this function
 * @see #decodeHex(char[])
 */
public byte[] decode(byte[] array) throws DecoderException {
    try {
        return decodeHex(new String(array, getCharsetName()).toCharArray());
    } catch (UnsupportedEncodingException e) {
        throw new DecoderException(e.getMessage(), e);
    }
}

From source file:at.ac.tuwien.big.moea.print.SolutionWriter.java

@Override
public String write(final S solution) {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final PrintStream ps = new PrintStream(baos);
    write(ps, solution);//  w  w  w  .jav  a2 s.c  om
    ps.close();
    try {
        return baos.toString("UTF-8");
    } catch (final UnsupportedEncodingException e) {
        return e.getMessage();
    }
}

From source file:com.bah.bahdit.main.plugins.imageindex.ImageIndex.java

/**
 * Query the hash table for the specified ranges
 * If the not enough pictures are found then fuzzy query kicks in
 * //  w w  w .  j av a2 s . com
 * @param scanner - scanner to the hash table
 * @param hashRanges - ranges to search for
 * @return - a set of strings -> loc + "[ ]" + URL
 */
public HashSet<String> getHash(BatchScanner scanner, HashSet<String> hashRanges) {

    HashSet<String> results = new HashSet<String>();

    if (doSimilar == 1) {

        String hashRangesString = null;
        try {
            hashRangesString = new String(Utils.serialize(hashRanges), ENCODING);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        Map<String, String> iteratorProperties = new HashMap<String, String>();
        iteratorProperties.put(Search.QUERY, hashRangesString);
        iteratorProperties.put(IMG_HASH_DISTANCE, String.valueOf(imgHashingDistance));
        IteratorSetting cfg = new IteratorSetting(10, SimiliarImageRanker.class, iteratorProperties);
        scanner.addScanIterator(cfg);

        HashSet<Range> ranges = new HashSet<Range>();
        ranges.add(new Range());
        scanner.setRanges(ranges);

    } else {
        HashSet<Range> ranges = new HashSet<Range>();

        for (String s : hashRanges)
            ranges.add(new Range(s));

        scanner.setRanges(ranges);
    }

    // scan for hashes with the specified ranges
    for (Entry<Key, Value> entry : scanner) {
        Key key = entry.getKey();
        String loc = key.getColumnFamily().toString();
        String URL = key.getColumnQualifier().toString();
        String info = loc + "[ ]" + URL;
        results.add(info);
    }

    return results;
}

From source file:com.evolveum.polygon.connector.ldap.ad.AdSchemaTranslator.java

@Override
protected Value<Object> toLdapPasswordValue(AttributeType ldapAttributeType, Object icfAttributeValue) {
    String password;//from   w w w  .jav a2s.c o  m
    if (icfAttributeValue instanceof String) {
        password = (String) icfAttributeValue;
    } else if (icfAttributeValue instanceof GuardedString) {
        final String[] out = new String[1];
        ((GuardedString) icfAttributeValue).access(new GuardedString.Accessor() {
            @Override
            public void access(char[] clearChars) {
                out[0] = new String(clearChars);
            }
        });
        password = out[0];
    } else {
        throw new IllegalArgumentException(
                "Password must be string or GuardedString, but it was " + icfAttributeValue.getClass());
    }

    String quotedPassword = "\"" + password + "\"";
    byte[] utf16PasswordBytes;
    try {
        utf16PasswordBytes = quotedPassword.getBytes("UTF-16LE");
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Error converting password to UTF-16: " + e.getMessage(), e);
    }

    try {
        return (Value) new BinaryValue(ldapAttributeType, utf16PasswordBytes);
    } catch (LdapInvalidAttributeValueException e) {
        throw new IllegalArgumentException("Invalid value for attribute " + ldapAttributeType.getName() + ": "
                + e.getMessage() + "; attributeType=" + ldapAttributeType, e);
    }
}