Example usage for java.io IOException getCause

List of usage examples for java.io IOException getCause

Introduction

In this page you can find the example usage for java.io IOException 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:io.openvidu.java.client.OpenVidu.java

/**
 * Stops the recording of a {@link io.openvidu.java.client.Session}
 *
 * @param recordingId The id property of the recording you want to stop
 *
 * @return The stopped recording/*from  ww w .ja  va 2  s .c o  m*/
 * 
 * @throws OpenViduJavaClientException
 * @throws OpenViduHttpException       Value returned from
 *                                     {@link io.openvidu.java.client.OpenViduHttpException#getStatus()}
 *                                     <ul>
 *                                     <li><code>404</code>: no recording exists
 *                                     for the passed <i>recordingId</i></li>
 *                                     <li><code>406</code>: recording has
 *                                     <i>starting</i> status. Wait until
 *                                     <i>started</i> status before stopping the
 *                                     recording</li>
 *                                     </ul>
 */
public Recording stopRecording(String recordingId) throws OpenViduJavaClientException, OpenViduHttpException {
    HttpPost request = new HttpPost(
            OpenVidu.urlOpenViduServer + API_RECORDINGS + API_RECORDINGS_STOP + "/" + recordingId);
    HttpResponse response;
    try {
        response = OpenVidu.httpClient.execute(request);
    } catch (IOException e) {
        throw new OpenViduJavaClientException(e.getMessage(), e.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(false);
            } 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

/**
 * Forces some user to unpublish a Stream. OpenVidu Browser will trigger the
 * proper events on the client-side (<code>streamDestroyed</code>) with reason
 * set to "forceUnpublishByServer". <br>
 * /*ww  w.ja v  a  2  s  . c  o  m*/
 * You can get <code>streamId</code> parameter with
 * {@link io.openvidu.java.client.Session#getActiveConnections()} and then for
 * each Connection you can call
 * {@link io.openvidu.java.client.Connection#getPublishers()}. Finally
 * {@link io.openvidu.java.client.Publisher#getStreamId()}) will give you the
 * <code>streamId</code>. Remember to call
 * {@link io.openvidu.java.client.Session#fetch()} before to fetch the current
 * actual properties of the Session from OpenVidu Server
 * 
 * @throws OpenViduJavaClientException
 * @throws OpenViduHttpException
 */
public void forceUnpublish(String streamId) throws OpenViduJavaClientException, OpenViduHttpException {
    HttpDelete request = new HttpDelete(
            OpenVidu.urlOpenViduServer + OpenVidu.API_SESSIONS + "/" + this.sessionId + "/stream/" + streamId);
    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

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

    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ((statusCode == org.apache.http.HttpStatus.SC_NO_CONTENT)) {
            for (Connection connection : this.activeConnections.values()) {
                // Try to remove the Publisher from the Connection publishers collection
                if (connection.publishers.remove(streamId) != null) {
                    continue;
                }
                // Try to remove the Publisher from the Connection subscribers collection
                connection.subscribers.remove(streamId);
            }
            log.info("Stream {} unpublished", streamId);
        } else {
            throw new OpenViduHttpException(statusCode);
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}

From source file:org.apache.hadoop.ha.TestActiveStandbyElector.java

/**
 * Test for a bug encountered during development of HADOOP-8163:
 * ensureBaseNode() should throw an exception if it has to retry
 * more than 3 times to create any part of the path.
 *//*from  w  w w  .  j  a v a2  s . c  o  m*/
@Test
public void testEnsureBaseNodeFails() throws Exception {
    Mockito.doThrow(new KeeperException.ConnectionLossException()).when(mockZK).create(
            Mockito.eq(ZK_PARENT_NAME), Mockito.<byte[]>any(), Mockito.eq(Ids.OPEN_ACL_UNSAFE),
            Mockito.eq(CreateMode.PERSISTENT));
    try {
        elector.ensureParentZNode();
        Assert.fail("Did not throw!");
    } catch (IOException ioe) {
        if (!(ioe.getCause() instanceof KeeperException.ConnectionLossException)) {
            throw ioe;
        }
    }
    // Should have tried three times
    Mockito.verify(mockZK, Mockito.times(3)).create(Mockito.eq(ZK_PARENT_NAME), Mockito.<byte[]>any(),
            Mockito.eq(Ids.OPEN_ACL_UNSAFE), Mockito.eq(CreateMode.PERSISTENT));
}

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

/**
 * Forces the user with Connection <code>connectionId</code> to leave the
 * session. OpenVidu Browser will trigger the proper events on the client-side
 * (<code>streamDestroyed</code>, <code>connectionDestroyed</code>,
 * <code>sessionDisconnected</code>) with reason set to
 * "forceDisconnectByServer" <br>/*ww  w. j av a2 s . c om*/
 * 
 * You can get <code>connectionId</code> parameter with
 * {@link io.openvidu.java.client.Session#fetch()} (use
 * {@link io.openvidu.java.client.Connection#getConnectionId()} to get the
 * `connectionId` you want)
 * 
 * @throws OpenViduJavaClientException
 * @throws OpenViduHttpException
 */
public void forceDisconnect(String connectionId) throws OpenViduJavaClientException, OpenViduHttpException {
    HttpDelete request = new HttpDelete(OpenVidu.urlOpenViduServer + OpenVidu.API_SESSIONS + "/"
            + this.sessionId + "/connection/" + connectionId);
    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

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

    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ((statusCode == org.apache.http.HttpStatus.SC_NO_CONTENT)) {
            // Remove connection from activeConnections map
            Connection connectionClosed = this.activeConnections.remove(connectionId);
            // Remove every Publisher of the closed connection from every subscriber list of
            // other connections
            if (connectionClosed != null) {
                for (Publisher publisher : connectionClosed.getPublishers()) {
                    String streamId = publisher.getStreamId();
                    for (Connection connection : this.activeConnections.values()) {
                        connection.setSubscribers(connection.getSubscribers().stream()
                                .filter(subscriber -> !streamId.equals(subscriber))
                                .collect(Collectors.toList()));
                    }
                }
            } else {
                log.warn(
                        "The closed connection wasn't fetched in OpenVidu Java Client. No changes in the collection of active connections of the Session");
            }
            log.info("Connection {} closed", connectionId);
        } else {
            throw new OpenViduHttpException(statusCode);
        }
    } finally

    {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}

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

@SuppressWarnings("unchecked")
private void getSessionIdHttp() throws OpenViduJavaClientException, OpenViduHttpException {
    if (this.hasSessionId()) {
        return;//from   w ww .j a v a2 s  .com
    }

    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:org.apache.cassandra.hadoop.cql3.CqlRecordReader.java

public boolean nextKeyValue() throws IOException {
    if (!rowIterator.hasNext()) {
        logger.trace("Finished scanning {} rows (estimate was: {})", rowIterator.totalRead, totalRowCount);
        return false;
    }//  w  w w. ja  v a  2  s .  c om

    try {
        currentRow = rowIterator.next();
    } catch (Exception e) {
        // throw it as IOException, so client can catch it and handle it at client side
        IOException ioe = new IOException(e.getMessage());
        ioe.initCause(ioe.getCause());
        throw ioe;
    }
    return true;
}

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

/**
 * Updates every property of every active Session with the current status they
 * have in OpenVidu Server. After calling this method you can access the updated
 * list of active sessions by calling/*  w  w  w.  j  a  va2 s . co  m*/
 * {@link io.openvidu.java.client.OpenVidu#getActiveSessions()}
 * 
 * @return true if any Session status has changed with respect to the server,
 *         false if not. This applies to any property or sub-property of any of
 *         the sessions locally stored in OpenVidu Java Client
 * 
 * @throws OpenViduHttpException
 * @throws OpenViduJavaClientException
 */
@SuppressWarnings("unchecked")
public boolean fetch() throws OpenViduJavaClientException, OpenViduHttpException {
    HttpGet request = new HttpGet(OpenVidu.urlOpenViduServer + API_SESSIONS);

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

    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
            JSONObject jsonSessions = httpResponseToJson(response);
            JSONArray jsonArraySessions = (JSONArray) jsonSessions.get("content");

            // Set to store fetched sessionIds and later remove closed sessions
            Set<String> fetchedSessionIds = new HashSet<>();
            // Boolean to store if any Session has changed
            final boolean[] hasChanged = { false };
            jsonArraySessions.forEach(session -> {
                String sessionId = (String) ((JSONObject) session).get("sessionId");
                fetchedSessionIds.add(sessionId);
                OpenVidu.activeSessions.computeIfPresent(sessionId, (sId, s) -> {
                    String beforeJSON = s.toJson();
                    s = s.resetSessionWithJson((JSONObject) session);
                    String afterJSON = s.toJson();
                    boolean changed = !beforeJSON.equals(afterJSON);
                    hasChanged[0] = hasChanged[0] || changed;
                    log.info("Available session '{}' info fetched. Any change: {}", sessionId, changed);
                    return s;
                });
                OpenVidu.activeSessions.computeIfAbsent(sessionId, sId -> {
                    log.info("New session '{}' fetched", sessionId);
                    hasChanged[0] = true;
                    return new Session((JSONObject) session);
                });
            });

            // Remove closed sessions from activeSessions map
            OpenVidu.activeSessions = OpenVidu.activeSessions.entrySet().stream().filter(entry -> {
                if (fetchedSessionIds.contains(entry.getKey())) {
                    return true;
                } else {
                    log.info("Removing closed session {}", entry.getKey());
                    hasChanged[0] = true;
                    return false;
                }
            }).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
            log.info("Active sessions info fetched: {}", OpenVidu.activeSessions.keySet());
            return hasChanged[0];
        } 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 w ww. j a  va2s . c  o 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:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java

/**
 * Reads the response from the URL connection.
 *
 * @param conn/*from   w  ww .ja va  2s  .  c  om*/
 *            URL from which to read response
 * @param res
 *            {@link SampleResult} to read response into
 * @return response content
 * @exception IOException
 *                if an I/O exception occurs
 */
protected byte[] readResponse(HttpURLConnection conn, SampleResult res) throws IOException {
    BufferedInputStream in;

    final int contentLength = conn.getContentLength();
    if ((contentLength == 0) && OBEY_CONTENT_LENGTH) {
        log.info("Content-Length: 0, not reading http-body");
        res.setResponseHeaders(getResponseHeaders(conn));
        res.latencyEnd();
        return NULL_BA;
    }

    // works OK even if ContentEncoding is null
    boolean gzipped = HTTPConstants.ENCODING_GZIP.equals(conn.getContentEncoding());
    InputStream instream = null;
    try {
        instream = new CountingInputStream(conn.getInputStream());
        if (gzipped) {
            in = new BufferedInputStream(new GZIPInputStream(instream));
        } else {
            in = new BufferedInputStream(instream);
        }
    } catch (IOException e) {
        if (!(e.getCause() instanceof FileNotFoundException)) {
            log.error("readResponse: " + e.toString());
            Throwable cause = e.getCause();
            if (cause != null) {
                log.error("Cause: " + cause);
                if (cause instanceof Error) {
                    throw (Error) cause;
                }
            }
        }
        // Normal InputStream is not available
        InputStream errorStream = conn.getErrorStream();
        if (errorStream == null) {
            log.info("Error Response Code: " + conn.getResponseCode() + ", Server sent no Errorpage");
            res.setResponseHeaders(getResponseHeaders(conn));
            res.latencyEnd();
            return NULL_BA;
        }

        log.info("Error Response Code: " + conn.getResponseCode());

        if (gzipped) {
            in = new BufferedInputStream(new GZIPInputStream(errorStream));
        } else {
            in = new BufferedInputStream(errorStream);
        }
    } catch (Exception e) {
        log.error("readResponse: " + e.toString());
        Throwable cause = e.getCause();
        if (cause != null) {
            log.error("Cause: " + cause);
            if (cause instanceof Error) {
                throw (Error) cause;
            }
        }
        in = new BufferedInputStream(conn.getErrorStream());
    }
    // N.B. this closes 'in'
    byte[] responseData = readResponse(res, in, contentLength);
    if (instream != null) {
        res.setBodySize(((CountingInputStream) instream).getCount());
        instream.close();
    }
    return responseData;
}

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  w  w  . ja va  2  s . c  o 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());
    }
}