Example usage for org.apache.http.client.methods CloseableHttpResponse getHeaders

List of usage examples for org.apache.http.client.methods CloseableHttpResponse getHeaders

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse getHeaders.

Prototype

Header[] getHeaders(String str);

Source Link

Usage

From source file:io.uploader.drive.drive.largefile.DriveResumableUpload.java

private String createResumableUploadUpdate(DriveUtils.HasId fileId, HasMimeType mimeType) throws IOException {

    logger.info("Creating update resumable upload...");
    Preconditions.checkArgument(fileId != null);
    Preconditions.checkArgument(StringUtils.isNotEmpty(fileId.getId()));

    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;

    // https://developers.google.com/google-apps/documents-list/#updatingchanging_documents_and_files

    try {//from w ww .jav  a 2  s  . com
        String putUri = "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable";
        if (useOldApi) {
            putUri = getResumableUploadUpdateUri(fileId);
            //putUri = "https://docs.google.com/feeds/upload/create-session/default/private/full/file%3A";
            //putUri = putUri + fileId.getId() ;
        } else {
            // TODO: new api
            // ...
            throw new IllegalStateException("Not implemented");
        }
        httpclient = getHttpClient();
        HttpPut httpPut = new HttpPut(putUri);
        httpPut.addHeader("Authorization", auth.getAuthHeader());
        httpPut.addHeader("If-Match", "*");
        httpPut.addHeader("X-Upload-Content-Type", mimeType.getMimeType());
        httpPut.addHeader("X-Upload-Content-Length", getFileSizeString());
        httpPut.addHeader("GData-Version", "3");

        //logger.info("Create Update Resumable Upload: " + httpPut.toString());
        response = httpclient.execute(httpPut);
        @SuppressWarnings("unused")
        BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity());
        EntityUtils.consume(response.getEntity());
        String location = "";
        if (response.getStatusLine().getStatusCode() == 200) {
            location = response.getHeaders("Location")[0].getValue();
            //logger.info("Location: " + location);
        }
        return location;
    } finally {
        if (response != null) {
            response.close();
        }
        if (httpclient != null) {
            httpclient.close();
        }
    }
}

From source file:io.uploader.drive.drive.largefile.DriveResumableUpload.java

private String createResumableUpload(String title, HasDescription description, HasId parentId,
        HasMimeType mimeType) throws IOException {

    logger.info("Creating resumable upload...");
    String postUri = "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable";
    if (useOldApi) {
        postUri = "https://docs.google.com/feeds/upload/create-session/default/private/full?convert=false";
        if (parentId != null && org.apache.commons.lang3.StringUtils.isNotEmpty(parentId.getId())) {

            // https://developers.google.com/google-apps/documents-list/
            postUri = "https://docs.google.com/feeds/upload/create-session/default/private/full" + "/folder%3A"
                    + parentId.getId() + "/contents" + "?convert=false";
        }//  ww  w .  j a  va 2  s .co  m
    } else {
        // TODO: new api
        // ...
        throw new IllegalStateException("Not implemented");
    }

    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;

    try {
        httpclient = getHttpClient();
        HttpPost httpPost = new HttpPost(postUri);
        httpPost.addHeader("Authorization", auth.getAuthHeader());
        httpPost.addHeader("X-Upload-Content-Type", mimeType.getMimeType());
        httpPost.addHeader("X-Upload-Content-Length", getFileSizeString());

        String entityString = new JSONObject().put("title", title).toString();
        BasicHeader entityHeader = new BasicHeader(HTTP.CONTENT_TYPE, "application/json");
        if (useOldApi) {

            StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append(
                    "<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:docs=\"http://schemas.google.com/docs/2007\">");
            sb.append(
                    "<category scheme=\"http://schemas.google.com/g/2005#kind\" term=\"http://schemas.google.com/docs/2007#document\"/>");
            // title
            sb.append("<title>").append(title).append("</title>");
            // description
            if (description != null
                    && org.apache.commons.lang3.StringUtils.isNotEmpty(description.getDescription())) {
                sb.append("<docs:description>").append(description.getDescription())
                        .append("</docs:description>");
            }
            sb.append("</entry>");
            entityString = sb.toString();
            httpPost.addHeader("GData-Version", "3");
            entityHeader = new BasicHeader(HTTP.CONTENT_TYPE, "application/atom+xml");
        } else {
            // TODO: new api
            // ...
            throw new IllegalStateException("Not implemented");
        }
        StringEntity se = new StringEntity(entityString);
        se.setContentType(entityHeader);
        httpPost.setEntity(se);
        //logger.info("Create Resumable: " + httpPost.toString());
        response = httpclient.execute(httpPost);
        @SuppressWarnings("unused")
        BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity());
        EntityUtils.consume(response.getEntity());
        String location = "";
        if (response.getStatusLine().getStatusCode() == 200) {
            location = response.getHeaders("Location")[0].getValue();
            //logger.info("Location: " + location);
        }
        return location;
    } finally {
        if (response != null) {
            response.close();
        }
        if (httpclient != null) {
            httpclient.close();
        }
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

private InputStream getFile(String url) {
    EntityManager em = getEm();//from  w  w  w .  j av a  2 s .  c o m
    File file = null;
    FileOutputStream fos = null;
    CloseableHttpClient cl = null;
    CloseableHttpResponse rs = null;
    String nameHint = null;

    File destDir = new File(System.getProperty("java.io.tmpdir"));
    if (!destDir.isDirectory() && !destDir.mkdir()) {
        throw new JqmClientException("could not create temp directory " + destDir.getAbsolutePath());
    }
    jqmlogger.trace("File will be copied into " + destDir);

    try {
        file = new File(destDir + "/" + UUID.randomUUID().toString());

        CredentialsProvider credsProvider = null;
        if (SimpleApiSecurity.getId(em).usr != null) {
            credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    SimpleApiSecurity.getId(em).usr, SimpleApiSecurity.getId(em).pass));
        }
        SSLContext ctx = null;
        if (getFileProtocol(em).equals("https://")) {
            try {
                if (p.containsKey("com.enioka.jqm.ws.truststoreFile")) {
                    KeyStore trust = null;
                    InputStream trustIs = null;

                    try {
                        trust = KeyStore
                                .getInstance(this.p.getProperty("com.enioka.jqm.ws.truststoreType", "JKS"));
                    } catch (KeyStoreException e) {
                        throw new JqmInvalidRequestException("Specified trust store type ["
                                + this.p.getProperty("com.enioka.jqm.ws.truststoreType", "JKS")
                                + "] is invalid", e);
                    }

                    try {
                        trustIs = new FileInputStream(this.p.getProperty("com.enioka.jqm.ws.truststoreFile"));
                    } catch (FileNotFoundException e) {
                        throw new JqmInvalidRequestException("Trust store file ["
                                + this.p.getProperty("com.enioka.jqm.ws.truststoreFile") + "] cannot be found",
                                e);
                    }

                    String trustp = this.p.getProperty("com.enioka.jqm.ws.truststorePass", null);
                    try {
                        trust.load(trustIs, (trustp == null ? null : trustp.toCharArray()));
                    } catch (Exception e) {
                        throw new JqmInvalidRequestException("Could not load the trust store file", e);
                    } finally {
                        try {
                            trustIs.close();
                        } catch (IOException e) {
                            // Nothing to do.
                        }
                    }
                    ctx = SSLContexts.custom().loadTrustMaterial(trust).build();
                } else {
                    ctx = SSLContexts.createSystemDefault();
                }
            } catch (Exception e) {
                // Cannot happen - not trust store is actually loaded!
                jqmlogger.error(
                        "An supposedly impossible error has happened. Downloading files through the API may not work.",
                        e);
            }
        }
        cl = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).setSslcontext(ctx).build();

        // Run HTTP request
        HttpUriRequest rq = new HttpGet(url.toString());
        rs = cl.execute(rq);
        if (rs.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new JqmClientException(
                    "Could not retrieve file from JQM node. The file may have been purged, or the node may be unreachable. HTTP code was: "
                            + rs.getStatusLine().getStatusCode());
        }

        // There may be a filename hint inside the response
        Header[] hs = rs.getHeaders("Content-Disposition");
        if (hs.length == 1) {
            Header h = hs[0];
            if (h.getValue().contains("filename=")) {
                nameHint = h.getValue().split("=")[1];
            }
        }

        // Save the file to a temp local file
        fos = new FileOutputStream(file);
        rs.getEntity().writeTo(fos);
        jqmlogger.trace("File was downloaded to " + file.getAbsolutePath());
    } catch (IOException e) {
        throw new JqmClientException(
                "Could not create a webserver-local copy of the file. The remote node may be down.", e);
    } finally {
        closeQuietly(em);
        closeQuietly(fos);
        closeQuietly(rs);
        closeQuietly(cl);
    }

    SelfDestructFileStream res = null;
    try {
        res = new SelfDestructFileStream(file);
    } catch (IOException e) {
        throw new JqmClientException("File seems not to be present where it should have been downloaded", e);
    }
    res.nameHint = nameHint;
    return res;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

private Pair<String, String[]> loginAndGetJWT() throws Exception {
    CloseableHttpClient client = null;/*  ww  w .ja  va  2s .c om*/
    try {
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
                NoopHostnameVerifier.INSTANCE);

        client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
        URL loginURL = new URL(new URL(HOPSWORKS_ENDPOINT), HOPSWORKS_LOGIN_PATH);
        HttpUriRequest login = RequestBuilder.post().setUri(loginURL.toURI())
                .addParameter("email", HOPSWORKS_USER).addParameter("password", HOPSWORKS_PASSWORD).build();
        CloseableHttpResponse response = client.execute(login);
        Assert.assertNotNull(response);
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
        Header[] authHeaders = response.getHeaders(HttpHeaders.AUTHORIZATION);

        String masterJWT = null;
        for (Header h : authHeaders) {
            Matcher matcher = HopsworksRMAppSecurityActions.JWT_PATTERN.matcher(h.getValue());
            if (matcher.matches()) {
                masterJWT = matcher.group(1);
            }
        }
        JsonParser jsonParser = new JsonParser();
        JsonObject json = jsonParser.parse(EntityUtils.toString(response.getEntity())).getAsJsonObject();
        JsonArray array = json.getAsJsonArray("renewTokens");
        String[] renewTokens = new String[array.size()];
        boolean renewalTokensFound = false;
        for (int i = 0; i < renewTokens.length; i++) {
            renewTokens[i] = array.get(i).getAsString();
            renewalTokensFound = true;
        }
        if (masterJWT != null && renewalTokensFound) {
            return new Pair<>(masterJWT, renewTokens);
        }

        throw new IOException("Could not get JWT from Hopsworks");
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:org.bimserver.webservices.impl.ServiceImpl.java

@Override
public void triggerRevisionService(Long roid, Long soid) throws ServerException, UserException {
    DatabaseSession session = getBimServer().getDatabase().createSession();
    try {/*  w w  w  . j a va  2s  .  com*/
        Revision revision = (Revision) session.get(StorePackage.eINSTANCE.getRevision(), roid,
                OldQuery.getDefault());
        if (revision == null) {
            throw new UserException("No revision found for roid " + roid);
        }
        NewService newService = session.get(StorePackage.eINSTANCE.getNewService(), soid,
                OldQuery.getDefault());
        String url = newService.getResourceUrl();
        SerializerPluginConfiguration serializer = newService.getSerializer();

        PackageMetaData pmd = getBimServer().getMetaDataManager()
                .getPackageMetaData(revision.getProject().getSchema());
        Query query = DefaultQueries.all(pmd);
        Long topicId = download(Collections.singleton(roid),
                new JsonQueryObjectModelConverter(pmd).toJson(query).toString(), serializer.getOid(), true);

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

        LongAction<?> longAction = getBimServer().getLongActionManager().getLongAction(topicId);
        if (longAction == null) {
            throw new UserException("No data found for topicId " + topicId);
        }
        SCheckoutResult result;
        if (longAction instanceof LongStreamingDownloadAction) {
            LongStreamingDownloadAction longStreamingDownloadAction = (LongStreamingDownloadAction) longAction;
            if (longStreamingDownloadAction.getErrors().isEmpty()) {
                try {
                    result = longStreamingDownloadAction.getCheckoutResult();
                } catch (SerializerException e) {
                    throw new UserException(e);
                }
            } else {
                LOGGER.error(longStreamingDownloadAction.getErrors().get(0));
                throw new ServerException(longStreamingDownloadAction.getErrors().get(0));
            }
        } else {
            LongDownloadOrCheckoutAction longDownloadAction = (LongDownloadOrCheckoutAction) longAction;
            try {
                longDownloadAction.waitForCompletion();
                if (longDownloadAction.getErrors().isEmpty()) {
                    result = longDownloadAction.getCheckoutResult();
                } else {
                    LOGGER.error(longDownloadAction.getErrors().get(0));
                    throw new ServerException(longDownloadAction.getErrors().get(0));
                }
            } catch (Exception e) {
                LOGGER.error("", e);
                throw new ServerException(e);
            }
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(result.getFile().getInputStream(), baos);

        httpPost.setHeader("Authorization", "Bearer " + newService.getAccessToken());
        httpPost.setEntity(new ByteArrayEntity(baos.toByteArray()));
        CloseableHttpResponse response = httpclient.execute(httpPost);

        LOGGER.info(response.getStatusLine().toString());
        if (response.getStatusLine().getStatusCode() == 401) {
            throw new UserException("Remote service responded with a 401 Unauthorized");
        } else if (response.getStatusLine().getStatusCode() == 200) {
            Header[] headers = response.getHeaders("Content-Disposition");
            String filename = "unknown";
            if (headers.length > 0) {
                String contentDisposition = headers[0].getValue();
                int indexOf = contentDisposition.indexOf("filename=") + 10;
                filename = contentDisposition.substring(indexOf, contentDisposition.indexOf("\"", indexOf + 1));
            }

            byte[] responseBytes = ByteStreams.toByteArray(response.getEntity().getContent());

            SFile file = new SFile();
            file.setData(responseBytes);
            file.setFilename(filename);
            file.setMime(response.getHeaders("Content-Type")[0].getValue());
            Long fileId = uploadFile(file);

            SExtendedData extendedData = new SExtendedData();
            extendedData.setAdded(new Date());
            extendedData.setRevisionId(roid);
            extendedData.setTitle(newService.getName() + " Results");
            extendedData.setSize(responseBytes.length);
            extendedData.setFileId(fileId);
            extendedData.setSchemaId(getExtendedDataSchemaByName(newService.getOutput()).getOid());
            addExtendedDataToRevision(roid, extendedData);
        } else {
            throw new UserException("Remote service responded with a " + response.getStatusLine());
        }
    } catch (Exception e) {
        handleException(e);
    } finally {
        session.close();
    }
}

From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java

License:asdf

private void verifyVersionedResourceResponseHeaders(final String subjectURI,
        final CloseableHttpResponse response) {
    assertEquals("Didn't get an OK (200) response!", OK.getStatusCode(), getStatus(response));
    checkForVersionedResourceLinkHeader(response);
    checkForMementoTimeGateLinkHeader(response);
    checkForLinkHeader(response, subjectURI, "original");
    checkForLinkHeader(response, subjectURI, "timegate");
    checkForLinkHeader(response, subjectURI + "/" + FCR_VERSIONS, "timemap");
    checkForLinkHeader(response, subjectURI + "/" + FCR_ACL, "acl");
    assertEquals(1, Arrays.asList(response.getHeaders("Vary")).stream()
            .filter(x -> x.getValue().contains("Accept-Datetime")).count());
}

From source file:org.fcrepo.integration.http.api.FedoraVersioningIT.java

/**
 * Utility function to verify TimeMap headers
 *
 * @param response the response//  ww  w  .  j av a 2 s  . co  m
 * @param uri the URI of the resource.
 */
private static void verifyTimeMapHeaders(final CloseableHttpResponse response, final String uri) {
    final String ldpcvUri = uri + "/" + FCR_VERSIONS;
    checkForLinkHeader(response, RESOURCE.toString(), "type");
    checkForLinkHeader(response, CONTAINER.toString(), "type");
    checkForLinkHeader(response, uri, "original");
    checkForLinkHeader(response, uri, "timegate");
    checkForLinkHeader(response, uri + "/" + FCR_VERSIONS, "timemap");
    checkForLinkHeader(response, VERSIONING_TIMEMAP_TYPE, "type");
    checkForLinkHeader(response, ldpcvUri + "/" + FCR_ACL, "acl");
    assertEquals(1, response.getHeaders("Accept-Post").length);
}

From source file:org.flowable.admin.service.engine.FlowableClientService.java

public JsonNode executeDownloadRequest(HttpUriRequest request, HttpServletResponse httpResponse,
        String userName, String password, int expectedStatusCode) {

    FlowableServiceException exception = null;
    CloseableHttpClient client = getHttpClient(userName, password);
    try {/*from   w ww .  ja  v a  2s. com*/
        CloseableHttpResponse response = client.execute(request);
        try {
            boolean success = response.getStatusLine() != null
                    && response.getStatusLine().getStatusCode() == expectedStatusCode;
            if (success) {
                httpResponse.setHeader("Content-Disposition",
                        response.getHeaders("Content-Disposition")[0].getValue());
                response.getEntity().writeTo(httpResponse.getOutputStream());
                return null;

            } else {
                JsonNode bodyNode = null;
                String strResponse = IOUtils.toString(response.getEntity().getContent());
                try {
                    bodyNode = objectMapper.readTree(strResponse);
                } catch (Exception e) {
                    log.debug("Error parsing error message", e);
                }
                exception = new FlowableServiceException(extractError(bodyNode,
                        "An error occurred while calling Flowable: " + response.getStatusLine()));
            }
        } catch (Exception e) {
            log.warn("Error consuming response from uri " + request.getURI(), e);
            exception = wrapException(e, request);
        } finally {
            response.close();
        }

    } catch (Exception e) {
        log.error("Error executing request to uri " + request.getURI(), e);
        exception = wrapException(e, request);
    } finally {
        try {
            client.close();
        } catch (Exception e) {
            log.warn("Error closing http client instance", e);
        }
    }

    if (exception != null) {
        throw exception;
    }

    return null;
}