/** * Sets the <tt>Expect</tt> header if it has not already been set, * in addition to the "standard" set of headers. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter ExpectContinueMethod.addRequestHeaders(HttpState, HttpConnection)"); super.addRequestHeaders(state, conn); // If the request is being retried, the header may already be present boolean headerPresent = (getRequestHeader("Expect") != null); // See if the expect header should be sent // = HTTP/1.1 or higher // = request body present if (getParams().isParameterTrue(HttpMethodParams.USE_EXPECT_CONTINUE) && getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1) && hasRequestContent()) { if (!headerPresent) { setRequestHeader("Expect", "100-continue"); } } else { if (headerPresent) { removeRequestHeader("Expect"); } } }
public void testSuccessfulVerifyTargetOverHttps() throws Exception { //Stub HttpClient so that executeMethod returns a 200 response when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), any(HttpState.class))).thenReturn(200); target.setEndpointProtocol(HTTPS_PROTOCOL); target.setEndpointPort(HTTPS_PORT); //Call verifyTarget transmitter.verifyTarget(target); ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class); ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class); ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class); verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture()); assertEquals("port", HTTPS_PORT, hostConfig.getValue().getPort()); assertTrue("socket factory", hostConfig.getValue().getProtocol().getSocketFactory() instanceof SecureProtocolSocketFactory); assertEquals("protocol", HTTPS_PROTOCOL.toLowerCase(), hostConfig.getValue().getProtocol().getScheme().toLowerCase()); }
@Override protected void writeRequest(HttpState state, HttpConnection conn) throws IOException { try { BufferedChunkedOutputStream bufferedChunkedOutputStream = new BufferedChunkedOutputStream(conn, state, this); this.writer.write(bufferedChunkedOutputStream); bufferedChunkedOutputStream.finish(); conn.flushRequestOutputStream(); } catch (IOException e) { this.cleanupConnection(conn); throw e; } }
@Override protected void writeRequest(HttpState state, HttpConnection conn) throws IOException { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(2048); this.writer.write(outputStream); outputStream.close(); this.result = outputStream.toByteArray(); this.setRequestEntity(this); this.writeRequestLine(state, conn); this.writeRequestHeaders(state, conn); conn.writeLine(); // close head // make sure the status line and headers have been sent conn.flushRequestOutputStream(); this.writeRequestBody(state, conn); conn.flushRequestOutputStream(); } catch (IOException e) { this.cleanupConnection(conn); throw e; } }
private synchronized void getHttpState(Shuttle shuttle) { if (authenticationPropertiesHasChanged) { context.httpState = null; authenticationPropertiesHasChanged = false; } if (context.httpState == null) { Engine.logSiteClipper.debug("(SiteClipperConnector) Creating new HttpState for context id " + context.contextID); context.httpState = new HttpState(); } else { Engine.logSiteClipper.debug("(SiteClipperConnector) Using HttpState of context id " + context.contextID); } if (!authUser.equals("") || !authPassword.equals("") || (givenAuthUser != null) || (givenAuthPassword != null)) { int indexSlash = (givenAuthUser == null) ? -1 : givenAuthUser.indexOf("\\"); String domain = (indexSlash == -1) ? NTLMAuthenticationDomain : givenAuthUser.substring(0, indexSlash); String user = (givenAuthUser == null) ? authUser : givenAuthUser.substring(indexSlash + 1); String password = (givenAuthPassword == null) ? authPassword : givenAuthPassword; String type = (givenAuthMode == null ? authenticationType.name() : givenAuthMode); String host = hostConfiguration != null ? hostConfiguration.getHost() : shuttle.getRequest(QueryPart.host); AuthenticationMode.get(type).setCredentials(context.httpState, user, password, host, domain); } }
/** * Adds a <tt>Content-Type</tt> request header. * * @param state current state of http requests * @param conn the connection to use for I/O * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @since 3.0 */ protected void addContentTypeRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter EntityEnclosingMethod.addContentTypeRequestHeader(" + "HttpState, HttpConnection)"); if (!parameters.isEmpty()) { StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE); if (Part.getBoundary() != null) { buffer.append("; boundary="); buffer.append(Part.getBoundary()); } setRequestHeader("Content-Type", buffer.toString()); } }
/** * <p> * This implementation will parse the <tt>Allow</tt> header to obtain * the set of methods supported by the resource identified by the Request-URI. * </p> * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @see #readResponse * @see #readResponseHeaders * @since 2.0 */ protected void processResponseHeaders(HttpState state, HttpConnection conn) { LOG.trace("enter OptionsMethod.processResponseHeaders(HttpState, HttpConnection)"); Header allowHeader = getResponseHeader("allow"); if (allowHeader != null) { String allowHeaderValue = allowHeader.getValue(); StringTokenizer tokenizer = new StringTokenizer(allowHeaderValue, ","); while (tokenizer.hasMoreElements()) { String methodAllowed = tokenizer.nextToken().trim().toUpperCase(); methodsAllowed.addElement(methodAllowed); } } }
/** * Generates <tt>Content-Length</tt> or <tt>Transfer-Encoding: Chunked</tt> * request header, as long as no <tt>Content-Length</tt> request header * already exists. * * @param state current state of http requests * @param conn the connection to use for I/O * * @throws IOException when errors occur reading or writing to/from the * connection * @throws HttpException when a recoverable error occurs */ protected void addContentLengthRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter EntityEnclosingMethod.addContentLengthRequestHeader(" + "HttpState, HttpConnection)"); if ((getRequestHeader("content-length") == null) && (getRequestHeader("Transfer-Encoding") == null)) { long len = getRequestContentLength(); if (len < 0) { if (getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1)) { addRequestHeader("Transfer-Encoding", "chunked"); } else { throw new ProtocolException(getEffectiveVersion() + " does not support chunk encoding"); } } else { addRequestHeader("Content-Length", String.valueOf(len)); } } }
public void testParseMultipleDifferentPaths() throws Exception { Header header = new Header("Set-Cookie", "name1=value1;Version=1;Path=/commons,name1=value2;Version=1;" + "Path=/commons/httpclient;Version=1"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/httpclient", true, header); HttpState state = new HttpState(); state.addCookies(parsed); Cookie[] cookies = state.getCookies(); assertEquals("Wrong number of cookies.",2,cookies.length); assertEquals("Name","name1",cookies[0].getName()); assertEquals("Value","value1",cookies[0].getValue()); assertEquals("Name","name1",cookies[1].getName()); assertEquals("Value","value2",cookies[1].getValue()); }
/** * Make sure preemptive authorization works when the server requires NLM. * @throws Exception */ public void testPreemptiveAuthorization() throws Exception { NTCredentials creds = new NTCredentials("testuser", "testpass", "host", "domain"); HttpState state = new HttpState(); state.setCredentials(AuthScope.ANY, creds); this.client.setState(state); this.client.getParams().setAuthenticationPreemptive(true); this.server.setHttpService(new PreemptiveNTLMAuthService()); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); }
private void getClient(){ CONTACT_URL = OscarProperties.getInstance().getProperty("TELEPLAN_URL",CONTACT_URL); HttpState initialState = new HttpState(); // Initial set of cookies can be retrieved from persistent storage and // re-created, using a persistence mechanism of choice, Cookie mycookie = new Cookie("moh.hnet.bc.ca","mycookie", "stuff", "/", null, false); // and then added to your HTTP state instance initialState.addCookie(mycookie); // Get HTTP client instance //HttpClientParams hcParams = new HttpClientParams(); //hcParams.setParameter("User-Agent","TeleplanPerl 1.0"); httpclient = new HttpClient(); //hcParams); httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); httpclient.setState(initialState); httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); httpclient.getParams().setParameter("User-Agent","TeleplanPerl 1.0"); }
public int executeMethod(HostConfiguration hostconfig, HttpMethod method, HttpState state, boolean addCasTicket) throws IOException, HttpException { if (LOG.isDebugEnabled()) { LOG.debug("executeMethod(HostConfiguration, HttpMethod, HttpState) - entering"); } try { if (this.isAddCasTicketParams()) { HttpClientCAS.addCASTicket(method); } } catch (MotuCasException e) { throw new HttpException(e.notifyException(), e); } int returnint = super.executeMethod(hostconfig, method, state); if (LOG.isDebugEnabled()) { LOG.debug("executeMethod(HostConfiguration, HttpMethod, HttpState) - exiting"); } return returnint; }
/** * Overridden to process the sync-token. Adapted from DavMethodBase. * * @see DavMethodBase#processResponseBody(HttpState, HttpConnection) */ @Override protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) { if (getStatusCode() == DavServletResponse.SC_MULTI_STATUS) { try { Document document = getResponseBodyAsDocument(); if (document != null) { synctoken = DomUtil.getChildText(document.getDocumentElement(), SyncReportInfo.XML_SYNC_TOKEN, DavConstants.NAMESPACE); log.info("Sync-Token for REPORT: " + synctoken); multiStatus = MultiStatus.createFromXml(document.getDocumentElement()); processMultiStatusBody(multiStatus, httpState, httpConnection); } } catch (IOException e) { log.error("Error while parsing sync-token.", e); setSuccess(false); } } }
private static HTTPResponse _invoke(HttpMethod httpMethod, URL url, String username, String password, long timeout, int maxRedirect, String charset, String useragent, ProxyData proxy, Header[] headers, Map<String,String> params, Object body) throws IOException { HttpClient client = new HttpClient(); HostConfiguration config = client.getHostConfiguration(); HttpState state = client.getState(); setHeader(httpMethod,headers); if(CollectionUtil.isEmpty(params))setContentType(httpMethod,charset); setUserAgent(httpMethod,useragent); setTimeout(client,timeout); setParams(httpMethod,params); setCredentials(client,httpMethod,username,password); setProxy(config,state,proxy); if(body!=null && httpMethod instanceof EntityEnclosingMethod)setBody((EntityEnclosingMethod)httpMethod,body); return new HTTPResponse3Impl(execute(client,httpMethod,maxRedirect),url); }
/** * Test create target. * * @throws Exception */ public void testSuccessfulVerifyTargetOverHttp() throws Exception { //Stub HttpClient so that executeMethod returns a 200 response when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), any(HttpState.class))).thenReturn(200); //Call verifyTarget transmitter.verifyTarget(target); ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class); ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class); ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class); verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture()); assertTrue("post method", httpMethod.getValue() instanceof PostMethod); assertEquals("host name", TARGET_HOST, hostConfig.getValue().getHost()); assertEquals("port", HTTP_PORT, hostConfig.getValue().getPort()); assertEquals("protocol", HTTP_PROTOCOL.toLowerCase(), hostConfig.getValue().getProtocol().getScheme().toLowerCase()); assertEquals("path", TRANSFER_SERVICE_PATH + "/test", httpMethod.getValue().getPath()); }
/** * Parse response. * * @param input Input stream */ public void parseResponse(InputStream input, HttpState state, HttpConnection conn) throws IOException, HttpException { try { int code = getStatusLine().getStatusCode(); if (code == WebdavStatus.SC_CONFLICT || code == WebdavStatus.SC_MULTI_STATUS || code == WebdavStatus.SC_FORBIDDEN ) { parseXMLResponse(input); } } catch (IOException e) { // FIX ME: provide a way to deliver non xml data } }
/** * Generate additional headers needed by the request. * * @param state State token * @param conn The connection being used to make the request. */ public void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { // set the default utf-8 encoding, if not already present if (getRequestHeader("Content-Type") == null ) super.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); super.addRequestHeaders(state, conn); switch (depth) { case DEPTH_0: super.setRequestHeader("Depth", "0"); break; case DEPTH_1: super.setRequestHeader("Depth", "1"); break; case DEPTH_INFINITY: super.setRequestHeader("Depth", "infinity"); break; } }
protected void processResponseHeaders(HttpState state, HttpConnection conn) { super.processResponseHeaders(state, conn); Header header; header = getResponseHeader(HEADER_SUBSCRIPTION_ID); if (header != null) { this.responsedSubscriptionId = Integer.parseInt(header.getValue()); } header = getResponseHeader(HEADER_SUBSCRIPTION_LIFETIME); if (header != null) { this.responsedSubscriptionLifetime = Long.parseLong(header.getValue()); } header = getResponseHeader(HEADER_CONTENT_LOCATION); if (header != null) { this.responsedContentLocation = header.getValue(); } }
/** * Generate additional headers needed by the request. * * @param state State token * @param conn The connection being used for the request. */ public void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { super.addRequestHeaders(state, conn); // set the default utf-8 encoding, if not already present if (getRequestHeader("Content-Type") == null ) super.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); switch (getDepth()) { case DEPTH_0 : super.setRequestHeader("Depth", "0"); break; case DEPTH_1 : super.setRequestHeader("Depth", "1"); break; case DEPTH_INFINITY : super.setRequestHeader("Depth", "infinity"); break; } }
/** * Generate additional headers needed by the request. * * @param state HttpState token * @param conn The connection being used for the request. */ public void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { super.addRequestHeaders(state, conn); String absoluteDestination = MoveMethod.getAbsoluteDestination(conn, destination); super.setRequestHeader("Destination", absoluteDestination); if (!isOverwrite()) super.setRequestHeader("Overwrite", "F"); switch (depth) { case DepthSupport.DEPTH_0: super.setRequestHeader("Depth", "0"); break; case DepthSupport.DEPTH_INFINITY: super.setRequestHeader("Depth", "Infinity"); break; } }
/** * Parse response. * * @param input Input stream */ public void parseResponse(InputStream input, HttpState state, HttpConnection conn) throws IOException, HttpException { try { int code = getStatusLine().getStatusCode(); if (code == WebdavStatus.SC_BAD_REQUEST || code == WebdavStatus.SC_MULTI_STATUS || code == WebdavStatus.SC_FORBIDDEN || code == WebdavStatus.SC_CONFLICT ) { parseXMLResponse(input); } } catch (IOException e) { // FIX ME: provide a way to deliver non xml data } }
public void testHttpsVerifyTargetWithCustomSocketFactory() throws Exception { //Override the default SSL socket factory with our own custom one... CustomSocketFactory socketFactory = new CustomSocketFactory(); transmitter.setHttpsSocketFactory(socketFactory); target.setEndpointProtocol(HTTPS_PROTOCOL); target.setEndpointPort(HTTPS_PORT); //Stub HttpClient so that executeMethod returns a 200 response when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), any(HttpState.class))).thenReturn(200); //Call verifyTarget transmitter.verifyTarget(target); ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class); ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class); ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class); verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture()); assertEquals("port", HTTPS_PORT, hostConfig.getValue().getPort()); //test that the socket factory passed to HttpClient is our custom one (intentional use of '==') assertTrue("socket factory", hostConfig.getValue().getProtocol().getSocketFactory() == socketFactory); assertEquals("protocol", HTTPS_PROTOCOL.toLowerCase(), hostConfig.getValue().getProtocol().getScheme().toLowerCase()); }
public void testUnauthorisedVerifyTarget() throws Exception { //Stub HttpClient so that executeMethod returns a 401 response when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), any(HttpState.class))).thenReturn(401); try { transmitter.verifyTarget(target); } catch (TransferException ex) { //expected } }
public void testGetStatusErrorRehydration() throws Exception { final ExceptionJsonSerializer errorSerializer = new ExceptionJsonSerializer(); final TransferException expectedException = new TransferException("my message id", new Object[] {"param1", "param2"}); when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), any(HttpState.class))).thenReturn(200); doAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { JSONObject progressObject = new JSONObject(); progressObject.put("transferId", "mytransferid"); progressObject.put("status", Status.ERROR); progressObject.put("currentPosition", 1); progressObject.put("endPosition", 10); JSONObject errorObject = errorSerializer.serialize(expectedException); progressObject.put("error", errorObject); return progressObject.toString(); } }).when(mockedHttpMethodFactory.latestPostMethod).getResponseBodyAsString(); Transfer transfer = new Transfer(); transfer.setTransferId("mytransferid"); transfer.setTransferTarget(target); TransferProgress progress = transmitter.getStatus(transfer); assertTrue(progress.getError() != null); assertEquals(expectedException.getClass(), progress.getError().getClass()); TransferException receivedException = (TransferException)progress.getError(); assertEquals(expectedException.getMsgId(), receivedException.getMsgId()); assertTrue(Arrays.deepEquals(expectedException.getMsgParams(), receivedException.getMsgParams())); }
public void testBeginFailure() throws Exception { final ExceptionJsonSerializer errorSerializer = new ExceptionJsonSerializer(); final TransferException expectedException = new TransferException("my message id", new Object[] {"param1", "param2"}); when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), any(HttpState.class))).thenReturn(500); doAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { JSONObject errorObject = errorSerializer.serialize(expectedException); return errorObject.toString(); } }).when(mockedHttpMethodFactory.latestPostMethod).getResponseBodyAsString(); try { transmitter.begin(target, "1234", new TransferVersionImpl("2", "2", "2", "Dummy")); fail(); } catch(TransferException ex) { assertEquals(expectedException.getClass(), ex.getClass()); assertEquals(expectedException.getMsgId(), ex.getMsgId()); assertTrue(Arrays.deepEquals(expectedException.getMsgParams(), ex.getMsgParams())); } }
public void reallyWriteHeaders(HttpState state, HttpConnection conn) throws IOException { this.writeRequestLine(state, conn); this.writeRequestHeaders(state, conn); conn.writeLine(); // close head // make sure the status line and headers have been sent conn.flushRequestOutputStream(); }
public BufferedChunkedOutputStream( HttpConnection conn, HttpState state, StreamedPostMethod streamedPostMethod) throws IOException { this.streamedPostMethod = streamedPostMethod; this.state = state; this.httpConnection = conn; this.cache = new byte[2048]; this.stream = this.httpConnection.getRequestOutputStream(); }