Example usage for java.io UnsupportedEncodingException getCause

List of usage examples for java.io UnsupportedEncodingException getCause

Introduction

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

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

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 .ja  v a  2  s .  c om
        // 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:com.bacic5i5j.framework.toolbox.web.WebUtils.java

/**
 * ??//from   ww w.j  a  v a2s.  c om
 *
 * @param params
 * @param url
 * @return
 */
public static String post(Map<String, String> params, String url) {
    String result = "";

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    List<NameValuePair> nvps = generateURLParams(params);
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage() + " : " + e.getCause());
    }

    CloseableHttpResponse response = null;

    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        log.error(e.getMessage() + " : " + e.getCause());
    }

    if (response != null) {
        StatusLine statusLine = response.getStatusLine();
        log.info("??: " + statusLine.getStatusCode());
        if (statusLine.getStatusCode() == 200 || statusLine.getStatusCode() == 302) {
            try {
                InputStream is = response.getEntity().getContent();
                int count = is.available();
                byte[] buffer = new byte[count];
                is.read(buffer);
                result = new String(buffer);
            } catch (IOException e) {
                log.error("???: " + e.getMessage());
            }
        }
    }

    return result;
}

From source file:net.yoomai.virgo.spider.Emulator.java

/**
 * //from   ww  w.  j av  a2 s. co m
 *
 * @param params
 * @param url
 */
public String login(Map<String, String> params, String url) {
    String cookie = "";

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    List<NameValuePair> nvps = generateURLParams(params);
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage() + " : " + e.getCause());
    }

    CloseableHttpResponse response = null;

    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        log.error(e.getMessage() + " : " + e.getCause());
    }

    if (response != null) {
        StatusLine statusLine = response.getStatusLine();
        log.info(statusLine);
        if (statusLine.getStatusCode() == 200 || statusLine.getStatusCode() == 302) {
            Header[] headers = response.getHeaders("Set-Cookie");
            for (Header header : headers) {
                cookie += header.getValue() + ";";
            }
        }
    }

    return cookie;
}

From source file:eu.seaclouds.platform.planner.core.utils.HttpHelper.java

public Pair<String, String> postRequestWithParams(String restPath, List<NameValuePair> params) {
    log.info("Posting request for " + this.serviceURL + restPath);
    HttpPost httpPost = new HttpPost(prepareRequestURL(restPath, params));
    CloseableHttpResponse response = null;
    try {/*from   w ww. java2s  .c  o m*/
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String content = "";
        int status = response.getStatusLine().getStatusCode();

        if (status == 200) {
            content = EntityUtils.toString(entity); //new Scanner(entity.getContent()).useDelimiter("\\Z").next();
        } else {
            content = response.getStatusLine().getReasonPhrase();
        }

        EntityUtils.consume(entity);
        log.info("Post success");
        return new Pair<String, String>(String.valueOf(status), content);

    } catch (UnsupportedEncodingException e) {
        log.error(e.getCause().getMessage(), e);
        return new Pair<String, String>("500", "Exception: " + e.getCause().getMessage());
    } catch (ClientProtocolException e) {
        log.error("ClientProtocolException");
        return new Pair<String, String>("500", "Exception: " + e.getCause().getMessage());
    } catch (IOException e) {
        log.error("IOException");
        return new Pair<String, String>("500", "Exception: " + e.getCause().getMessage());
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            log.error("IOException", e);
            return new Pair<String, String>("500", "Exception: " + e.getCause().getMessage());
        }
    }
}

From source file:com.gisgraphy.domain.geoloc.service.fulltextsearch.FullTextSearchEngine.java

public String executeQueryToString(FulltextQuery query) {
    try {/*from   www.  j a v  a  2 s.c  o  m*/
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        executeAndSerialize(query, outputStream);
        return outputStream.toString(Constants.CHARSET);
    } catch (UnsupportedEncodingException e) {
        throw new FullTextSearchException("Encoding error during search : " + e.getCause().getMessage());
    }
}

From source file:com.gisgraphy.fulltext.FullTextSearchEngine.java

public String executeQueryToString(FulltextQuery query) {
    try {//  w  w  w. j a v a 2s  .c  o m
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        executeAndSerialize(query, outputStream);
        return outputStream.toString(Constants.CHARSET);
    } catch (UnsupportedEncodingException e) {
        throw new FullTextSearchException("Encoding error during search : " + e.getCause().getMessage(), e);
    }
}

From source file:org.dcache.spi.dCacheStorageBackend.java

@Override
public void updateCdmiObject(String path, String targetCapabilityUri) throws BackEndException {
    LOG.debug("QoS Update of {} to target capability {}", path, targetCapabilityUri);
    String url = DCACHE_SERVER + apiPrefix + (isRestApiNew ? qosPrefixNew : "qos-management/" + "namespace")
            + path;//www .  j  ava2 s  .  c o  m
    try {
        HttpPost post = new HttpPost(url);
        post.setEntity(new StringEntity(isRestApiNew ? JsonUtils.targetCapUriToJsonNew(targetCapabilityUri)
                : JsonUtils.targetCapUriToJsonOld(targetCapabilityUri)));
        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader("Content-Type", "application/json"));
        headers.add(new BasicHeader("Accept", "application/json"));
        JSONObject response = HttpUtils.execute(post, headers);
        LOG.info("QoS Update of {} to {}: {}", path, targetCapabilityUri,
                response.getString(isRestApiNew ? "status" : "message"));
    } catch (SpiException se) {
        LOG.error("Error Updating Capability of {} to {}: {}", path, targetCapabilityUri, se.getMessage());
        throw new BackEndException(se.getMessage(), se.getCause());
    } catch (UnsupportedEncodingException ue) {
        LOG.error("Error creating request to update capability of {} to {}: {}", path, targetCapabilityUri,
                ue.getMessage());
        throw new BackEndException(ue.getMessage(), ue.getCause());
    }
}

From source file:io.openvidu.java.client.Session.java

@SuppressWarnings("unchecked")
private void getSessionIdHttp() throws OpenViduJavaClientException, OpenViduHttpException {
    if (this.hasSessionId()) {
        return;/*from  w w  w  .j a v a  2  s  . c o m*/
    }

    HttpPost request = new HttpPost(OpenVidu.urlOpenViduServer + OpenVidu.API_SESSIONS);

    JSONObject json = new JSONObject();
    json.put("mediaMode", properties.mediaMode().name());
    json.put("recordingMode", properties.recordingMode().name());
    json.put("defaultOutputMode", properties.defaultOutputMode().name());
    json.put("defaultRecordingLayout", properties.defaultRecordingLayout().name());
    json.put("defaultCustomLayout", properties.defaultCustomLayout());
    json.put("customSessionId", properties.customSessionId());
    StringEntity params = null;
    try {
        params = new StringEntity(json.toString());
    } catch (UnsupportedEncodingException e1) {
        throw new OpenViduJavaClientException(e1.getMessage(), e1.getCause());
    }

    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    request.setEntity(params);

    HttpResponse response;
    try {
        response = OpenVidu.httpClient.execute(request);
    } catch (IOException e2) {
        throw new OpenViduJavaClientException(e2.getMessage(), e2.getCause());
    }
    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
            JSONObject responseJson = httpResponseToJson(response);
            this.sessionId = (String) responseJson.get("id");
            this.createdAt = (long) responseJson.get("createdAt");
            log.info("Session '{}' created", this.sessionId);
        } else if (statusCode == org.apache.http.HttpStatus.SC_CONFLICT) {
            // 'customSessionId' already existed
            this.sessionId = properties.customSessionId();
        } else {
            throw new OpenViduHttpException(statusCode);
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}

From source file:io.openvidu.java.client.OpenVidu.java

/**
 * Starts the recording of a {@link io.openvidu.java.client.Session}
 *
 * @param sessionId  The sessionId of the session you want to start recording
 * @param properties The configuration for this recording
 *
 * @return The new created session//from ww  w .jav  a 2 s  . co  m
 * 
 * @throws OpenViduJavaClientException
 * @throws OpenViduHttpException       Value returned from
 *                                     {@link io.openvidu.java.client.OpenViduHttpException#getStatus()}
 *                                     <ul>
 *                                     <li><code>404</code>: no session exists
 *                                     for the passed <i>sessionId</i></li>
 *                                     <li><code>406</code>: the session has no
 *                                     connected participants</li>
 *                                     <li><code>422</code>: "resolution"
 *                                     parameter exceeds acceptable values (for
 *                                     both width and height, min 100px and max
 *                                     1999px) or trying to start a recording
 *                                     with both "hasAudio" and "hasVideo" to
 *                                     false</li>
 *                                     <li><code>409</code>: the session is not
 *                                     configured for using
 *                                     {@link io.openvidu.java.client.MediaMode#ROUTED}
 *                                     or it is already being recorded</li>
 *                                     <li><code>501</code>: OpenVidu Server
 *                                     recording module is disabled
 *                                     (<i>openvidu.recording</i> property set
 *                                     to <i>false</i>)</li>
 *                                     </ul>
 */
@SuppressWarnings("unchecked")
public Recording startRecording(String sessionId, RecordingProperties properties)
        throws OpenViduJavaClientException, OpenViduHttpException {

    HttpPost request = new HttpPost(OpenVidu.urlOpenViduServer + API_RECORDINGS + API_RECORDINGS_START);

    JSONObject json = new JSONObject();
    json.put("session", sessionId);
    json.put("name", properties.name());
    json.put("outputMode", properties.outputMode().name());
    json.put("hasAudio", properties.hasAudio());
    json.put("hasVideo", properties.hasVideo());

    if (Recording.OutputMode.COMPOSED.equals(properties.outputMode()) && properties.hasVideo()) {
        json.put("resolution", properties.resolution());
        json.put("recordingLayout",
                (properties.recordingLayout() != null) ? properties.recordingLayout().name() : "");
        if (RecordingLayout.CUSTOM.equals(properties.recordingLayout())) {
            json.put("customLayout", (properties.customLayout() != null) ? properties.customLayout() : "");
        }
    }

    StringEntity params = null;
    try {
        params = new StringEntity(json.toString());
    } catch (UnsupportedEncodingException e1) {
        throw new OpenViduJavaClientException(e1.getMessage(), e1.getCause());
    }

    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    request.setEntity(params);

    HttpResponse response;
    try {
        response = OpenVidu.httpClient.execute(request);
    } catch (IOException e2) {
        throw new OpenViduJavaClientException(e2.getMessage(), e2.getCause());
    }

    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
            Recording r = new Recording(httpResponseToJson(response));
            Session activeSession = OpenVidu.activeSessions.get(r.getSessionId());
            if (activeSession != null) {
                activeSession.setIsBeingRecorded(true);
            } else {
                log.warn("No active session found for sessionId '" + r.getSessionId()
                        + "'. This instance of OpenVidu Java Client didn't create this session");
            }
            return r;
        } else {
            throw new OpenViduHttpException(statusCode);
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}

From source file:io.openvidu.java.client.Session.java

/**
 * Gets a new token associated to Session object configured with
 * <code>tokenOptions</code>. This always translates into a new request to
 * OpenVidu Server// w ww.  j a v  a2  s .co m
 *
 * @return The generated token
 * 
 * @throws OpenViduJavaClientException
 * @throws OpenViduHttpException
 */
@SuppressWarnings("unchecked")
public String generateToken(TokenOptions tokenOptions)
        throws OpenViduJavaClientException, OpenViduHttpException {

    if (!this.hasSessionId()) {
        this.getSessionId();
    }

    HttpPost request = new HttpPost(OpenVidu.urlOpenViduServer + OpenVidu.API_TOKENS);

    JSONObject json = new JSONObject();
    json.put("session", this.sessionId);
    json.put("role", tokenOptions.getRole().name());
    json.put("data", tokenOptions.getData());
    if (tokenOptions.getKurentoOptions() != null) {
        JSONObject kurentoOptions = new JSONObject();
        if (tokenOptions.getKurentoOptions().getVideoMaxRecvBandwidth() != null) {
            kurentoOptions.put("videoMaxRecvBandwidth",
                    tokenOptions.getKurentoOptions().getVideoMaxRecvBandwidth());
        }
        if (tokenOptions.getKurentoOptions().getVideoMinRecvBandwidth() != null) {
            kurentoOptions.put("videoMinRecvBandwidth",
                    tokenOptions.getKurentoOptions().getVideoMinRecvBandwidth());
        }
        if (tokenOptions.getKurentoOptions().getVideoMaxSendBandwidth() != null) {
            kurentoOptions.put("videoMaxSendBandwidth",
                    tokenOptions.getKurentoOptions().getVideoMaxSendBandwidth());
        }
        if (tokenOptions.getKurentoOptions().getVideoMinSendBandwidth() != null) {
            kurentoOptions.put("videoMinSendBandwidth",
                    tokenOptions.getKurentoOptions().getVideoMinSendBandwidth());
        }
        if (tokenOptions.getKurentoOptions().getAllowedFilters().length > 0) {
            JSONArray allowedFilters = new JSONArray();
            for (String filter : tokenOptions.getKurentoOptions().getAllowedFilters()) {
                allowedFilters.add(filter);
            }
            kurentoOptions.put("allowedFilters", allowedFilters);
        }
        json.put("kurentoOptions", kurentoOptions);
    }
    StringEntity params;
    try {
        params = new StringEntity(json.toString());
    } catch (UnsupportedEncodingException e1) {
        throw new OpenViduJavaClientException(e1.getMessage(), e1.getCause());
    }

    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    request.setEntity(params);

    HttpResponse response;
    try {
        response = OpenVidu.httpClient.execute(request);
    } catch (IOException e2) {
        throw new OpenViduJavaClientException(e2.getMessage(), e2.getCause());
    }

    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
            String token = (String) httpResponseToJson(response).get("id");
            log.info("Returning a TOKEN: {}", token);
            return token;
        } else {
            throw new OpenViduHttpException(statusCode);
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}