Example usage for org.apache.http.util EntityUtils consumeQuietly

List of usage examples for org.apache.http.util EntityUtils consumeQuietly

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils consumeQuietly.

Prototype

public static void consumeQuietly(HttpEntity httpEntity) 

Source Link

Usage

From source file:org.eclipse.aether.transport.http.HttpTransporter.java

private void execute(HttpUriRequest request, EntityGetter getter) throws Exception {
    try {/*ww  w.j  av  a  2 s  .  c  o  m*/
        SharingHttpContext context = new SharingHttpContext(state);
        prepare(request, context);
        HttpResponse response = client.execute(server, request, context);
        try {
            context.close();
            handleStatus(response);
            if (getter != null) {
                getter.handle(response);
            }
        } finally {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    } catch (IOException e) {
        if (e.getCause() instanceof TransferCancelledException) {
            throw (Exception) e.getCause();
        }
        throw e;
    }
}

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/* w  ww  .  ja  va 2s  . 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:pl.psnc.synat.wrdz.zmkd.plan.MigrationPlanProcessorBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public MigrationProcessingResult processOne(long planId, List<TransformationInfo> path)
        throws MigrationProcessingException, MigrationPlanNotFoundException {

    MigrationPlan plan = migrationPlanManager.getMigrationPlanById(planId);
    UserDto owner = userBrowser.getUser(plan.getOwnerId());
    if (owner == null) {
        throw new WrdzRuntimeException("Missing owner");
    }//from  www .  j  a  v  a  2 s  .  c  o m

    String objectIdentifier = getCurrentObjectIdentifier(planId);
    if (objectIdentifier == null) {
        return MigrationProcessingResult.FINISHED;
    }

    Long objectId = identifierBrowser.getObjectId(objectIdentifier);
    if (objectId == null) {
        migrationItemManager.logError(planId, objectIdentifier, null);
        throw new MigrationProcessingException(planId, "Object does not exist: " + objectIdentifier);
    }
    if (!objectPermissionManager.hasPermission(owner.getUsername(), objectId,
            ObjectPermissionType.METADATA_UPDATE)) {
        migrationItemManager.logPermissionError(planId, objectIdentifier, null);
        throw new MigrationProcessingException(planId, "Insufficient access rights: " + objectIdentifier);
    }

    migrationItemManager.logMigrationStarted(planId, objectIdentifier);

    HttpClient client = httpsClientHelper.getHttpsClient(WrdzModule.ZMKD);

    HttpGet get = new HttpGet(zmkdConfiguration.getZmdObjectUrl(objectIdentifier));
    HttpResponse response = null;

    File digitalObjectFile;
    File workDir;

    try {

        synchronized (this) {
            response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
                migrationPlanManager.logWaitingForObject(planId, objectIdentifier);
                return MigrationProcessingResult.PAUSED;
            }
        }

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            migrationItemManager.logFetchingError(planId, objectIdentifier,
                    response.getStatusLine().getStatusCode() + "");
            throw new MigrationProcessingException(planId,
                    "Could not fetch object from ZMD: " + response.getStatusLine());
        }

        workDir = new File(zmkdConfiguration.getWorkingDirectory(uuidGenerator.generateCacheFolderName()));
        workDir.mkdir();

        digitalObjectFile = httpsClientHelper.storeResponseEntity(workDir, response.getEntity(),
                response.getFirstHeader("Content-Disposition"));

        ZipUtility.unzip(digitalObjectFile, workDir);

    } catch (IOException e) {
        migrationItemManager.logFetchingError(planId, objectIdentifier, null);
        throw new MigrationProcessingException(planId, "Could not fetch object from ZMD", e);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }

    DigitalObjectInfo objectInfo = reader.parseMets(workDir, METS_PATH);
    try {
        planExecutionManager.transform(objectInfo, path);
    } catch (TransformationException e) {
        migrationItemManager.logServiceError(planId, objectIdentifier, e.getServiceIri());
        throw new MigrationProcessingException(planId, "Transformation failed", e);
    }

    Map<String, File> targetFiles = new HashMap<String, File>();
    Map<String, Integer> fileSequence = new HashMap<String, Integer>();
    for (DataFileInfo dataFileInfo : objectInfo.getFiles()) {
        String filename = dataFileInfo.getPath();
        if (filename.startsWith(CONTENT_PREFIX)) {
            filename = filename.substring(CONTENT_PREFIX.length());
        }
        targetFiles.put(filename, dataFileInfo.getFile());
        if (dataFileInfo.getSequence() != null) {
            fileSequence.put(filename, dataFileInfo.getSequence());
        }
    }

    MigrationType originType;
    switch (objectInfo.getType()) {
    case MASTER:
        originType = MigrationType.TRANSFORMATION;
        break;
    case OPTIMIZED:
        originType = MigrationType.OPTIMIZATION;
        break;
    case CONVERTED:
        originType = MigrationType.CONVERSION;
        break;
    default:
        throw new WrdzRuntimeException("Unexpected type: " + objectInfo.getType());
    }

    try {
        String requestId = saveObject(client, targetFiles, fileSequence, objectIdentifier, originType);
        migrationItemManager.logUploaded(planId, objectIdentifier, requestId);
    } catch (IOException e) {
        migrationItemManager.logCreationError(planId, objectIdentifier, null);
        throw new MigrationProcessingException(planId, "Upload failed", e);
    }

    return MigrationProcessingResult.PROCESSED;
}

From source file:org.ovirt.engine.sdk4.internal.HttpConnection.java

private JsonNode getSsoResponse(URI uri, List<NameValuePair> params) {
    HttpResponse response = null;/*from w  w w .  j  av  a2  s .  c  o m*/
    try {
        // Send request and parse token:
        HttpPost requestToken = new HttpPost(uri);
        requestToken.addHeader("User-Agent", "JavaSDK");
        requestToken.addHeader("Accept", "application/json");
        requestToken.setEntity(new UrlEncodedFormEntity(params));
        response = client.execute(requestToken);
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readTree(response.getEntity().getContent());
    } catch (IOException ex) {
        throw new Error("Failed to parse JSON response", ex);
    } catch (Exception ex) {
        throw new Error("Failed to send SSO request", ex);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }
}

From source file:org.scassandra.http.client.ActivityClient.java

private void httpDelete(String url, String warningMessage) {
    HttpDelete delete = new HttpDelete(url);
    try {/* w  ww . j  a va2 s. co m*/
        CloseableHttpResponse httpResponse = httpClient.execute(delete);
        EntityUtils.consumeQuietly(httpResponse.getEntity());
    } catch (IOException e) {
        LOGGER.warn(warningMessage, e);
        throw new ActivityRequestFailed(warningMessage, e);
    }
}

From source file:org.apache.olingo.server.example.TripPinServiceTest.java

@Test
public void testUpdateRawValue() throws Exception {
    // Note that in-real services must convert raw value (byte[]) to 
    // the data type it needs to save in in updateProperty method
    String editUrl = baseURL + "/Airlines('AF')/Name/$value";
    HttpPut put = new HttpPut(editUrl);
    put.setEntity(new StringEntity("Safari"));
    HttpResponse response = httpSend(put, 204);
    EntityUtils.consumeQuietly(response.getEntity());

    response = httpGET(baseURL + "/Airlines('AF')/Name/$value", 200);
    assertEquals("Safari", IOUtils.toString(response.getEntity().getContent()));
}

From source file:org.wisdom.framework.vertx.ServerTest.java

@Test
public void testAllow() throws InterruptedException, IOException, KeyStoreException, CertificateException,
        NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException {
    FakeConfiguration s1 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0)
            .put("ssl", false).put("authentication", false).put("allow", ImmutableList.of("/foo*")).build());

    FakeConfiguration s2 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0)
            .put("ssl", false).put("authentication", false).put("allow", ImmutableList.of("/bar*")).build());

    when(application.getConfiguration("vertx.servers"))
            .thenReturn(new FakeConfiguration(ImmutableMap.<String, Object>of("s1", s1, "s2", s2)));
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            return ok("Alright");
        }/*from   www.  ja  va  2 s .  c  o m*/
    };
    final Route route1 = new RouteBuilder().route(HttpMethod.GET).on("/foo").to(controller, "index");
    final Route route2 = new RouteBuilder().route(HttpMethod.GET).on("/bar").to(controller, "index");
    doAnswer(new Answer<Route>() {
        @Override
        public Route answer(InvocationOnMock mock) throws Throwable {
            String url = (String) mock.getArguments()[1];
            if (url.equals("/foo")) {
                return route1;
            }
            if (url.equals("/bar")) {
                return route2;
            }
            return null;
        }
    }).when(router).getRouteFor(anyString(), anyString(), any(Request.class));

    wisdom.start();
    waitForStart(wisdom);

    assertThat(wisdom.servers).hasSize(2);
    for (Server server : wisdom.servers) {
        if (server.name().equalsIgnoreCase("s1")) {
            // Accept /foo, Deny /bar
            HttpResponse r = org.apache.http.client.fluent.Request
                    .Get("http://localhost:" + server.port() + "/foo").execute().returnResponse();
            assertThat(r.getStatusLine().getStatusCode()).isEqualTo(Status.OK);
            EntityUtils.consumeQuietly(r.getEntity());
            r = org.apache.http.client.fluent.Request.Get("http://localhost:" + server.port() + "/bar")
                    .execute().returnResponse();
            assertThat(r.getStatusLine().getStatusCode()).isEqualTo(Status.FORBIDDEN);
            EntityUtils.consumeQuietly(r.getEntity());
        } else {
            // Accept /foo, Deny /bar
            HttpResponse r = org.apache.http.client.fluent.Request
                    .Get("http://localhost:" + server.port() + "/bar").execute().returnResponse();
            assertThat(r.getStatusLine().getStatusCode()).isEqualTo(Status.OK);
            EntityUtils.consumeQuietly(r.getEntity());
            r = org.apache.http.client.fluent.Request.Get("http://localhost:" + server.port() + "/foo")
                    .execute().returnResponse();
            assertThat(r.getStatusLine().getStatusCode()).isEqualTo(Status.FORBIDDEN);
            EntityUtils.consumeQuietly(r.getEntity());
        }
    }
}

From source file:org.aludratest.service.gui.web.selenium.TAFMSSeleniumResourceService.java

private String extractMessage(HttpResponse response) throws IOException {
    if (response.getEntity() == null) {
        return null;
    }/*from w w w  .j  a  va2s .  c om*/

    HttpEntity entity = response.getEntity();
    InputStream in = entity.getContent();

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(in, baos);
        return new String(baos.toByteArray(), "UTF-8");
    } finally {
        EntityUtils.consumeQuietly(entity);
        IOUtils.closeQuietly(in);
    }
}

From source file:org.eclipse.aether.transport.http.HttpTransporter.java

private void prepare(HttpUriRequest request, SharingHttpContext context) {
    boolean put = HttpPut.METHOD_NAME.equalsIgnoreCase(request.getMethod());
    if (state.getWebDav() == null && (put || isPayloadPresent(request))) {
        try {/*from   ww  w.  jav  a 2 s.  c  om*/
            HttpOptions req = commonHeaders(new HttpOptions(request.getURI()));
            HttpResponse response = client.execute(server, req, context);
            state.setWebDav(isWebDav(response));
            EntityUtils.consumeQuietly(response.getEntity());
        } catch (IOException e) {
            LOGGER.debug("Failed to prepare HTTP context", e);
        }
    }
    if (put && Boolean.TRUE.equals(state.getWebDav())) {
        mkdirs(request.getURI(), context);
    }
}

From source file:io.wcm.devops.maven.nodejsproxy.resource.MavenProxyResource.java

private Checksums getChecksums(String version) throws IOException {
    String url = config.getNodeJsBinariesRootUrl()
            + StringUtils.replace(config.getNodeJsChecksumUrl(), "${version}", version);
    log.info("Get file: {}", url);
    HttpGet get = new HttpGet(url);
    HttpResponse response = httpClient.execute(get);
    try {//from  w ww .  ja  v a  2 s  .com
        if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
            return new Checksums(EntityUtils.toString(response.getEntity()));
        } else {
            return null;
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}