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:com.httprequest.HTTPRequest.java

/**
 * Send synchronous request to HTTP server.
 * //www  .j a v  a2  s .  c o m
 * @param method  request method (GET or POST).
 * @param params set of pairs <key, value>, fields.
 * @param listenr interface (callback) to bind to external classes.
 * @return response of HTTP Server.
 */
private String HTTPSyncRequest(Methods method, JSONObject params, OnHTTPRequest listenr) {
    Log.i(LOG_TAG, "HTTPSyncRequest(" + method + ")");

    List<NameValuePair> requestParams = null;
    HttpRequestBase httpRequest = null;
    OnHTTPRequest listener = listenr;

    try {
        requestParams = jsonToList(params);
    } catch (JSONException e1) {
        e1.printStackTrace();
    }
    // Set parameters of HTTP request.
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    // Create a new HttpClient and Header
    HttpClient httpclient = new DefaultHttpClient(httpParameters);

    if (method == Methods.GET) {
        httpRequest = new HttpGet(URLServer + "?" + URLEncodedUtils.format(requestParams, "utf-8"));
    } else {
        httpRequest = new HttpPost(URLServer);

        // Add data to request
        try {
            ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(requestParams));
        } catch (UnsupportedEncodingException e) {
            listener.OnResquestError(e.getMessage().toString());
            e.printStackTrace();
        }
    }

    try {
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httpRequest);

        Log.i(LOG_TAG, "Code: " + response.getStatusLine().getStatusCode());

        // Response
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return getHTTPResponseContent(response);
        } else {
            listener.OnResquestError("Server Error");
        }

    } catch (SocketTimeoutException e) {
        listener.OnResquestError("Socket Timeout" + e.getMessage().toString());
        Log.e(LOG_TAG, "Socket Timeout", e);
    } catch (ConnectTimeoutException e) {
        listener.OnResquestError("Connect Timeout" + e.getMessage().toString());
        Log.e(LOG_TAG, "Connect Timeout", e);
    } catch (ClientProtocolException e) {
        listener.OnResquestError("HTTP Error: " + e.getMessage().toString());
        Log.e(LOG_TAG, "HTTP Error", e);
    } catch (IOException e) {
        listener.OnResquestError("Connection Error: " + e.getMessage().toString());
        Log.e(LOG_TAG, "Connection Error", e);
    }

    return null;
}

From source file:com.wso2telco.dep.mediator.ResponseHandler.java

/**
 * Make query sms status response./*from w  w  w. ja  v a  2  s  .c  o m*/
 *
 * @param mc
 *            the mc
 * @param senderAddress
 *            the sender address
 * @param requestid
 *            the requestid
 * @param responseMap
 *            the response map
 * @return the string
 */
public String makeQuerySmsStatusResponse(MessageContext mc, String senderAddress, String requestid,
        Map<String, QuerySMSStatusResponse> responseMap) {
    log.info("Building Query SMS Status Response" + " Request ID: " + UID.getRequestID(mc));
    Gson gson = new GsonBuilder().create();
    QuerySMSStatusResponse finalResponse = new QuerySMSStatusResponse();

    DeliveryInfoList deliveryInfoListObj = new DeliveryInfoList();
    List<DeliveryInfo> deliveryInfoList = new ArrayList<DeliveryInfo>(responseMap.size());

    for (Map.Entry<String, QuerySMSStatusResponse> entry : responseMap.entrySet()) {
        QuerySMSStatusResponse statusResponse = entry.getValue();
        if (statusResponse != null) {
            DeliveryInfo[] resDeliveryInfos = statusResponse.getDeliveryInfoList().getDeliveryInfo();
            Collections.addAll(deliveryInfoList, resDeliveryInfos);
        } else {
            DeliveryInfo deliveryInfo = new DeliveryInfo();
            deliveryInfo.setAddress(entry.getKey());
            deliveryInfo.setDeliveryStatus("DeliveryImpossible");
            deliveryInfoList.add(deliveryInfo);
        }
    }
    deliveryInfoListObj.setDeliveryInfo(deliveryInfoList.toArray(new DeliveryInfo[deliveryInfoList.size()]));
    try {
        senderAddress = URLEncoder.encode(senderAddress, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    }
    String resourceURL = getResourceURL(mc, senderAddress) + "/requests/" + requestid + "/deliveryInfos";
    deliveryInfoListObj.setResourceURL(resourceURL);

    finalResponse.setDeliveryInfoList(deliveryInfoListObj);

    ((Axis2MessageContext) mc).getAxis2MessageContext().setProperty("HTTP_SC", 200);
    ((Axis2MessageContext) mc).getAxis2MessageContext().setProperty("messageType", "application/json");
    return gson.toJson(finalResponse);
}

From source file:org.commonjava.tensor.maven.plugin.LogProjectBuildroot.java

@Override
public void execute() throws MojoExecutionException {
    if (isThisTheExecutionRoot()) {
        final ModuleAssociations moduleAssoc = new ModuleAssociations(
                new ProjectVersionRef(project.getGroupId(), project.getArtifactId(), project.getVersion()));
        for (final MavenProject p : projects) {
            moduleAssoc.addModule(new ProjectVersionRef(p.getGroupId(), p.getArtifactId(), p.getVersion()));
        }//from   w  w w  . j  a va 2  s. c  o m

        final TensorSerializerProvider prov = new TensorSerializerProvider(
                new EGraphManager(new JungEGraphDriver()), new GraphWorkspaceHolder());

        final JsonSerializer serializer = prov.getTensorSerializer();

        final String json = serializer.toString(moduleAssoc);
        final DefaultHttpClient client = new DefaultHttpClient();

        try {
            final HttpPut request = new HttpPut(getUrl());
            request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            request.setEntity(new StringEntity(json));

            final HttpResponse response = client.execute(request);

            final StatusLine sl = response.getStatusLine();
            if (sl.getStatusCode() != HttpStatus.SC_CREATED) {
                throw new MojoExecutionException("Failed to publish module-artifact association data: "
                        + sl.getStatusCode() + " " + sl.getReasonPhrase());
            }
        } catch (final UnsupportedEncodingException e) {
            throw new MojoExecutionException(
                    "Failed to publish module-artifact association data; invalid encoding for JSON: "
                            + e.getMessage(),
                    e);
        } catch (final ClientProtocolException e) {
            throw new MojoExecutionException(
                    "Failed to publish module-artifact association data; http request failed: "
                            + e.getMessage(),
                    e);
        } catch (final IOException e) {
            throw new MojoExecutionException(
                    "Failed to publish module-artifact association data; http request failed: "
                            + e.getMessage(),
                    e);
        }
    }
}

From source file:com.microsoft.aad.adal.IdToken.java

private HashMap<String, String> parseJWT(final String idtoken) throws AuthenticationException {
    final String idbody = extractJWTBody(idtoken);
    // URL_SAFE: Encoder/decoder flag bit to use
    // "URL and filename safe" variant of Base64
    // (see RFC 3548 section 4) where - and _ are used in place of +
    // and /.//ww  w .j ava 2s .com
    final byte[] data = Base64.decode(idbody, Base64.URL_SAFE);

    try {
        final String decodedBody = new String(data, "UTF-8");
        final HashMap<String, String> responseItems = extractJsonObjects(decodedBody);
        return responseItems;
    } catch (UnsupportedEncodingException exception) {
        Logger.e(TAG, "The encoding is not supported.", "", ADALError.ENCODING_IS_NOT_SUPPORTED, exception);
        throw new AuthenticationException(ADALError.ENCODING_IS_NOT_SUPPORTED, exception.getMessage(),
                exception);
    } catch (JSONException exception) {
        Logger.e(TAG, "Failed to parse the decoded body into JsonObject.", "", ADALError.JSON_PARSE_ERROR,
                exception);
        throw new AuthenticationException(ADALError.JSON_PARSE_ERROR, exception.getMessage(), exception);
    }
}

From source file:com.sdl.odata.renderer.batch.ODataBatchRequestRenderer.java

private String getRenderedXML(ProcessorResult result) throws ODataException {
    LOG.debug("Content Type not specified. Atom Renderer will be used to render the result data");
    AbstractRenderer atomRenderer = new AtomRenderer();
    ODataResponse.Builder builder = new ODataResponse.Builder().setStatus(result.getStatus());

    atomRenderer.render(result.getRequestContext(), result.getQueryResult(), builder);

    try {/*from  w ww  .j  ava 2  s .  c o m*/
        return builder.build().getBodyText(StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        throw new ODataRenderException("Unsupported encoding", e.getMessage());
    }
}

From source file:com.threewks.thundr.http.service.gae.HttpServiceImpl.java

protected String encodeParameter(String value) {
    try {//from  www.j  ava2s.c  o m
        return URLEncoder.encode(value, StringPool.UTF_8);
    } catch (UnsupportedEncodingException e) {
        throw new HttpRequestException(e, "Unable to format the parameter using %s: %s", StringPool.UTF_8,
                e.getMessage());
    }
}

From source file:de.micromata.genome.gwiki.controls.GWikiViewAllPagesActionBean.java

public Map<String, String> decode(String search) {
    if (StringUtils.isEmpty(search) == true) {
        return Collections.emptyMap();
    }/*from w ww  .  ja  va2 s  .c om*/
    Map<String, String> parmsMap = new HashMap<String, String>();
    String params[] = search.split("&");

    for (String param : params) {
        String temp[] = param.split("=");
        if (temp.length < 2) {
            continue;
        }
        if (StringUtils.isEmpty(temp[0]) == true || StringUtils.isEmpty(temp[1]) == true) {
            continue;
        }
        try {
            parmsMap.put(temp[0], java.net.URLDecoder.decode(temp[1], "UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(
                    "Cannot decode url param: " + temp[0] + "=" + temp[1] + "; " + ex.getMessage(), ex);
        }
    }
    return parmsMap;
}

From source file:com.scooterframework.web.controller.ScooterRequestFilter.java

private String decode(String s) {
    String ss = s;/*  w  w  w.  java 2  s. c  o  m*/
    try {
        ss = URLDecoder.decode(s, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.warn("Failed to decode \"" + s + "\" because " + e.getMessage());
    }
    return ss;
}

From source file:uk.co.uwcs.choob.modules.HttpModule.java

private String performRequest(final String contentType, final String url, final String user, final String pass,
        final Map<String, String> headers, final Map<String, String> params, final int requestType) {

    // add user and pass to client credentials if present
    if ((user != null) && (pass != null)) {
        HttpModule.client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, pass));
    }/*from   ww  w  .  j  a  va2  s  .  c  om*/

    // process headers using request interceptor
    final Map<String, String> sendHeaders = new HashMap<String, String>();
    // add encoding header for gzip if not present
    if (!sendHeaders.containsKey(HttpModule.ACCEPT_ENCODING)) {
        sendHeaders.put(HttpModule.ACCEPT_ENCODING, HttpModule.GZIP);
    }
    if ((headers != null) && (headers.size() > 0)) {
        sendHeaders.putAll(headers);
    }
    if (requestType == HttpModule.POST_TYPE) {
        sendHeaders.put(HttpModule.CONTENT_TYPE, contentType);
    }
    if (sendHeaders.size() > 0) {
        HttpModule.client.addRequestInterceptor(new HttpRequestInterceptor() {
            @Override
            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));
                    }
                }
            }
        });
    }

    // handle POST or GET request respectively
    HttpRequestBase method = null;
    if (requestType == HttpModule.POST_TYPE) {
        method = new HttpPost(url);
        // data - name/value params
        List<NameValuePair> nvps = null;
        if ((params != null) && (params.size() > 0)) {
            nvps = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        if (nvps != null) {
            try {
                HttpPost methodPost = (HttpPost) method;
                methodPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("Error peforming HTTP request: " + e.getMessage(), e);
            }
        }
    } else if (requestType == HttpModule.GET_TYPE) {
        method = new HttpGet(url);
    }

    // execute request
    return execute(method);
}

From source file:com.opentok.Session.java

/**
 * Creates a token for connecting to an OpenTok session. In order to authenticate a user
 * connecting to an OpenTok session that user must pass an authentication token along with
 * the API key.//  w  ww. j a  v a2 s .co m
 *
 * @param tokenOptions This TokenOptions object defines options for the token.
 * These include the following:
 *
 * <ul>
 *    <li>The role of the token (subscriber, publisher, or moderator)</li>
 *    <li>The expiration time of the token</li>
 *    <li>Connection data describing the end-user</li>
 * </ul>
 *
 * @return The token string.
 */
public String generateToken(TokenOptions tokenOptions) throws OpenTokException {

    // Token format
    //
    // | ------------------------------  tokenStringBuilder ----------------------------- |
    // | "T1=="+Base64Encode(| --------------------- innerBuilder --------------------- |)|
    //                       | "partner_id={apiKey}&sig={sig}:| -- dataStringBuilder -- |

    if (tokenOptions == null) {
        throw new InvalidArgumentException("Token options cannot be null");
    }

    Role role = tokenOptions.getRole();
    double expireTime = tokenOptions.getExpireTime(); // will be 0 if nothing was explicitly set
    String data = tokenOptions.getData(); // will be null if nothing was explicitly set
    Long create_time = new Long(System.currentTimeMillis() / 1000).longValue();

    StringBuilder dataStringBuilder = new StringBuilder();
    Random random = new Random();
    int nonce = random.nextInt();
    dataStringBuilder.append("session_id=");
    dataStringBuilder.append(sessionId);
    dataStringBuilder.append("&create_time=");
    dataStringBuilder.append(create_time);
    dataStringBuilder.append("&nonce=");
    dataStringBuilder.append(nonce);
    dataStringBuilder.append("&role=");
    dataStringBuilder.append(role);

    double now = System.currentTimeMillis() / 1000L;
    if (expireTime == 0) {
        expireTime = now + (60 * 60 * 24); // 1 day
    } else if (expireTime < now - 1) {
        throw new InvalidArgumentException(
                "Expire time must be in the future. relative time: " + (expireTime - now));
    } else if (expireTime > (now + (60 * 60 * 24 * 30) /* 30 days */)) {
        throw new InvalidArgumentException("Expire time must be in the next 30 days. too large by "
                + (expireTime - (now + (60 * 60 * 24 * 30))));
    }
    // NOTE: Double.toString() would print the value with scientific notation
    dataStringBuilder.append(String.format("&expire_time=%.0f", expireTime));

    if (data != null) {
        if (data.length() > 1000) {
            throw new InvalidArgumentException(
                    "Connection data must be less than 1000 characters. length: " + data.length());
        }
        dataStringBuilder.append("&connection_data=");
        try {
            dataStringBuilder.append(URLEncoder.encode(data, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new InvalidArgumentException(
                    "Error during URL encode of your connection data: " + e.getMessage());
        }
    }

    StringBuilder tokenStringBuilder = new StringBuilder();
    try {
        tokenStringBuilder.append("T1==");

        StringBuilder innerBuilder = new StringBuilder();
        innerBuilder.append("partner_id=");
        innerBuilder.append(this.apiKey);

        innerBuilder.append("&sig=");

        innerBuilder.append(Crypto.signData(dataStringBuilder.toString(), this.apiSecret));
        innerBuilder.append(":");
        innerBuilder.append(dataStringBuilder.toString());

        tokenStringBuilder.append(Base64.encodeBase64String(innerBuilder.toString().getBytes("UTF-8"))
                .replace("+", "-").replace("/", "_"));

        // if we only wanted Java 7 and above, we could DRY this into one catch clause
    } catch (SignatureException e) {
        throw new OpenTokException("Could not generate token, a signing error occurred.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new OpenTokException("Could not generate token, a signing error occurred.", e);
    } catch (InvalidKeyException e) {
        throw new OpenTokException("Could not generate token, a signing error occurred.", e);
    } catch (UnsupportedEncodingException e) {
        throw new OpenTokException("Could not generate token, a signing error occurred.", e);
    }

    return tokenStringBuilder.toString();
}