public List<DataPoint> getData ( final String item, final String type, final Date from, final Date to, final Integer number ) throws Exception { final HttpClient client = new HttpClient (); final HttpMethod method = new GetMethod ( this.baseUrl + "/" + URLEncoder.encode ( item, "UTF-8" ) + "/" + URLEncoder.encode ( type, "UTF-8" ) + "?from=" + URLEncoder.encode ( Utils.isoDateFormat.format ( from ), "UTF-8" ) + "&to=" + URLEncoder.encode ( Utils.isoDateFormat.format ( to ), "UTF-8" ) + "&no=" + number ); client.getParams ().setSoTimeout ( (int)this.timeout ); try { final int status = client.executeMethod ( method ); if ( status != HttpStatus.SC_OK ) { throw new RuntimeException ( "Method failed with error " + status + " " + method.getStatusLine () ); } return Utils.fromJson ( method.getResponseBodyAsString () ); } finally { method.releaseConnection (); } }
@Override public HttpResponse get(URL urlObj, String userName, String password, int timeout) { HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(urlObj.toString()); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); client.getParams().setSoTimeout(1000 * timeout); client.getParams().setConnectionManagerTimeout(1000 * timeout); if (userName != null && password != null) { setBasicAuthorization(method, userName, password); } try { int response = client.executeMethod(method); return new HttpResponse(response, method.getResponseBody()); } catch (IOException e) { throw new RuntimeException("Failed to get " + urlObj.toString(), e); } finally { method.releaseConnection(); } }
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()); }
@SuppressWarnings("unchecked") private HttpMethod createDeleteMethod(HttpServletRequest req, String redirectUrl) throws IOException, ServletException, NotLoggedInException { DeleteMethod delete = new DeleteMethod(redirectUrl); addUserNameToHeader(delete, req); addAcceptEncodingHeader(delete, req); delete.getParams().setContentCharset("UTF-8"); HttpMethodParams params = new HttpMethodParams(); Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { String paramName = (String) e.nextElement(); String[] values = req.getParameterValues(paramName); for (String value : values) { params.setParameter(paramName, value); } } delete.setParams(params); return delete; }
private void doService(HttpMethod method, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { outputRequestLog(req); InputStream iStream = null; ServletOutputStream oStream = null; try { long threadID = Thread.currentThread().getId(); log.debug("[" + threadID + "] forwarded to " + distributer.getRedirectUrl(req)); HttpClient client = new HttpClient(); log.debug("[" + threadID + "]send request."); int resultCode = client.executeMethod(method); log.debug("[" + threadID + "]got response: result code is " + resultCode); res.setStatus(resultCode); for (Header header : method.getResponseHeaders()) { res.setHeader(header.getName(), header.getValue()); } iStream = method.getResponseBodyAsStream(); oStream = res.getOutputStream(); writeOutputStream(iStream, oStream); log.debug("[" + threadID + "] response sent to client."); } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } finally { if (iStream != null) { iStream.close(); } if (oStream != null) { oStream.close(); } } }
/** * {@inheritDoc} */ @Override public boolean authenticateResponse(HttpMethod method, String remoteIP, byte[] decryptedBody) { try { byte[] expectedMAC = getResponseMac(method); Long timestamp = getResponseTimestamp(method); if(timestamp == null) { return false; } remoteIP = IPUtils.getRealIPAddress(remoteIP); return authenticate(expectedMAC, new MACInput(decryptedBody, timestamp.longValue(), remoteIP)); } catch(Exception e) { throw new RuntimeException("Unable to authenticate HTTP response", e); } }
/** * {@inheritDoc} */ @Override public void setRequestAuthentication(HttpMethod method, byte[] message) throws IOException { long requestTimestamp = System.currentTimeMillis(); // add MAC header byte[] mac = macUtils.generateMAC(KeyProvider.ALIAS_SOLR, new MACInput(message, requestTimestamp, getLocalIPAddress())); if(logger.isDebugEnabled()) { logger.debug("Setting MAC " + Arrays.toString(mac) + " on HTTP request " + method.getPath()); logger.debug("Setting timestamp " + requestTimestamp + " on HTTP request " + method.getPath()); } setRequestMac(method, mac); // prevent replays setRequestTimestamp(method, requestTimestamp); }
/** * Will write all request headers stored in the request to the method that * are not in the set of banned headers. * The Accept-Endocing header is also changed to allow compressed content * connection to the server even if the end client doesn't support that. * A Via headers is created as well in compliance with the RFC. * * @param method The HttpMethod used for this connection * @param request The incoming request * @throws HttpException */ protected void setHeaders(HttpMethod method, HttpServletRequest request) throws HttpException { Enumeration headers = request.getHeaderNames(); String connectionToken = request.getHeader("connection"); while (headers.hasMoreElements()) { String name = (String) headers.nextElement(); boolean isToken = (connectionToken != null && name.equalsIgnoreCase(connectionToken)); if (!isToken && !bannedHeaders.contains(name.toLowerCase())) { Enumeration value = request.getHeaders(name); while (value.hasMoreElements()) { method.addRequestHeader(name, (String) value.nextElement()); } } } setProxySpecificHeaders(method, request); }
@Test public void charge_communicationFailureDetailedInfo_Bug8712() throws Exception { // setup ChargingData chargingData = createChargingData(); RequestData requestData = createRequestData(DIRECT_DEBIT); PostMethodStub.setStubReturnValue(sampleResponse); when( Integer.valueOf(httpClientMock .executeMethod(any(HttpMethod.class)))).thenThrow( new IOException()); // Check error message provides details in case of communication failure try { psp.charge(requestData, chargingData); Assert.fail(PSPCommunicationException.class.getName() + " expected"); } catch (PSPCommunicationException pspEx) { final String ERROR_MSG = pspEx.getMessage(); Assert.assertTrue(ERROR_MSG.indexOf("[Details]") > 0); Assert.assertTrue(ERROR_MSG.indexOf(XML_URL) > 0); Assert.assertTrue(ERROR_MSG .indexOf(HeidelpayXMLTags.XML_ATTRIBUTE_CHANNEL) > 0); Assert.assertTrue(ERROR_MSG .indexOf(HeidelpayXMLTags.XML_ATTRIBUTE_LOGIN) > 0); } }
@Test public void testPreventLoopIncorrectHttpBasicCredentials() throws Exception { // assume http and webdav are on the same host + port URL url = new URL(HttpTest.HTTP_BASE_URL); Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage"); H.getHttpClient().getState() .setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds); final String requestUrl = HttpTest.HTTP_BASE_URL + "/junk?param1=1"; HttpMethod get = new GetMethod(requestUrl); get.setRequestHeader("Referer", requestUrl); get.setRequestHeader("User-Agent", "Mozilla/5.0 Sling Integration Test"); int status = H.getHttpClient().executeMethod(get); assertEquals(HttpServletResponse.SC_UNAUTHORIZED, status); }
/** * 同步客户端3.X版本 * * @return */ @GET @Path("httpclient3test") public String httpClient3Test() { HttpClient httpClient = new HttpClient(); HttpMethod method = new GetMethod("https://www.baidu.com/"); try { httpClient.executeMethod(method); System.out.println(method.getURI()); System.out.println(method.getStatusLine()); System.out.println(method.getName()); System.out.println(method.getResponseHeader("Server").getValue()); System.out.println(method.getResponseBodyAsString()); } catch (Exception e) { e.printStackTrace(); } return "httpClient3 test success"; }
/** * Method uses given method parameter to connect to the server and tries to download.<br /> * Method updates download state of HttpFile automatically - sets <code>DownloadState.GETTING</code> and then <code>DownloadState.DOWNLOADING</code> * * @param method HttpMethod - its URL should be a link to the file * @return true if file was successfully downloaded, false otherwise - file was not found, only string content is available * @throws Exception when connection/writing to file failed */ protected boolean tryDownloadAndSaveFile(HttpMethod method) throws Exception { if (httpFile.getState() == DownloadState.PAUSED || httpFile.getState() == DownloadState.CANCELLED) return false; else httpFile.setState(DownloadState.GETTING); if (logger.isLoggable(Level.INFO)) { logger.info("Download link URI: " + method.getURI().toString()); logger.info("Making final request for file"); } try { final InputStream inputStream = client.makeFinalRequestForFile(method, httpFile, true); if (inputStream != null) { logger.info("Saving to file"); downloadTask.saveToFile(inputStream); return true; } else { logger.info("Saving file failed"); return false; } } finally { method.abort(); method.releaseConnection(); } }
/** * Returns result POST method.<br/> * Result POST method is composed by baseURL + action (if baseURL is not null).<br/> * All parameters are set and encoded. * At least one of the parameter has to be not null and the string has to start with 'http'. * * @return new instance of HttpMethod with POST request * @throws BuildMethodException if something goes wrong */ public HttpMethod toPostMethod() throws BuildMethodException { if (referer != null) client.setReferer(referer); String s = generateURL(); if (encodePathAndQuery) try { s = URIUtil.encodePathQuery(s, encoding); } catch (URIException e) { throw new BuildMethodException("Cannot create URI"); } s = checkURI(s); final PostMethod postMethod = client.getPostMethod(s); for (Map.Entry<String, String> entry : parameters.entrySet()) { postMethod.addParameter(entry.getKey(), (encodeParameters) ? encode(entry.getValue()) : entry.getValue()); } setAdditionalHeaders(postMethod); return postMethod; }
protected HttpMethod assertPostStatus(String url, int expectedStatusCode, List<NameValuePair> postParams, List<Header> headers, String assertMessage) throws IOException { final PostMethod post = new PostMethod(url); post.setFollowRedirects(false); if (headers != null) { for (Header header : headers) { post.addRequestHeader(header); } } if (postParams != null) { final NameValuePair[] nvp = {}; post.setRequestBody(postParams.toArray(nvp)); } final int status = H.getHttpClient().executeMethod(post); if (assertMessage == null) { assertEquals(expectedStatusCode, status); } else { assertEquals(assertMessage, expectedStatusCode, status); } return post; }
private String downloadPacContent(String url) throws IOException { if (url == null) { Engine.logProxyManager.debug("(PacManager) Invalid PAC script URL: null"); throw new IOException("Invalid PAC script URL: null"); } HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new IOException("(PacManager) Method failed: " + method.getStatusLine()); } return IOUtils.toString(method.getResponseBodyAsStream(), "UTF-8"); }
public SwiftInvalidResponseException(String message, String operation, URI uri, HttpMethod method) { super(message); this.statusCode = method.getStatusCode(); this.operation = operation; this.uri = uri; String bodyAsString; try { bodyAsString = method.getResponseBodyAsString(); if (bodyAsString == null) { bodyAsString = ""; } } catch (IOException e) { bodyAsString = ""; } this.body = bodyAsString; }
/** * Execute the request with the request and response logged at debug level * @param method method to execute * @param client client to use * @param <M> method type * @return the status code * @throws IOException any failure reported by the HTTP client. */ private <M extends HttpMethod> int execWithDebugOutput(M method, HttpClient client) throws IOException { if (LOG.isDebugEnabled()) { StringBuilder builder = new StringBuilder( method.getName() + " " + method.getURI() + "\n"); for (Header header : method.getRequestHeaders()) { builder.append(header.toString()); } LOG.debug(builder); } int statusCode = client.executeMethod(method); if (LOG.isDebugEnabled()) { LOG.debug("Status code = " + statusCode); } return statusCode; }
@Test public void testValidatingCorrectFormCredentials() throws Exception { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("j_username", "admin")); params.add(new NameValuePair("j_password", "admin")); params.add(new NameValuePair("j_validate", "true")); HttpMethod post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_OK, params, null); assertTrue(post.getResponseBodyAsString().length() == 0); List<NameValuePair> params2 = new ArrayList<NameValuePair>(); params2.add(new NameValuePair("j_validate", "true")); HttpMethod post2 = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_OK, params2, null); assertTrue(post2.getResponseBodyAsString().length() == 0); }
@Test public void testValidatingIncorrectHttpBasicCredentials() throws Exception { // assume http and webdav are on the same host + port URL url = new URL(HttpTest.HTTP_BASE_URL); Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage"); H.getHttpClient().getState() .setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("j_validate", "true")); HttpMethod post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_FORBIDDEN, params, null); assertXReason(post); HttpMethod get = H.assertHttpStatus(HttpTest.HTTP_BASE_URL + "/?j_validate=true", HttpServletResponse.SC_FORBIDDEN); assertXReason(get); }
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 } }
protected long executeMethod(HttpMethod method) throws HttpException, IOException { // execute method long startTime = System.currentTimeMillis(); // TODO: Pool, and sent host configuration and state on execution getHttpClient().executeMethod(method); return System.currentTimeMillis() - startTime; }
protected void setRequestMac(HttpMethod method, byte[] mac) { if(mac == null) { throw new AlfrescoRuntimeException("Mac cannot be null"); } method.setRequestHeader(HEADER_MAC, Base64.encodeBytes(mac)); }
private static BufferedImage readHTTPImage(URI uri, HostConfiguration hostConfiguration, HttpClient client, ConnectionWrapper wrapper) { List<Proxy> list = ProxySelector.getDefault().select(uri); for (Proxy p : list) { InetSocketAddress addr = (InetSocketAddress) p.address(); if (addr == null) hostConfiguration.setProxyHost(null); else hostConfiguration.setProxy(addr.getHostName(), addr.getPort()); try { HttpMethod method = new GetMethod(uri.toString()); synchronized (wrapper) { wrapper.connection = method; } int sc = client.executeMethod(hostConfiguration, method); if (sc != HttpStatus.SC_OK) { continue; } // Check Content Type Header h = method.getResponseHeader("Content-Type"); if (h == null || !h.getValue().contains("image")) continue; return ImageIO.read( method.getResponseBodyAsStream() ); } catch (IOException ex) { continue; } } return null; }
/** * Get the timestamp on the HTTP response * * @param method HttpMethod * @return timestamp (ms, in UNIX time) * @throws IOException */ protected Long getResponseTimestamp(HttpMethod method) throws IOException { Header header = method.getResponseHeader(HEADER_TIMESTAMP); if(header != null) { return Long.valueOf(header.getValue()); } else { return null; } }
@Test public void testPreventLoopIncorrectFormCredentials() throws Exception { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("j_username", "garbage")); params.add(new NameValuePair("j_password", "garbage")); final String requestUrl = HttpTest.HTTP_BASE_URL + "/j_security_check"; List<Header> headers = new ArrayList<Header>(); headers.add(new Header("Referer", requestUrl)); headers.add(new Header("User-Agent", "Mozilla/5.0 Sling Integration Test")); HttpMethod post = assertPostStatus(requestUrl, HttpServletResponse.SC_FORBIDDEN, params, headers, null); assertNotNull(post.getResponseHeader("X-Reason")); assertEquals("Username and Password do not match", post.getResponseHeader("X-Reason").getValue()); }
/** * {@inheritDoc} */ @Override public byte[] decryptResponseBody(HttpMethod method) throws IOException { // TODO fileoutputstream if content is especially large? InputStream body = method.getResponseBodyAsStream(); if(body != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); FileCopyUtils.copy(body, out); AlgorithmParameters params = decodeAlgorithmParameters(method); if(params != null) { byte[] decrypted = encryptor.decrypt(KeyProvider.ALIAS_SOLR, params, out.toByteArray()); return decrypted; } else { throw new AlfrescoRuntimeException("Unable to decrypt response body, missing encryption algorithm parameters"); } } else { return null; } }
/** * Execute a transaction method given only the path. Will select at random * one of the members of the supplied cluster definition and iterate through * the list until a transaction can be successfully completed. The * definition of success here is a complete HTTP transaction, irrespective * of result code. * @param cluster the cluster definition * @param method the transaction method * @param headers HTTP header values to send * @param path the properly urlencoded path * @return the HTTP response code * @throws IOException */ public int executePathOnly(Cluster cluster, HttpMethod method, Header[] headers, String path) throws IOException { IOException lastException; if (cluster.nodes.size() < 1) { throw new IOException("Cluster is empty"); } int start = (int)Math.round((cluster.nodes.size() - 1) * Math.random()); int i = start; do { cluster.lastHost = cluster.nodes.get(i); try { StringBuilder sb = new StringBuilder(); if (sslEnabled) { sb.append("https://"); } else { sb.append("http://"); } sb.append(cluster.lastHost); sb.append(path); URI uri = new URI(sb.toString(), true); return executeURI(method, headers, uri.toString()); } catch (IOException e) { lastException = e; } } while (++i != start && i < cluster.nodes.size()); throw lastException; }
@Override public void setRequestAuthentication(HttpMethod method, byte[] message) throws IOException { if (method instanceof PostMethod) { // encrypt body Pair<byte[], AlgorithmParameters> encrypted = encryptor.encrypt(KeyProvider.ALIAS_SOLR, null, message); setRequestAlgorithmParameters(method, encrypted.getSecond()); ((PostMethod) method).setRequestEntity(new ByteArrayRequestEntity(encrypted.getFirst(), "application/octet-stream")); } long requestTimestamp = System.currentTimeMillis(); // add MAC header byte[] mac = macUtils.generateMAC(KeyProvider.ALIAS_SOLR, new MACInput(message, requestTimestamp, getLocalIPAddress())); if (logger.isDebugEnabled()) { logger.debug("Setting MAC " + mac + " on HTTP request " + method.getPath()); logger.debug("Setting timestamp " + requestTimestamp + " on HTTP request " + method.getPath()); } if (overrideMAC) { mac[0] += (byte) 1; } setRequestMac(method, mac); if (overrideTimestamp) { requestTimestamp += 60000; } // prevent replays setRequestTimestamp(method, requestTimestamp); }
protected HttpMethod getPostMethod(OutputStreamWriter writer) { if (this.chunkSupported) { return new StreamedPostMethod(this.url.getPath(), writer); } return new BufferedPostMethod(this.url.getPath(), writer); }
protected void setMethodTimeout(HttpMethod httpMethod, Method methodToCall) { int timeout = this.timeout; Integer methodTimeout = this.methodResolver.getMethodTimeout(methodToCall); if (methodTimeout != null) { timeout = methodTimeout.intValue(); } if (timeout > 0) { httpMethod.getParams().setSoTimeout(timeout); } }
/** * Will write all the headers included in the request to the method. * The difference between this method and setHeaders in BasicRequestHandler * is that the BasicRequestHandler will also add Via, x-forwarded-for, etc. * These "special" headers should not be added when the proxy is target * directly with a Max-Forwards: 0 headers. * @param method The method to write to * @param request The incoming request * @see RequestHandlerBase#setHeaders(HttpMethod, HttpServletRequest) */ private void setAllHeaders(HttpMethod method, HttpServletRequest request) { Enumeration headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String name = (String) headers.nextElement(); Enumeration value = request.getHeaders(name); while (value.hasMoreElements()) { method.addRequestHeader(name, (String) value.nextElement()); } } }
/** * Will create the method and execute it. After this the method is sent to a * ResponseHandler that is returned. * * @param httpRequest * Request we are receiving from the client * @param url * The location we are proxying to * @return A ResponseHandler that can be used to write the response * @throws MethodNotAllowedException * If the method specified by the request isn't handled * @throws IOException * When there is a problem with the streams * @throws HttpException * The httpclient can throw HttpExcetion when executing the * method */ ResponseHandler executeRequest(HttpServletRequest httpRequest, String url) throws MethodNotAllowedException, IOException, HttpException { RequestHandler requestHandler = RequestHandlerFactory .createRequestMethod(httpRequest.getMethod()); HttpMethod method = requestHandler.process(httpRequest, url); method.setFollowRedirects(false); /* * Why does method.validate() return true when the method has been * aborted? I mean, if validate returns true the API says that means * that the method is ready to be executed. TODO I don't like doing type * casting here, see above. */ if (!((HttpMethodBase) method).isAborted()) { httpClient.executeMethod(method); if (method.getStatusCode() == 405) { Header allow = method.getResponseHeader("allow"); String value = allow.getValue(); throw new MethodNotAllowedException( "Status code 405 from server", AllowedMethodHandler.processAllowHeader(value)); } } return ResponseHandlerFactory.createResponseHandler(method); }
/** * Checks the method being received and created a * suitable ResponseHandler for this method. * * @param method Method to handle * @return The handler for this response * @throws MethodNotAllowedException If no method could be choose this exception is thrown */ public static ResponseHandler createResponseHandler(HttpMethod method) throws MethodNotAllowedException { if (!AllowedMethodHandler.methodAllowed(method)) { throw new MethodNotAllowedException("The method " + method.getName() + " is not in the AllowedHeaderHandler's list of allowed methods.", AllowedMethodHandler.getAllowHeader()); } ResponseHandler handler = null; if (method.getName().equals("OPTIONS")) { handler = new OptionsResponseHandler((OptionsMethod) method); } else if (method.getName().equals("GET")) { handler = new GetResponseHandler((GetMethod) method); } else if (method.getName().equals("HEAD")) { handler = new HeadResponseHandler((HeadMethod) method); } else if (method.getName().equals("POST")) { handler = new PostResponseHandler((PostMethod) method); } else if (method.getName().equals("PUT")) { handler = new PutResponseHandler((PutMethod) method); } else if (method.getName().equals("DELETE")) { handler = new DeleteResponseHandler((DeleteMethod) method); } else if (method.getName().equals("TRACE")) { handler = new TraceResponseHandler((TraceMethod) method); } else { throw new MethodNotAllowedException("The method " + method.getName() + " was allowed by the AllowedMethodHandler, not by the factory.", handledMethods); } return handler; }
@Test(expected = PSPCommunicationException.class) public void charge_IOException() throws Exception { // setup when( Integer.valueOf(httpClientMock .executeMethod(any(HttpMethod.class)))).thenThrow( new IOException()); ChargingData chargingData = createChargingData(); RequestData requestData = createRequestData(CREDIT_CARD); PostMethodStub.setStubReturnValue(sampleResponse); // execute psp.charge(requestData, chargingData); }
@Test(expected = PSPProcessingException.class) public void charge_Exception() throws Exception { // setup when( Integer.valueOf(httpClientMock .executeMethod(any(HttpMethod.class)))).thenThrow( new RuntimeException()); ChargingData chargingData = createChargingData(); RequestData requestData = createRequestData(CREDIT_CARD); PostMethodStub.setStubReturnValue(sampleResponse); // execute psp.charge(requestData, chargingData); }
@Test(expected = PSPCommunicationException.class) public void determineRegistrationLink_IOException() throws Exception { // SETUP when( Integer.valueOf(httpClientMock .executeMethod(any(HttpMethod.class)))).thenThrow( new IOException()); RequestData requestData = createRequestData(DIRECT_DEBIT); // EXECUTE psp.determineRegistrationLink(requestData); }
@Test(expected = PSPCommunicationException.class) public void determineRegistrationLink_Exception() throws Exception { // SETUP when( Integer.valueOf(httpClientMock .executeMethod(any(HttpMethod.class)))).thenThrow( new RuntimeException()); RequestData requestData = createRequestData(DIRECT_DEBIT); // EXECUTE psp.determineRegistrationLink(requestData); }
@Override public int executeMethod(HttpMethod method) throws IOException, HttpException { if (throwHTTPException) { throw new HttpException("exception caused by test"); } if (throwIOException) { throw new IOException("exception caused by test"); } return 0; }
@Override public Document getDocument(Document document, DocumentFactory factory) throws IOException { HttpMethod request = new GetMethod(baseURL); request.addRequestHeader("Authorization", String.format("Bearer %s", bearerToken)); //TODO request.setPath(path + document.getId()); int status = client.executeMethod(request); if(status == 200) { JsonNode json = mapper.readValue(request.getResponseBody(), JsonNode.class); for(FieldDescriptor descriptor : factory.listFields()) { try { Object value = getValue(json, descriptor); if(value != null) { document.setValue(descriptor, value); } else LOG.warn("No data found for id {}", document.getId()); } catch (IOException e) { LOG.warn("Cannot use data for id {}: {}", document.getId(), e.getMessage()); } } return document; } else throw new IOException(request.getStatusText()); }