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:org.mulgara.store.jxunit.SparqlQueryJX.java

/**
 * Execute a query against a SPARQL endpoint.
 * @param endpoint The URL of the endpoint.
 * @param query The query to execute./*from  w  ww . j  av  a2 s  . com*/
 * @param defGraph The default graph to execute the query against,
 *        or <code>null</code> if not set.
 * @return A string representation of the result from the server.
 * @throws IOException If there was an error communicating with the server.
 * @throws UnsupportedEncodingException The SPARQL endpoint used an encoding not understood by this system.
 * @throws HttpClientException An unexpected response was returned from the SPARQL endpoint.
 */
String executeQuery(String endpoint, String query, URI defGraph)
        throws IOException, UnsupportedEncodingException, HttpClientException {
    String request = endpoint + "?";
    if (defGraph != null && (0 != defGraph.toString().length()))
        request += "default-graph-uri=" + defGraph.toString() + "&";
    request += "query=" + URLEncoder.encode(query, UTF8);
    requestUrl = request;

    HttpClient client = new DefaultHttpClient();
    client.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    HttpGet get = new HttpGet(request);
    get.setHeader("Accept", "application/rdf+xml");

    StringBuilder result = new StringBuilder();
    try {
        HttpResponse response = client.execute(get);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HttpStatus.SC_OK) {
            String msg = "Bad result from SPARQL endpoint: " + status;
            System.err.println(msg);
            throw new HttpClientException(msg);
        }

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStreamReader resultStream = new InputStreamReader(entity.getContent());
            char[] buffer = new char[BUFFER_SIZE];
            int len;
            while ((len = resultStream.read(buffer)) >= 0)
                result.append(buffer, 0, len);
            resultStream.close();
        } else {
            String msg = "No data in response from SPARQL endpoint";
            System.out.println(msg);
            throw new HttpClientException(msg);
        }
    } catch (UnsupportedEncodingException e) {
        System.err.println("Unsupported encoding returned from SPARQL endpoint: " + e.getMessage());
        throw e;
    } catch (IOException ioe) {
        System.err.println("Error communicating with SPARQL endpoint: " + ioe.getMessage());
        throw ioe;
    }
    return result.toString();
}

From source file:it.txt.ens.client.publisher.impl.osgi.test.BasicENSPublisherTest.java

private void publishEvent(String message) {
    try {//  w  w w. j  a va2s  .  co m
        ENSEvent event = eventFactory.create(null, message.getBytes(ENSEvent.DEFAULT_CONTENT_ENCODING),
                new Date(), true);
        publisher.publish(event);

        LOGGER.info("Published event:: " + event.toString());

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } catch (IllegalStateException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } catch (ENSPublishingException e) {
        fail(e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.alibaba.openapi.client.rpc.AbstractHttpRequestBuilder.java

public HttpRequest getHttpRequest(InvokeContext context) {
    final RequestPolicy requestPolicy = context.getPolicy();
    final StringBuilder path = getProtocolRequestPath(context, getProtocol());
    final StringBuilder queryString = new StringBuilder();
    final String method;
    final List<NameValuePair> parameters = buildParams(context);
    buildSysParams(parameters, queryString, context, requestPolicy);
    HttpEntity entity = null;//w w  w.j a va  2s.  c om
    switch (requestPolicy.getHttpMethod()) {
    case POST:
        method = METHOD_POST;
        break;
    case GET:
        method = METHOD_GET;
        break;
    case AUTO:
        if (hasParameters(parameters) || hasAttachments(context.getRequest())) {
            method = METHOD_POST;
        } else {
            method = METHOD_GET;
        }
        break;
    default:
        method = METHOD_POST;
    }
    if (hasParameters(parameters)) {
        if (METHOD_GET.equals(method)) {
            if (queryString.length() > 0) {
                queryString.append(PARAMETER_SEPARATOR);
            }
            queryString.append(URLEncodedUtils.format(parameters, requestPolicy.getQueryStringCharset()));
        } else {
            try {
                entity = new UrlEncodedFormEntity(parameters, requestPolicy.getContentCharset());
            } catch (UnsupportedEncodingException e) {
                throw new IllegalArgumentException(e.getMessage(), e);
            }
        }
    }
    signature(path, queryString, parameters, requestPolicy);
    HttpRequest httpRequest;
    try {
        httpRequest = requestFactory.newHttpRequest(method, getApiRequestPath(context, requestPolicy)
                .append('/').append(path).append(QUERY_STRING_SEPARATOR).append(queryString).toString());
    } catch (MethodNotSupportedException e) {
        throw new UnsupportedOperationException("Unsupported http request method:" + e.getMessage(), e);
    }
    if (httpRequest instanceof BasicHttpEntityEnclosingRequest) {
        if (hasAttachments(context.getRequest())) {
            MultipartEntity multipartEntity = new MultipartEntity();
            for (Entry<String, String> entry : context.getRequest().getAttachments().entrySet()) {
                File file = new File(entry.getValue());
                multipartEntity.addPart(entry.getKey(), new FileBody(file));
            }
            entity = multipartEntity;
        } else if (requestPolicy.getRequestCompressThreshold() >= 0
                && entity.getContentLength() > requestPolicy.getRequestCompressThreshold()) {
            entity = new GzipCompressingNEntity(entity);
            httpRequest.addHeader("Content-Encoding", "gzip");
        }
        ((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(entity);
    }
    //        httpRequest.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    //        httpRequest.addHeader("Accept-Charset", "gb18030,utf-8;q=0.7,*;q=0.3");
    //        httpRequest.addHeader("Accept-Encoding", "gzip,deflate,sdch");
    //        httpRequest.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
    //        httpRequest.addHeader("Cache-Control", "max-age=0");
    //        httpRequest.addHeader("Connection", "keep-alive");
    return httpRequest;
}

From source file:org.belio.service.gateway.AirtelCharging.java

public String chargeSms(Outbox outbox) {
    String x = "no change ";
    try {/*  w  w w. j  a  v a2s. c  o m*/
        //            String sourceCode = outbox.getShortCode();
        //            String phone = "254736375819";
        //            //String phone = outbox.getMsisdn();
        //            String contentid = String.valueOf(outbox.getRefNo());
        //            String itemName = String.valueOf(outbox.getRefNo());
        //            String contentDescription = URLEncoder.encode(outbox.getText(), "UTF-8");
        //            String actualPrice = "5";
        //            String contentMediaType = outbox.getShortCode();
        //            String contentUrl = URLEncoder.encode(outbox.getText(), "UTF-8");
        String sourceCode = "22554";
        String phone = "254736375819";
        String contentid = String.valueOf(Math.abs(new Random().nextInt()));
        String itemName = String.valueOf(Math.abs(new Random().nextInt()));
        String contentDescription = "sms";
        String actualPrice = "5";
        String contentMediaType = URLDecoder.decode(URLEncoder.encode("sasa jacktone test", "UTF-8"), "UTF-8");
        String xml = xmlRequest(sourceCode, phone, contentid, itemName, contentDescription, actualPrice,
                contentMediaType);
        x = sendXmlOverPost(networkproperties.getProperty("airtel_charging_url"), xml);
    } catch (UnsupportedEncodingException ex) {
        Launcher.LOG.info(ex.getMessage());
    } catch (Exception ex) {
        Launcher.LOG.info(ex.getMessage());
    }
    return x;
}

From source file:com.securekey.sdk.sample.AuthenticateDeviceActivity.java

/**
 * Implementation of Briidge.AuthenticateDeviceListener.authenticateDeviceComplete
 * or Briidge.AuthenticateDeviceReturnJWSListener.authenticateDeviceComplete
 *//*from   ww w  .  jav a  2  s .c om*/
@Override
public void authenticateDeviceComplete(int status, String txnId) {
    dismissProgressDialog();
    if (status == Briidge.STATUS_OK) {
        if (txnId != null) {

            if (this.jwsExpected) {

                // The JWT should be provide to a third party to be verify
                // It could be parse to see what's inside 

                dismissProgressDialog();
                String[] jwtSegment = getJWSSegments(txnId);
                try {
                    final StringBuilder message = new StringBuilder();
                    message.append(new String(Base64.decode(jwtSegment[0], Base64.NO_WRAP), "UTF-8") + "\n");
                    message.append(
                            new String(Base64.decode(jwtSegment[1], Base64.NO_WRAP), "UTF-8") + "\n\n\n");
                    showDialog(message.toString());

                    // JWT could be check on server side
                    verifyJWT(txnId);
                } catch (UnsupportedEncodingException e) {
                    Log.e(VerifyQuickCodeActivity.class.toString(), e.getMessage());
                }

            } else {

                getDeviceId(txnId);
            }
        } else {
            showDialog("Error: null data!");
        }
    } else if (status == Briidge.STATUS_CONNECTIVITY_ERROR) {
        showDialog("Error connecting to server!");
    } else {
        showDialog("Error processing request!");
    }
}

From source file:lu.list.itis.dkd.aig.template.TemplateService.java

protected Response storeTemplate(final ServletContext context, final InputStream stream, final String name,
        final String folder) {
    try {/* ww  w  .  j  av  a 2s .  c  o m*/
        TemplateManager.store(context, stream, name, folder);
        return Response.ok().build();
    } catch (final UnsupportedEncodingException e) {
        Logger.getLogger(TemplateService.class.getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
        return Response.serverError()
                .entity("UTF-8 was not supported by the stream reader!\n" + ExceptionUtils.getStackTrace(e)) //$NON-NLS-1$
                .build();
    } catch (final IOException e) {
        Logger.getLogger(TemplateService.class.getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
        return Response.serverError().entity(
                "An error occured while attempting to store the template!\n" + ExceptionUtils.getStackTrace(e)) //$NON-NLS-1$
                .build();
    }
}

From source file:fedroot.dacs.http.DacsPostRequest.java

private HttpPost urlEncodedPost(WebServiceRequest webServiceRequest) {
    HttpPost urlEncodedPost = new HttpPost(webServiceRequest.getBaseURI());
    try {/* www. j  a  v a  2  s  . co  m*/
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
                webServiceRequest.getNameValuePairs());
        // urlEncodedFormEntity = new UrlEncodedFormEntity(dacsWebServiceRequest.getNameValuePairs(), "UTF-8");
        urlEncodedPost.setEntity(urlEncodedFormEntity);
        return urlEncodedPost;
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(DacsPostRequest.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException("Invalid DacsWebServiceRequest parameters " + ex.getMessage());
    }
}

From source file:com.neusoft.mid.clwapi.service.homePage.HomePageServiceImpl.java

/**
 * ??/*from   w  ww. ja  v a  2 s . co m*/
 * 
 * @param region
 *            ?(?uri)
 * @return ?
 */
@Override
public String getWeather(String token, String region) {
    logger.info("???");
    logger.info("??[ " + region + " ]?");

    region = StringUtils.strip(region);

    try {
        region = URLDecoder.decode(region, HttpConstant.CHARSET);
    } catch (UnsupportedEncodingException e) {
        logger.error("URL?" + e.getMessage());
        throw new ApplicationException(ErrorConstant.ERROR90000, Response.Status.INTERNAL_SERVER_ERROR);
    }
    logger.info("URL?[ " + region + " ]");

    if (region == null || region.equals("null")) {
        logger.error("?????NULL");
        throw new ApplicationException(ErrorConstant.ERROR10001, Response.Status.BAD_REQUEST);
    }

    //2014-03-14 by wuxja ?
    MemcacheCache cache = (MemcacheCache) memcacheCacheManager.getCache("CLW_API_CACHE");
    WeatherInfoResp iWeatherInfoResp = null;
    logger.info("dd" + cache.get("WEATHER_" + region));
    if (cache.get("WEATHER_" + region) != null)
        iWeatherInfoResp = (WeatherInfoResp) cache.get("WEATHER_" + region).get();
    else {
        iWeatherInfoResp = WeatherReport.getWeatherInfo(region);
        iWeatherInfoResp.setValidSeconds(18000);
        cache.put("WEATHER_" + region, iWeatherInfoResp);
    }
    logger.info("????");
    return JacksonUtils.toJsonRuntimeException(iWeatherInfoResp);
}

From source file:com.suntek.gztpb.controller.ChemicalController.java

@RequestMapping(value = "isCarrierExists.htm", method = RequestMethod.POST)
public @ResponseBody String isCarrierExists(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    response.setCharacterEncoding("utf-8");
    String carrierNo = "";
    try {//from   w  w  w .  ja  v  a2  s  .  co  m
        carrierNo = URLDecoder.decode(request.getParameter("carrierNo"), "utf-8");
    } catch (UnsupportedEncodingException e) {
        System.out.println(
                "[gztpbwebsite]?????????!"
                        + e.getMessage());
    }
    if (carrierNo == "null" || carrierNo == "") {
        return "0";
    } else {
        String carrier = chemicalService.isCarrierExists(carrierNo);
        if (carrierNo.equals("0"))
            return "0";
        else
            return java.net.URLEncoder.encode(carrier, "utf-8");
    }
}

From source file:net.anymeta.AnyMetaAPI.java

/**
 * Execute the given API call onto the anymeta instance, with arguments.
 *
 * @param method    The method, e.g. "anymeta.user.info"
 * @param args      Arguments to give to the call.
 * @return         A JSONObject or JSONArray with the response.
 * @throws AnyMetaException/*from  w  ww  .j a  v  a 2s .  co  m*/
 */
public Object doMethod(String method, Map<String, Object> args) throws AnyMetaException {

    List<NameValuePair> params = new ArrayList<NameValuePair>();

    params.add(new BasicNameValuePair("method", method));
    params.add(new BasicNameValuePair("format", "json"));

    convertParameters((Object) args, params, null);

    String url = this.entrypoint;

    OAuthConsumer consumer = new CommonsHttpOAuthConsumer(this.ckey, this.csec, SignatureMethod.PLAINTEXT);
    consumer.setTokenWithSecret(this.tkey, this.tsec);

    HttpPost request = new HttpPost(url);
    request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    // set up httppost
    try {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
        request.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        throw new AnyMetaException(e.getMessage());
    }

    try {
        consumer.sign(request);
    } catch (OAuthMessageSignerException e) {
        throw new AnyMetaException(e.getMessage());
    } catch (OAuthExpectationFailedException e) {
        throw new AnyMetaException(e.getMessage());
    }

    DefaultHttpClient client = new DefaultHttpClient();
    ResponseHandler<String> handler = new BasicResponseHandler();

    String response = "";
    try {
        response = client.execute(request, handler);
    } catch (IOException e) {
        throw new AnyMetaException(e.getMessage());
    }

    if (response.equalsIgnoreCase("null") || response.equalsIgnoreCase("false")) {
        return null;
    }

    if (!response.startsWith("[") && !response.startsWith("{")) {
        response = "{\"result\": " + response + "}";
    }

    // System.out.println(response);

    Object o;
    try {
        o = new JSONObject(response);
    } catch (JSONException e) {
        try {
            o = new JSONArray(response);
        } catch (JSONException e2) {
            throw new AnyMetaException(e.getMessage() + ": response=" + response);
        }
    }

    if (o instanceof JSONObject && ((JSONObject) o).has("err")) {
        // handle error
        try {
            JSONObject err = ((JSONObject) o).getJSONObject("err").getJSONObject("-attrib-");
            throw new AnyMetaException(err.getString("code") + ": " + err.getString("msg"));
        } catch (JSONException e) {
            throw new AnyMetaException("Unexpected response in API error: response=" + response);
        }
    }

    return o;
}