Example usage for org.apache.http.message BasicHeader BasicHeader

List of usage examples for org.apache.http.message BasicHeader BasicHeader

Introduction

In this page you can find the example usage for org.apache.http.message BasicHeader BasicHeader.

Prototype

public BasicHeader(String str, String str2) 

Source Link

Usage

From source file:com.falcon.orca.actors.Manager.java

public Manager(String url, Integer noOfUsers, Long duration, Integer numOfRepeats, HttpMethods httpMethod,
        String data, List<String> headersString, List<String> cookiesString, boolean isBodyDynamic,
        boolean isUrlDynamic, DynDataStore dataStore) {
    this.noOfUsers = noOfUsers;
    this.duration = duration;
    this.numOfRepeats = numOfRepeats;
    this.totalRepeats = numOfRepeats;
    this.generators = new LinkedList<>();
    this.collector = getContext().actorOf(Collector.props());
    this.durationMode = (duration != null);
    final List<Header> headers = new ArrayList<>();
    if (headersString != null) {
        headersString.forEach((o) -> {
            if (o.contains(":")) {
                String[] keyVal = o.split(":");
                headers.add(new BasicHeader(keyVal[0], keyVal[1]));
            }/*from w  w w.ja v a2s .  c  om*/
        });
    }
    final List<Cookie> cookies = new ArrayList<>();
    if (cookiesString != null) {
        cookiesString.forEach((o) -> {
            try {
                HttpCookie cookie = objectMapper.readValue(o, HttpCookie.class);
                BasicClientCookie basicCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
                basicCookie.setDomain(cookie.getDomain());
                basicCookie.setPath(cookie.getPath());
                cookies.add(basicCookie);
            } catch (IOException e) {
                System.out.println("Wrong cookie format ignoring this cookie " + o);
            }
        });
    }
    for (int i = 0; i < this.noOfUsers; i++) {
        this.generators.add(getContext().actorOf(Generator.props(collector, url, httpMethod,
                data == null ? null : data.getBytes(StandardCharsets.UTF_8), headers, cookies, isBodyDynamic,
                isUrlDynamic, dataStore)));
    }
}

From source file:ch.cyberduck.core.onedrive.OneDriveCommonsHttpRequestExecutor.java

protected Upload doUpload(final URL url, final Set<RequestHeader> headers,
        final HttpEntityEnclosingRequestBase request) {
    for (RequestHeader header : headers) {
        if (header.getKey().equals(HTTP.TRANSFER_ENCODING)) {
            continue;
        }/*  ww w  .  j  a v  a 2  s  .c o m*/
        if (header.getKey().equals(HTTP.CONTENT_LEN)) {
            continue;
        }
        request.addHeader(new BasicHeader(header.getKey(), header.getValue()));
    }
    final CountDownLatch entry = new CountDownLatch(1);
    final DelayedHttpEntity entity = new DelayedHttpEntity(entry) {
        @Override
        public long getContentLength() {
            for (RequestHeader header : headers) {
                if (header.getKey().equals(HTTP.CONTENT_LEN)) {
                    return Long.valueOf(header.getValue());
                }
            }
            // Content-Encoding: chunked
            return -1L;
        }
    };
    request.setEntity(entity);
    final DefaultThreadPool executor = new DefaultThreadPool(String.format("http-%s", url), 1);
    final Future<CloseableHttpResponse> future = executor.execute(new Callable<CloseableHttpResponse>() {
        @Override
        public CloseableHttpResponse call() throws Exception {
            return client.execute(request);
        }
    });
    return new Upload() {
        @Override
        public Response getResponse() throws IOException {
            final CloseableHttpResponse response;
            try {
                response = future.get();
            } catch (InterruptedException e) {
                throw new IOException(e);
            } catch (ExecutionException e) {
                throw new IOException(e.getCause());
            } finally {
                executor.shutdown(false);
            }
            return new CommonsHttpResponse(response);
        }

        @Override
        public OutputStream getOutputStream() {
            try {
                // Await execution of HTTP request to make stream available
                entry.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return entity.getStream();
        }
    };
}

From source file:ch.cyberduck.core.dav.DAVWriteFeature.java

@Override
public ResponseOutputStream<String> write(final Path file, final TransferStatus status)
        throws BackgroundException {
    final List<Header> headers = new ArrayList<Header>();
    if (status.isAppend()) {
        final HttpRange range = HttpRange.withStatus(status);
        // Content-Range entity-header is sent with a partial entity-body to specify where
        // in the full entity-body the partial body should be applied.
        final String header = String.format("bytes %d-%d/%d", range.getStart(), range.getEnd(),
                status.getOffset() + status.getLength());
        if (log.isDebugEnabled()) {
            log.debug(String.format("Add range header %s for file %s", header, file));
        }//from  w ww .j a va  2s.c  o  m
        headers.add(new BasicHeader(HttpHeaders.CONTENT_RANGE, header));
    }
    if (expect) {
        if (status.getLength() > 0L) {
            headers.add(new BasicHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE));
        }
    }
    return this.write(file, headers, status);
}

From source file:leap.lang.http.client.apache.ApacheHttpRequest.java

@Override
public HttpRequest addHeader(String name, String value) {
    headers.addHeader(new BasicHeader(name, value));
    return this;
}

From source file:com.nextdoor.bender.ipc.http.HttpTransport.java

protected HttpResponse sendBatchCompressed(HttpPost httpPost, byte[] raw) throws TransportException {
    /*// ww  w. java  2 s .  co  m
     * Write gzip data to Entity and set content encoding to gzip
     */
    ByteArrayEntity entity = new ByteArrayEntity(raw, ContentType.DEFAULT_BINARY);
    entity.setContentEncoding("gzip");

    httpPost.addHeader(new BasicHeader("Accept-Encoding", "gzip"));
    httpPost.setEntity(entity);

    /*
     * Make call
     */
    HttpResponse resp = null;
    try {
        resp = this.client.execute(httpPost);
    } catch (IOException e) {
        throw new TransportException("failed to make call", e);
    }

    return resp;
}

From source file:de.devbliss.apitester.ApiTestUnitTest.java

@Before
public void setUp() throws Exception {
    uri = new URI(URI_STRING);
    headers = new Header[1];
    headers[0] = new BasicHeader("name", "value");
    when(response.getStatusLine()).thenReturn(statusLine);
    when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(response);
    testState = new TestState(httpClient, cookieStore);

    when(httpGet.getRequestLine()).thenReturn(requestLine);
    when(httpGet.getAllHeaders()).thenReturn(headers);

    when(httpPost.getRequestLine()).thenReturn(requestLine);
    when(httpPost.getAllHeaders()).thenReturn(headers);

    when(httpPut.getRequestLine()).thenReturn(requestLine);
    when(httpPut.getAllHeaders()).thenReturn(headers);

    when(httpDelete.getRequestLine()).thenReturn(requestLine);
    when(httpDelete.getAllHeaders()).thenReturn(headers);
    when(httpDeleteWithBody.getRequestLine()).thenReturn(requestLine);
    when(httpDeleteWithBody.getAllHeaders()).thenReturn(headers);

    when(response.getAllHeaders()).thenReturn(headers);
}

From source file:org.elasticsearch.integration.AbstractPrivilegeTestCase.java

protected void assertAccessIsDenied(String user, String method, String uri, String body,
        Map<String, String> params) throws IOException {
    ResponseException responseException = expectThrows(ResponseException.class,
            () -> getRestClient().performRequest(method, uri, params, entityOrNull(body),
                    new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken
                            .basicAuthHeaderValue(user, new SecureString("passwd".toCharArray())))));
    StatusLine statusLine = responseException.getResponse().getStatusLine();
    String message = String.format(Locale.ROOT, "%s %s body %s: Expected 403, got %s %s with body %s", method,
            uri, body, statusLine.getStatusCode(), statusLine.getReasonPhrase(),
            EntityUtils.toString(responseException.getResponse().getEntity()));
    assertThat(message, statusLine.getStatusCode(), is(403));
}

From source file:org.neo4j.ogm.session.transaction.TransactionManager.java

public void commit(Transaction tx) {
    String url = tx.url() + "/commit";
    logger.debug("POST {}", url);
    HttpPost request = new HttpPost(url);
    request.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
    executeRequest(request);//from  w ww .java2 s  .  c  o  m
}

From source file:net.ymate.module.sso.support.SSOUserSessionHandler.java

private boolean __doValidateToken(ISSOToken token) {
    try {// ww w . j  av a  2s.  c o  m
        if (SSO.get().getModuleCfg().isClientMode()) {
            Map<String, String> _params = new HashMap<String, String>();
            _params.put("token_id", token.getId());
            _params.put("uid", token.getUid());
            _params.put("remote_addr", token.getRemoteAddr());
            _params.put("sign",
                    ParamUtils.createSignature(_params, false, SSO.get().getModuleCfg().getServiceAuthKey()));
            IHttpResponse _result = HttpClientHelper.create().post(
                    SSO.get().getModuleCfg().getServiceBaseUrl().concat("sso/authorize"), _params,
                    new Header[] {
                            new BasicHeader("User-Agent", WebContext.getRequest().getHeader("User-Agent")) });
            if (_result != null && _result.getStatusCode() == HttpServletResponse.SC_OK) {
                JSONObject _resultObj = JSON.parseObject(_result.getContent());
                if (_resultObj.getIntValue("ret") == ErrorCode.SUCCEED) {
                    // ?Cookie
                    SSO.get().getModuleCfg().getTokenAdapter().setToken(token);
                    // ?????token?
                    JSONObject _dataObj = _resultObj.getJSONObject("data");
                    if (_dataObj != null && !_dataObj.isEmpty()) {
                        for (Map.Entry<String, Object> _attr : _dataObj.entrySet()) {
                            token.getAttributes().put(_attr.getKey(),
                                    BlurObject.bind(_attr.getValue()).toStringValue());
                        }
                    }
                    //
                    return true;
                }
            }
        } else {
            ISSOTokenStorageAdapter _storageAdapter = SSO.get().getModuleCfg().getTokenStorageAdapter();
            // ???
            ISSOToken _originalToken = _storageAdapter.load(token.getUid(), token.getId());
            if (_originalToken != null) {
                boolean _ipCheck = (SSO.get().getModuleCfg().isIpCheckEnabled()
                        && !StringUtils.equals(token.getRemoteAddr(), _originalToken.getRemoteAddr()));
                if (_originalToken.timeout() || !_originalToken.verified() || _ipCheck) {
                    _storageAdapter.remove(_originalToken.getUid(), _originalToken.getId());
                } else {
                    // ?
                    ISSOTokenAttributeAdapter _attributeAdapter = SSO.get().getModuleCfg()
                            .getTokenAttributeAdapter();
                    if (_attributeAdapter != null) {
                        _attributeAdapter.loadAttributes(token);
                    }
                    return true;
                }
            }
        }
    } catch (Exception e) {
        _LOG.warn("An exception occurred while validate token '" + token.getId() + "' for user '"
                + token.getUid() + "'", RuntimeUtils.unwrapThrow(e));
    }
    return false;
}

From source file:org.sonatype.nexus.testsuite.security.nexus4383.Nexus4383LogoutResourceIT.java

/**
 * 1.) Make a get request to set a cookie </BR>
 * 2.) verify cookie works (do not send basic auth) </BR>
 * 3.) do logout  </BR>/* w w w  . jav  a  2s.  c o m*/
 * 4.) repeat step 2 and expect failure.
 */
@Test
public void testLogout() throws Exception {
    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "status";
    String logoutUrl = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "authentication/logout";

    Header userAgentHeader = new BasicHeader("User-Agent", "Something Stateful");

    // default useragent is: Jakarta Commons-HttpClient/3.1[\r][\n]
    DefaultHttpClient httpClient = new DefaultHttpClient();
    URI nexusBaseURI = new URI(url);
    final BasicHttpContext localcontext = new BasicHttpContext();
    final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(),
            nexusBaseURI.getScheme());
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // HACK: Disable CSRFGuard support for now, its too problematic
    //String owaspQueryParams = null;
    HttpGet getMethod = new HttpGet(url);
    getMethod.addHeader(userAgentHeader);
    try {
        CloseableHttpResponse response = httpClient.execute(getMethod, localcontext);
        // HACK: Disable CSRFGuard support for now, its too problematic
        //Header owaspCsrfToken = response.getFirstHeader("OWASP_CSRFTOKEN");
        //assertThat(owaspCsrfToken, is(notNullValue()));
        //owaspQueryParams = "?" + owaspCsrfToken.getName() + "=" + owaspCsrfToken.getValue();
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
    } finally {
        getMethod.reset();
    }

    Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies());
    Assert.assertNotNull("Session Cookie not set", sessionCookie);

    httpClient.getCookieStore().clear(); // remove cookies
    httpClient.getCredentialsProvider().clear(); // remove auth

    // now with just the cookie
    httpClient.getCookieStore().addCookie(sessionCookie);
    // HACK: Disable CSRFGuard support for now, its too problematic
    //getMethod = new HttpGet(url + owaspQueryParams);
    getMethod = new HttpGet(url);
    try {
        Assert.assertEquals(httpClient.execute(getMethod).getStatusLine().getStatusCode(), 200);
    } finally {
        getMethod.reset();
    }

    // do logout
    // HACK: Disable CSRFGuard support for now, its too problematic
    //HttpGet logoutGetMethod = new HttpGet(logoutUrl + owaspQueryParams);
    HttpGet logoutGetMethod = new HttpGet(logoutUrl);
    try {
        final HttpResponse response = httpClient.execute(logoutGetMethod);
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
        Assert.assertEquals("OK", EntityUtils.toString(response.getEntity()));
    } finally {
        logoutGetMethod.reset();
    }

    // set cookie again
    httpClient.getCookieStore().clear(); // remove cookies
    httpClient.getCredentialsProvider().clear(); // remove auth

    httpClient.getCookieStore().addCookie(sessionCookie);
    HttpGet failedGetMethod = new HttpGet(url);
    try {
        final HttpResponse response = httpClient.execute(failedGetMethod);
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 401);
    } finally {
        failedGetMethod.reset();
    }
}