org.apache.commons.httpclient.HttpMethod Java Examples

The following examples show how to use org.apache.commons.httpclient.HttpMethod. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GroupMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddParticipant() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/participants/" + part3.getKey();
    final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200 || code == 201);

    final List<Identity> participants = securityManager.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup());
    boolean found = false;
    for (final Identity participant : participants) {
        if (participant.getKey().equals(part3.getKey())) {
            found = true;
        }
    }

    assertTrue(found);
}
 
Example #2
Source File: Filter5HttpProxy.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * 处理请求自动转向问题
 * </p>
 * @param appServer
 * @param response
 * @param client
 * @param httppost
 * @throws IOException
 * @throws BusinessServletException
 */
private void dealWithRedirect(AppServer appServer, HttpServletResponse response, HttpClient client, HttpMethod httpMethod) 
           throws IOException, BusinessServletException {
    
	Header location = httpMethod.getResponseHeader("location");
	httpMethod.releaseConnection();
	
	if ( location == null || EasyUtils.isNullOrEmpty(location.getValue()) ) {
		throw new BusinessServletException(appServer.getName() + "(" + appServer.getCode() + ")返回错误的自动转向地址信息");
	}
	
	String redirectURI = location.getValue();
       GetMethod redirect = new GetMethod(redirectURI);
       try {
           client.executeMethod(redirect); // 发送Get请求
           
           transmitResponse(appServer, response, client, redirect);
           
       } finally {
           redirect.releaseConnection();
       }
}
 
Example #3
Source File: BigSwitchBcfApi.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
protected HttpMethod createMethod(final String type, final String uri, final int port) throws BigSwitchBcfApiException {
    String url;
    try {
        url = new URL(S_PROTOCOL, host, port, uri).toString();
    } catch (MalformedURLException e) {
        S_LOGGER.error("Unable to build Big Switch API URL", e);
        throw new BigSwitchBcfApiException("Unable to build Big Switch API URL", e);
    }

    if ("post".equalsIgnoreCase(type)) {
        return new PostMethod(url);
    } else if ("get".equalsIgnoreCase(type)) {
        return new GetMethod(url);
    } else if ("delete".equalsIgnoreCase(type)) {
        return new DeleteMethod(url);
    } else if ("put".equalsIgnoreCase(type)) {
        return new PutMethod(url);
    } else {
        throw new BigSwitchBcfApiException("Requesting unknown method type");
    }
}
 
Example #4
Source File: HttpMethodBaseExecuteMethodInterceptor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private String getHost(HttpMethod httpMethod, HttpConnection httpConnection) {
    try {
        final URI uri = httpMethod.getURI();
        // if uri have schema
        if (uri.isAbsoluteURI()) {
            return HttpClient3RequestWrapper.getEndpoint(uri.getHost(), uri.getPort());
        }
        if (httpConnection != null) {
            final String host = httpConnection.getHost();
            final int port = HttpClient3RequestWrapper.getPort(httpConnection);
            return HttpClient3RequestWrapper.getEndpoint(host, port);
        }
    } catch (Exception e) {
        if (isDebug) {
            logger.debug("Failed to get host. httpMethod={}", httpMethod, e);
        }
    }
    return null;
}
 
Example #5
Source File: ExchangeFormAuthenticator.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
protected String getAbsoluteUri(HttpMethod method, String path) throws URIException {
    URI uri = method.getURI();
    if (path != null) {
        // reset query string
        uri.setQuery(null);
        if (path.startsWith("/")) {
            // path is absolute, replace method path
            uri.setPath(path);
        } else if (path.startsWith("http://") || path.startsWith("https://")) {
            return path;
        } else {
            // relative path, build new path
            String currentPath = method.getPath();
            int end = currentPath.lastIndexOf('/');
            if (end >= 0) {
                uri.setPath(currentPath.substring(0, end + 1) + path);
            } else {
                throw new URIException(uri.getURI());
            }
        }
    }
    return uri.getURI();
}
 
Example #6
Source File: GroupMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddTutor() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners/" + owner3.getKey();
    final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200 || code == 201);

    final List<Identity> owners = securityManager.getIdentitiesOfSecurityGroup(g1.getOwnerGroup());
    boolean found = false;
    for (final Identity owner : owners) {
        if (owner.getKey().equals(owner3.getKey())) {
            found = true;
        }
    }

    assertTrue(found);
}
 
Example #7
Source File: BasicRestApiResult.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/**
 * Create an HttpMethod.
 * 
 * @param properties Properties to drive the API.
 * @param path Path to REST API method.
 * @param param Parameter for REST API method.
 * @return HttpMethod.
 */
protected HttpMethod createHttpMethod(
    Map<String, String> properties, String path, String param) {
  String encodedPath = path;
  if ((param != null) && !param.isEmpty()) {
    encodedPath += "/" + param;
    // NOTE: Do not encode, doesn't work with titles like Sergueï Chakourov
    /*try {
      encodedPath += "/" + URLEncoder.encode(param, "UTF8");
    } catch (UnsupportedEncodingException e) {
      // Nothing
    }*/
  }
  return Hc3HttpUtils.createHttpMethod(
      getWiki().getSettings().getHostURL(true) + "/" + encodedPath,
      properties, false);
}
 
Example #8
Source File: NetworkTools.java    From yeti with MIT License 6 votes vote down vote up
public static String getHTMLFromUrl(String url) {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    String response = "";
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            response = method.getResponseBodyAsString();
        }
    } catch (IOException e) {
        Logger.getLogger("networkTools.getHTMLFromUrl").log(Level.SEVERE, null, e);
    } finally {
        method.releaseConnection();
    }
    return response;
}
 
Example #9
Source File: PaymentServiceProviderBeanTest.java    From development with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #10
Source File: HttpClientTransmitterImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #11
Source File: CoursesITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCourses() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/repo/courses", MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<CourseVO> courses = parseCourseArray(body);
    assertNotNull(courses);
    assertTrue(courses.size() >= 2);

    CourseVO vo1 = null;
    CourseVO vo2 = null;
    for (final CourseVO course : courses) {
        if (course.getTitle().equals("courses1")) {
            vo1 = course;
        } else if (course.getTitle().equals("courses2")) {
            vo2 = course;
        }
    }
    assertNotNull(vo1);
    assertEquals(vo1.getKey(), course1.getResourceableId());
    assertNotNull(vo2);
    assertEquals(vo2.getKey(), course2.getResourceableId());
}
 
Example #12
Source File: StressTestDirectAttach.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private static String executeRegistration(String server, String username, String password) throws HttpException, IOException {
    String url = server + "?command=registerUserKeys&id=" + s_userId.get().toString();
    s_logger.info("registering: " + username);
    String returnValue = null;
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> requestKeyValues = getSingleValueFromXML(is, new String[] {"apikey", "secretkey"});
        s_apiKey.set(requestKeyValues.get("apikey"));
        returnValue = requestKeyValues.get("secretkey");
    } else {
        s_logger.error("registration failed with error code: " + responseCode);
    }
    return returnValue;
}
 
Example #13
Source File: RequestHandlerBase.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #14
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetUserNotAdmin() throws IOException {
    final HttpClient c = loginWithCookie("rest-one", "A6B7C8");

    final HttpMethod method = createGet("/users/" + id2.getKey(), MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final UserVO vo = parse(body, UserVO.class);

    assertNotNull(vo);
    assertEquals(vo.getKey(), id2.getKey());
    assertEquals(vo.getLogin(), id2.getName());
    // no properties for security reason
    assertTrue(vo.getProperties().isEmpty());
}
 
Example #15
Source File: AbstractHttpClient.java    From alfresco-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean isRedirect(HttpMethod method)
{
    switch (method.getStatusCode()) {
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        if (method.getFollowRedirects()) {
            return true;
        } else {
            return false;
        }
    default:
        return false;
    }
}
 
Example #16
Source File: ChatterCommands.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * <p>This creates a HttpMethod with the message as its payload and image attachment. The message should be a properly formatted JSON
 * String (No validation is done on this).</p>
 *
 * <p>The message can be easily created using the {@link #getJsonPayload(Message)} method.</p>
 *
 * @param uri The full URI which we will post to
 * @param message A properly formatted JSON message. UTF-8 is expected
 * @param image A complete instance of ImageAttachment object
 * @throws IOException
 */
public HttpMethod getJsonPostForMultipartRequestEntity(String uri, String message, ImageAttachment image) throws IOException {
    PostMethod post = new PostMethod(uri);

    StringPart bodyPart = new StringPart("json", message);
    bodyPart.setContentType("application/json");

    FilePart filePart= new FilePart("feedItemFileUpload", image.retrieveObjectFile());
    filePart.setContentType(image.retrieveContentType());

    Part[] parts = {
            bodyPart,
            filePart,
    };

    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    return post;
}
 
Example #17
Source File: GroupMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveTutor() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners/" + owner2.getKey();
    final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200);

    final List<Identity> owners = securityManager.getIdentitiesOfSecurityGroup(g1.getOwnerGroup());
    boolean found = false;
    for (final Identity owner : owners) {
        if (owner.getKey().equals(owner2.getKey())) {
            found = true;
        }
    }

    assertFalse(found);
}
 
Example #18
Source File: SwiftInvalidResponseException.java    From hadoop with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #19
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 6 votes vote down vote up
private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut,
        HttpMethod httpMethod) {
    if (skipContentCache && null != cacheData) {
        if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) {
            httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader());
        }
        if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) {
            httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5());
        }
    }

    httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate");

    // 设置HttpMethod的参数
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout((int) onceTimeOut);
    // ///////////////////////
    httpMethod.setParams(params);
    httpClient.getHostConfiguration().setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
        diamondConfigure.getPort());
}
 
Example #20
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public String getHeaderField(int nth)
// throws IOException TODO: doesn't this one throw exceptions??
{
  try {
    HttpMethod res = getResult(true);
    Header[] hs = res.getResponseHeaders();

    if (hs.length > nth && nth >= 0) {
      return hs[nth].getValue();
    } else {
      return null;
    }
  } catch (IOException e) {
    return null;
  }
}
 
Example #21
Source File: GrafanaDashboardServiceImpl.java    From cymbal with Apache License 2.0 6 votes vote down vote up
private void doHttpAPI(HttpMethod method) throws MonitorException {
    // 拼装http post请求,调用grafana http api建立dashboard
    HttpClient httpclient = new HttpClient();
    httpclient.getParams().setConnectionManagerTimeout(Constant.Http.CONN_TIMEOUT);
    httpclient.getParams().setSoTimeout(Constant.Http.SO_TIMEOUT);

    // api key
    method.setRequestHeader("Authorization", String.format("Bearer %s", grafanaApiKey));
    try {

        int statusCode = httpclient.executeMethod(method);
        // 若http请求失败
        if (statusCode != Constant.Http.STATUS_OK) {
            String responseBody = method.getResponseBodyAsString();
            throw new MonitorException(responseBody);
        }
    } catch (Exception e) {
        if (e instanceof MonitorException) {
            throw (MonitorException) e;
        } else {
            new MonitorException(e);
        }
    } finally {
        method.releaseConnection();
    }
}
 
Example #22
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public long getHeaderFieldDate(String key, long def) throws IOException {
  HttpMethod res = getResult(true);
  Header head = res.getResponseHeader(key);

  if (head == null) {
    return def;
  }

  try {
    Date date = DateUtil.parseDate(head.getValue());
    return date.getTime();

  } catch (DateParseException e) {
    return def;
  }
}
 
Example #23
Source File: RESTMetadataProvider.java    From vind with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #24
Source File: HTTPUtils.java    From cosmic with Apache License 2.0 5 votes vote down vote up
/**
 * @param httpClient
 * @param httpMethod
 * @return Returns the HTTP Status Code or -1 if an exception occurred.
 */
public static int executeMethod(final HttpClient httpClient, final HttpMethod httpMethod) {
    // Execute GetMethod
    try {
        return httpClient.executeMethod(httpMethod);
    } catch (final IOException e) {
        LOGGER.warn("Exception while executing HttpMethod " + httpMethod.getName() + " on URL " + httpMethod.getPath());
        return -1;
    }
}
 
Example #25
Source File: Hc3HttpUtils.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Create an HttpMethod.
 * 
 * @param url URL of the request.
 * @param properties Properties to add to the request.
 * @param canUseGetMethod Flag indicating if a GET method can be used.
 * @return HttpMethod.
 */
public static HttpMethod createHttpMethod(
    String url,
    Map<String, String> properties,
    boolean canUseGetMethod) {
  try {
    if (canUseGetMethod) {
      return createHttpGetMethod(url, properties);
    }
    return createHttpPostMethod(url, properties);
  } catch (URIException e) {
    log.error("Invalid URL {}: {}", url, e.getMessage());
    return null;
  }
}
 
Example #26
Source File: MorphologicalServiceFRImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
private InputStream retreiveXMLReply(String word) {
    HttpClient client = HttpClientFactory.getHttpClientInstance();
    HttpMethod method = new GetMethod(MORPHOLOGICAL_SERVICE_ADRESS);
    NameValuePair wordValues = new NameValuePair(GLOSS_TERM_PARAM, word);
    if (log.isDebugEnabled()) {
        String url = MORPHOLOGICAL_SERVICE_ADRESS + "?" + GLOSS_TERM_PARAM + "=" + word;
        log.debug("Send GET request to morph-service with URL: " + url);
    }
    method.setQueryString(new NameValuePair[] { wordValues });
    try {
        client.executeMethod(method);
        int status = method.getStatusCode();
        if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
            if (log.isDebugEnabled()) {
                log.debug("got a valid reply!");
            }
        } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            log.error("Morphological Service unavailable (404)::" + method.getStatusLine().toString(), null);
        } else {
            log.error("Unexpected HTTP Status::" + method.getStatusLine().toString(), null);
        }
    } catch (Exception e) {
        log.error("Unexpected exception trying to get flexions!", e);
    }
    Header responseHeader = method.getResponseHeader("Content-Type");
    if (responseHeader == null) {
        // error
        log.error("URL not found!", null);
    }
    HttpRequestMediaResource mr = new HttpRequestMediaResource(method);
    InputStream inputStream = mr.getInputStream();

    return inputStream;
}
 
Example #27
Source File: ChatterResponseTest.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testGetStatusCode() {
    int statusCode = 199;
    HttpMethod method = mock(HttpMethod.class);
    when(method.getStatusCode()).thenReturn(statusCode);

    ChatterResponse response = new ChatterResponse(method);
    assertEquals(statusCode, response.getStatusCode());
}
 
Example #28
Source File: PaymentServiceProviderBeanTest.java    From development with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #29
Source File: SOLRAPIClientTest.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example #30
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 5 votes vote down vote up
Set<String> getUpdateDataIdsInBody(HttpMethod httpMethod) {
    Set<String> modifiedDataIdSet = new HashSet<String>();
    try {
        String modifiedDataIdsString = httpMethod.getResponseBodyAsString();
        return convertStringToSet(modifiedDataIdsString);
    }
    catch (Exception e) {

    }
    return modifiedDataIdSet;

}