Example usage for java.io UnsupportedEncodingException getLocalizedMessage

List of usage examples for java.io UnsupportedEncodingException getLocalizedMessage

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:br.com.cams7.siscom.member.MemberEdit.java

private static String POST(String url, Member member, String errorMsg) {

    // 1. create HttpClient
    HttpClient httpclient = new DefaultHttpClient();
    try {/* w  w  w  .  j  a v  a  2  s  .co m*/
        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("id", member.getId());
        jsonObject.accumulate("name", member.getName());
        jsonObject.accumulate("email", member.getEmail());
        jsonObject.accumulate("phoneNumber", member.getPhoneNumber());

        // 4. convert JSONObject to JSON to String
        String json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin
        // Jackson Lib
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person);

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the
        // content
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        InputStream inputStream = httpResponse.getEntity().getContent();

        if (inputStream == null) {
            Log.d(RestUtil.TAG_INPUT_STREAM, "InputStream is null");
            return errorMsg;
        }

        // 10. convert inputstream to string
        return RestUtil.convertInputStreamToString(inputStream);

    } catch (UnsupportedEncodingException e) {
        Log.d(RestUtil.TAG_INPUT_STREAM, e.getLocalizedMessage(), e.getCause());
    } catch (ClientProtocolException e) {
        Log.d(RestUtil.TAG_INPUT_STREAM, e.getLocalizedMessage(), e.getCause());
    } catch (IOException e) {
        Log.d(RestUtil.TAG_INPUT_STREAM, e.getLocalizedMessage(), e.getCause());
    } catch (JSONException e) {
        Log.d(RestUtil.TAG_INPUT_STREAM, e.getLocalizedMessage(), e.getCause());
    }

    // 11. return result
    return errorMsg;
}

From source file:org.opencms.ui.apps.CmsEditor.java

/**
 * Returns the edit state for the given resource structure id.<p>
 *
 * @param resourceId the resource structure is
 * @param plainText if plain text/source editing is required
 * @param backLink the back link location
 *
 * @return the state/*from   ww w .j  av  a 2 s  . co m*/
 */
public static String getEditState(CmsUUID resourceId, boolean plainText, String backLink) {

    try {
        backLink = URLEncoder.encode(backLink, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        LOG.error(e.getLocalizedMessage(), e);
    }
    String state = CmsEditor.RESOURCE_ID_PREFIX + resourceId.toString() + CmsEditor.STATE_SEPARATOR
            + CmsEditor.PLAIN_TEXT_PREFIX + plainText + CmsEditor.STATE_SEPARATOR + CmsEditor.BACK_LINK_PREFIX
            + backLink;
    return state;
}

From source file:org.opencms.ui.apps.CmsEditor.java

/**
 * Navigates to the back link target.<p>
 *
 * @param backlink the back link//from  w ww  .j  a va  2  s.  c  o m
 */
public static void openBackLink(String backlink) {

    try {
        backlink = URLDecoder.decode(backlink, "UTF-8");
        String current = Page.getCurrent().getLocation().toString();
        if (current.contains("#")) {
            current = current.substring(0, current.indexOf("#"));
        }
        // check if the back link targets the workplace UI
        if (backlink.startsWith(current)) {
            // use the navigator to open the target
            String target = backlink.substring(backlink.indexOf("#") + 1);
            CmsAppWorkplaceUi.get().getNavigator().navigateTo(target);
        } else {
            // otherwise set the new location
            Page.getCurrent().setLocation(backlink);
        }
    } catch (UnsupportedEncodingException e) {
        // only in case of malformed charset
        LOG.error(e.getLocalizedMessage(), e);
    }
}

From source file:annis.libgui.Helper.java

public static CorpusConfig getCorpusConfig(String corpus) {
    CorpusConfig corpusConfig = new CorpusConfig();
    corpusConfig.setConfig(new TreeMap<String, String>());

    try {/*from  w  ww  .  j a  va 2  s.  c om*/
        corpusConfig = Helper.getAnnisWebResource().path("query").path("corpora")
                .path(URLEncoder.encode(corpus, "UTF-8")).path("config").get(CorpusConfig.class);
    } catch (UnsupportedEncodingException ex) {
        Notification.show("could not query corpus configuration", ex.getLocalizedMessage(),
                Notification.Type.TRAY_NOTIFICATION);
    } catch (UniformInterfaceException ex) {
        Notification.show("could not query corpus configuration", ex.getLocalizedMessage(),
                Notification.Type.WARNING_MESSAGE);
    }
    return corpusConfig;
}

From source file:org.zenoss.zep.dao.impl.ConfigDaoImpl.java

private static Object valueFromString(FieldDescriptor field, Builder builder, String strValue)
        throws ZepException {
    if (field.isRepeated()) {
        throw new ZepException("Repeated field not supported");
    }//  w ww .j  a va  2s .  c o  m
    switch (field.getJavaType()) {
    case BOOLEAN:
        return Boolean.valueOf(strValue);
    case BYTE_STRING:
        try {
            return ByteString.copyFrom(Base64.decodeBase64(strValue.getBytes("US-ASCII")));
        } catch (UnsupportedEncodingException e) {
            // This exception should never happen - US-ASCII always exists in JVM
            throw new RuntimeException(e.getLocalizedMessage(), e);
        }
    case DOUBLE:
        return Double.valueOf(strValue);
    case ENUM:
        return field.getEnumType().findValueByNumber(Integer.valueOf(strValue));
    case FLOAT:
        return Float.valueOf(strValue);
    case INT:
        return Integer.valueOf(strValue);
    case LONG:
        return Long.valueOf(strValue);
    case MESSAGE:
        try {
            return JsonFormat.merge(strValue, builder.newBuilderForField(field));
        } catch (IOException e) {
            throw new ZepException(e.getLocalizedMessage(), e);
        }
    case STRING:
        return strValue;
    default:
        throw new ZepException("Unsupported type: " + field.getType());
    }
}

From source file:com.nextgis.mobile.map.LocalGeoJsonLayer.java

/**
 * Create a LocalGeoJsonLayer from the GeoJson data submitted by uri.
 *//*  ww w .  j  a va  2s.  c  om*/
protected static void create(final MapBase map, String layerName, Uri uri) {

    String sErr = map.getContext().getString(R.string.error_occurred);
    ProgressDialog progressDialog = new ProgressDialog(map.getContext());

    try {
        InputStream inputStream = map.getContext().getContentResolver().openInputStream(uri);
        if (inputStream != null) {

            progressDialog.setMessage(map.getContext().getString(R.string.message_loading_progress));
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setCancelable(true);
            progressDialog.show();

            int nSize = inputStream.available();
            int nIncrement = 0;
            progressDialog.setMax(nSize);

            //read all geojson
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            StringBuilder responseStrBuilder = new StringBuilder();

            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                nIncrement += inputStr.length();
                progressDialog.setProgress(nIncrement);
                responseStrBuilder.append(inputStr);
            }

            progressDialog.setMessage(map.getContext().getString(R.string.message_opening_progress));

            JSONObject geoJSONObject = new JSONObject(responseStrBuilder.toString());

            if (!geoJSONObject.has(GEOJSON_TYPE)) {
                sErr += ": " + map.getContext().getString(R.string.error_geojson_unsupported);
                Toast.makeText(map.getContext(), sErr, Toast.LENGTH_SHORT).show();
                progressDialog.hide();
                return;
            }

            //check crs
            boolean isWGS84 = true; //if no crs tag - WGS84 CRS

            if (geoJSONObject.has(GEOJSON_CRS)) {
                JSONObject crsJSONObject = geoJSONObject.getJSONObject(GEOJSON_CRS);

                //the link is unsupported yet.
                if (!crsJSONObject.getString(GEOJSON_TYPE).equals(GEOJSON_NAME)) {
                    sErr += ": " + map.getContext().getString(R.string.error_geojson_crs_unsupported);
                    Toast.makeText(map.getContext(), sErr, Toast.LENGTH_SHORT).show();
                    progressDialog.hide();
                    return;
                }

                JSONObject crsPropertiesJSONObject = crsJSONObject.getJSONObject(GEOJSON_PROPERTIES);
                String crsName = crsPropertiesJSONObject.getString(GEOJSON_NAME);

                if (crsName.equals("urn:ogc:def:crs:OGC:1.3:CRS84")) { // WGS84
                    isWGS84 = true;
                } else if (crsName.equals("urn:ogc:def:crs:EPSG::3857")) { //Web Mercator
                    isWGS84 = false;
                } else {
                    sErr += ": " + map.getContext().getString(R.string.error_geojson_crs_unsupported);
                    Toast.makeText(map.getContext(), sErr, Toast.LENGTH_SHORT).show();
                    progressDialog.hide();
                    return;
                }
            }

            //load contents to memory and reproject if needed
            JSONArray geoJSONFeatures = geoJSONObject.getJSONArray(GEOJSON_TYPE_FEATURES);

            if (0 == geoJSONFeatures.length()) {
                sErr += ": " + map.getContext().getString(R.string.error_geojson_crs_unsupported);
                Toast.makeText(map.getContext(), sErr, Toast.LENGTH_SHORT).show();
                progressDialog.hide();
                return;
            }

            List<Feature> features = geoJSONFeaturesToFeatures(geoJSONFeatures, isWGS84, map.getContext(),
                    progressDialog);

            create(map, layerName, features);
        }

    } catch (UnsupportedEncodingException e) {
        Log.d(TAG, "Exception: " + e.getLocalizedMessage());
        sErr += ": " + e.getLocalizedMessage();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "Exception: " + e.getLocalizedMessage());
        sErr += ": " + e.getLocalizedMessage();
    } catch (IOException e) {
        Log.d(TAG, "Exception: " + e.getLocalizedMessage());
        sErr += ": " + e.getLocalizedMessage();
    } catch (JSONException e) {
        Log.d(TAG, "Exception: " + e.getLocalizedMessage());
        sErr += ": " + e.getLocalizedMessage();
    }

    progressDialog.hide();
    //if we here something wrong occurred
    Toast.makeText(map.getContext(), sErr, Toast.LENGTH_SHORT).show();
}

From source file:devbox.com.br.minercompanion.LoginActivity.java

public static String POST(String url, String data) {
    InputStream inputStream = null;
    String result = "";

    try {/* ww w. j ava2 s  .co m*/

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            //String usuarios = jsonParser.getAllUsuariosAsJson().toString();

            //Log.i("USUARIOS", usuarios);
            Log.d("Dados sendo enviado: ", data);

            //params.add(new BasicNameValuePair("usuarios", usuarios));
            params.add(new BasicNameValuePair("login", data));

            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse response = httpclient.execute(httpPost);

            inputStream = response.getEntity().getContent();

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 10. convert inputstream to string
        if (inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Resultado Nulo";

    } catch (Exception e) {
        Log.i("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

public static String encodePostBody(Bundle parameters) {
    if (parameters == null) {
        return "";
    }/*from  w  w w .j a va2s  .  co m*/

    StringBuilder sb = new StringBuilder();

    for (Iterator<String> i = parameters.keySet().iterator(); i.hasNext();) {
        String key = i.next();
        Object parameter = parameters.get(key);
        if (!(parameter instanceof String)) {
            continue;
        }

        try {
            sb.append(URLEncoder.encode(key, "UTF-8"));
            sb.append("=");
            sb.append(URLEncoder.encode((String) parameter, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO report parse error
            LoggingUtils.e(LOG_TAG, "Error encoding \"" + key + "\" or \"" + parameter + "\" to UTF-8 ."
                    + e.getLocalizedMessage(), null);
        }

        if (i.hasNext()) {
            sb.append("&");
        }
    }
    return sb.toString();
}

From source file:com.cubusmail.mail.text.MessageTextUtil.java

/**
 * Reads a string from given input stream using direct buffering
 * /*w w  w  .  j  a v  a 2 s  . co m*/
 * @param inStream
 *            - the input stream
 * @param charset
 *            - the charset
 * @return the <code>String</code> read from input stream
 * @throws IOException
 *             - if an I/O error occurs
 */
public static String readStream(final InputStream inStream, final String charset) throws IOException {

    InputStreamReader isr = null;
    try {
        int count = 0;
        final char[] c = new char[BUFSIZE];
        isr = new InputStreamReader(inStream, charset);
        if ((count = isr.read(c)) > 0) {
            final StringBuilder sb = new StringBuilder(STRBLD_SIZE);
            do {
                sb.append(c, 0, count);
            } while ((count = isr.read(c)) > 0);
            return sb.toString();
        }
        return "";
    } catch (final UnsupportedEncodingException e) {
        log.error("Unsupported encoding in a message detected and monitored.", e);
        return "";
    } finally {
        if (null != isr) {
            try {
                isr.close();
            } catch (final IOException e) {
                log.error(e.getLocalizedMessage(), e);
            }
        }
    }
}

From source file:devbox.com.br.minercompanion.ProfileActivity.java

public static String POST(String url, String data, boolean isLoggingOut){
    InputStream inputStream = null;
    String result = "";

    try {// w w w  . j  av a  2s  . c o m

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);


        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            //String usuarios = jsonParser.getAllUsuariosAsJson().toString();

            //Log.i("USUARIOS", usuarios);
            Log.d(TAG, "Dados sendo enviado: " + data);

            //params.add(new BasicNameValuePair("usuarios", usuarios));
            if(isLoggingOut) {
                params.add(new BasicNameValuePair("logout", data));

            } else {
                params.add(new BasicNameValuePair("log", data));
            }


            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse response = httpclient.execute(httpPost);

            inputStream = response.getEntity().getContent();

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Resultado Nulo";

    } catch (Exception e) {
        Log.i(TAG, e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}