org.apache.commons.httpclient.HttpException Java Examples

The following examples show how to use org.apache.commons.httpclient.HttpException. 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: MultipartPostMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example #2
Source File: SolrQueryHTTPClient.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected JSONResult postSolrQuery(HttpClient httpClient, String url, JSONObject body, SolrJsonProcessor<?> jsonProcessor, String spellCheckParams)
            throws UnsupportedEncodingException, IOException, HttpException, URIException,
            JSONException
{
    JSONObject json = postQuery(httpClient, url, body);
    if (spellCheckParams != null)
    {
        SpellCheckDecisionManager manager = new SpellCheckDecisionManager(json, url, body, spellCheckParams);
        if (manager.isCollate())
        {
            json = postQuery(httpClient, manager.getUrl(), body);
        }
        json.put("spellcheck", manager.getSpellCheckJsonValue());
    }

        JSONResult results = jsonProcessor.getResult(json);

        if (s_logger.isDebugEnabled())
        {
            s_logger.debug("Sent :" + url);
            s_logger.debug("   with: " + body.toString());
            s_logger.debug("Got: " + results.getNumberFound() + " in " + results.getQueryTime() + " ms");
        }
        
        return results;
}
 
Example #3
Source File: DataSetFactory.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static RESTDataSet manageSolrDataSet(JSONObject jsonConf, List<DataSetParameterItem> parameters)
		throws JSONException, HttpException, HMACSecurityException, IOException {
	SolrDataSet res = null;

	HashMap<String, String> parametersMap = new HashMap<String, String>();
	if (parameters != null) {
		for (Iterator iterator = parameters.iterator(); iterator.hasNext();) {
			DataSetParameterItem dataSetParameterItem = (DataSetParameterItem) iterator.next();
			parametersMap.put(dataSetParameterItem.getDefaultValue(), dataSetParameterItem.getName());
		}
	}

	String solrType = jsonConf.getString(SolrDataSetConstants.SOLR_TYPE);
	Assert.assertNotNull(solrType, "Solr type cannot be null");
	res = solrType.equalsIgnoreCase(SolrDataSetConstants.TYPE.DOCUMENTS.name()) ? new SolrDataSet(jsonConf, parametersMap)
			: new FacetSolrDataSet(jsonConf, parametersMap);
	res.setDsType(DataSetConstants.DS_SOLR_NAME);

	if (!jsonConf.has(SolrDataSetConstants.SOLR_FIELDS)) {
		JSONArray solrFields = res.getSolrFields();
		jsonConf.put(SolrDataSetConstants.SOLR_FIELDS, solrFields);
		res.setConfiguration(jsonConf.toString());
	}
	res.setSolrQueryParameters(res.getSolrQuery(), res.getParamsMap());
	return res;
}
 
Example #4
Source File: AbstractTest4.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
public static void callAPI(String url, String user, String uToken) throws HttpException, IOException {
	if(url.indexOf("?") < 0) {
		url += "?uName=" +user+ "&uToken=" + uToken;
	}
	else {
		url += "&uName=" +user+ "&uToken=" + uToken;
	}
	PostMethod postMethod = new PostMethod(url);
	postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

    // 最后生成一个HttpClient对象,并发出postMethod请求
    HttpClient httpClient = new HttpClient();
    int statusCode = httpClient.executeMethod(postMethod);
    if(statusCode == 200) {
        System.out.print("返回结果: ");
        String soapResponseData = postMethod.getResponseBodyAsString();
        System.out.println(soapResponseData);     
    }
    else {
        System.out.println("调用失败!错误码:" + statusCode);
    }
}
 
Example #5
Source File: OAuth2Client.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private String sendHttpPost(PostMethod httppost) throws HttpException, IOException, JSONException {
	HttpClient httpClient = getHttpClient();
	int statusCode = httpClient.executeMethod(httppost);
	byte[] response = httppost.getResponseBody();
	if (statusCode != 200) {
		logger.error("Error while getting access token from OAuth2 provider: server returned statusCode = " + statusCode);
		LogMF.error(logger, "Server response is:\n{0}", new Object[] { new String(response) });
		throw new SpagoBIRuntimeException("Error while getting access token from OAuth2 provider: server returned statusCode = " + statusCode);
	}

	String responseStr = new String(response);
	LogMF.debug(logger, "Server response is:\n{0}", responseStr);
	JSONObject jsonObject = new JSONObject(responseStr);
	String accessToken = jsonObject.getString("access_token");

	return accessToken;
}
 
Example #6
Source File: HttpUtil.java    From OfficeAutomatic-System with Apache License 2.0 6 votes vote down vote up
public static String sendGet(String urlParam) throws HttpException, IOException {
    // 创建httpClient实例对象
    HttpClient httpClient = new HttpClient();
    // 设置httpClient连接主机服务器超时时间:15000毫秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 创建GET请求方法实例对象
    GetMethod getMethod = new GetMethod(urlParam);
    // 设置post请求超时时间
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    getMethod.addRequestHeader("Content-Type", "application/json");

    httpClient.executeMethod(getMethod);

    String result = getMethod.getResponseBodyAsString();
    getMethod.releaseConnection();
    return result;
}
 
Example #7
Source File: RestClient.java    From Kylin with Apache License 2.0 6 votes vote down vote up
public void wipeCache(String type, String action, String name) throws IOException {
    String url = baseUrl + "/cache/" + type + "/" + name + "/" + action;
    HttpMethod request = new PutMethod(url);

    try {
        int code = client.executeMethod(request);
        String msg = Bytes.toString(request.getResponseBody());

        if (code != 200)
            throw new IOException("Invalid response " + code + " with cache wipe url " + url + "\n" + msg);

    } catch (HttpException ex) {
        throw new IOException(ex);
    } finally {
        request.releaseConnection();
    }
}
 
Example #8
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 #9
Source File: GroupMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveParticipant() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/participants/" + part2.getKey();
    final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    method.releaseConnection();

    assertTrue(code == 200);

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

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

    assertTrue(code == 200);

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

    assertFalse(found);
}
 
Example #11
Source File: MailUtils.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * User tinyurl service as url shorter Depends on commons-httpclient:commons-httpclient:jar:3.0 because of
 * org.apache.jackrabbit:jackrabbit-webdav:jar:1.6.4
 */
public static String getTinyUrl(String fullUrl) throws HttpException, IOException {
	HttpClient httpclient = new HttpClient();

	// Prepare a request object
	HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
	method.setQueryString(new NameValuePair[]{new NameValuePair("url", fullUrl)});
	httpclient.executeMethod(method);
	InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
	StringWriter sw = new StringWriter();
	int c;
	while ((c = isr.read()) != -1)
		sw.write(c);
	isr.close();
	method.releaseConnection();

	return sw.toString();
}
 
Example #12
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 #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: GroupMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetParticipantsAdmin() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final String request = "/groups/" + g1.getKey() + "/participants";
    final HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<UserVO> participants = parseUserArray(body);
    assertNotNull(participants);
    assertEquals(participants.size(), 2);

    Long idKey1 = null;
    Long idKey2 = null;
    for (final UserVO participant : participants) {
        if (participant.getKey().equals(part1.getKey())) {
            idKey1 = part1.getKey();
        } else if (participant.getKey().equals(part2.getKey())) {
            idKey2 = part2.getKey();
        }
    }
    assertNotNull(idKey1);
    assertNotNull(idKey2);
}
 
Example #15
Source File: Simulator.java    From realtime-analytics with GNU General Public License v2.0 6 votes vote down vote up
private static void sendMessage() throws IOException, JsonProcessingException, JsonGenerationException,
            JsonMappingException, UnsupportedEncodingException, HttpException {
        ObjectMapper mapper = new ObjectMapper();

        Map<String, Object> m = new HashMap<String, Object>();

        m.put("si", "12345");
        m.put("ct", System.currentTimeMillis());
        
        String payload = mapper.writeValueAsString(m);
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod("http://localhost:8080/tracking/ingest/PulsarRawEvent");
//      method.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
        method.setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8"));
        int status = client.executeMethod(method);
        System.out.println(Arrays.toString(method.getResponseHeaders()));
        System.out.println("Status code: " + status + ", Body: " +  method.getResponseBodyAsString());
    }
 
Example #16
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 #17
Source File: ExpectContinueMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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");
        }
    }
}
 
Example #18
Source File: YarnJobCrawlerTask.java    From Hue-Ctrip-DI with MIT License 6 votes vote down vote up
private List<YarnJobsDo> getJobList(long maxStartTime)
		throws HttpException, IOException {
	List<YarnJobsDo> jobsList = new ArrayList<YarnJobsDo>();

	JSONObject json = getJson();
	JSONObject jobs = (JSONObject) json.get("jobs");
	JSONArray jobArray = (JSONArray) jobs.get("job");
	@SuppressWarnings("unchecked")
	ListIterator<JSONObject> iterator = jobArray.listIterator();
	while (iterator.hasNext()) {
		JSONObject jobObject = iterator.next();
		long startTime = jobObject.getLong("startTime");
		if (startTime > maxStartTime) {
			YarnJobsDo yarnJobsDo = toYarnJobsDo(jobObject);
			jobsList.add(yarnJobsDo);
		}
	}
	return jobsList;
}
 
Example #19
Source File: GroupMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetOwnersAdmin() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners";
    final HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<UserVO> owners = parseUserArray(body);
    assertNotNull(owners);
    assertEquals(owners.size(), 2);

    Long idKey1 = null;
    Long idKey2 = null;
    for (final UserVO participant : owners) {
        if (participant.getKey().equals(owner1.getKey())) {
            idKey1 = owner1.getKey();
        } else if (participant.getKey().equals(owner2.getKey())) {
            idKey2 = owner2.getKey();
        }
    }
    assertNotNull(idKey1);
    assertNotNull(idKey2);
}
 
Example #20
Source File: GroupMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetParticipants() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("rest-four", "A6B7C8");

    final String request = "/groups/" + g1.getKey() + "/participants";
    final HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);

    // g1 not authorized
    assertEquals(code, 401);
}
 
Example #21
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportCp() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("cp-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "cp-demo.zip"), new StringPart("resourcename", "CP demo"),
            new StringPart("displayname", "CP demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("CP demo", re.getDisplayname());
}
 
Example #22
Source File: AuthenticationITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrongPassword() throws HttpException, IOException {
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path("administrator").queryParam("password", "blabla").build();
    final GetMethod method = createGet(uri, MediaType.TEXT_PLAIN, true);
    final HttpClient c = getHttpClient();
    final int code = c.executeMethod(method);
    assertEquals(401, code);
}
 
Example #23
Source File: FacebookSignupTest.java    From mamute with Apache License 2.0 5 votes vote down vote up
private String getAppToken() throws IOException, HttpException {
	String appSecret = env.get(OAuthServiceCreator.FACEBOOK_APP_SECRET);
	String clientId = env.get(OAuthServiceCreator.FACEBOOK_CLIENT_ID);
	
	GetMethod method = new GetMethod("https://graph.facebook.com/oauth/access_token" +
			"?client_id=" + clientId +
			"&client_secret=" + appSecret +
			"&grant_type=client_credentials");
	int status = client.executeMethod(method);
	if (status != 200) {
		fail("could not create app access_token");
	}
	String responseBody = method.getResponseBodyAsString();
	return responseBody.split("=")[1];
}
 
Example #24
Source File: FacebookSignupTest.java    From mamute with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private FacebookUser createFacebookTestUser(String appToken) throws URIException,
		IOException, HttpException {
	String clientId = env.get(OAuthServiceCreator.FACEBOOK_CLIENT_ID);
	GetMethod method = new GetMethod("https://graph.facebook.com/"+clientId+"/accounts/test-users?" +
			"installed=true" +
			"&name=TESTUSER" +
			"&method=post" +
			"&access_token=" + URLEncoder.encode(appToken));
	int status = client.executeMethod(method);
	if (status != 200) {
		fail("could not create test user, facebook sent " + status + " status code");
	}
	return new FacebookUser(method.getResponseBodyAsString());
}
 
Example #25
Source File: RepositoryEntriesITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testImportCp() throws HttpException, IOException, URISyntaxException {
    final URL cpUrl = RepositoryEntriesITCase.class.getResource("cp-demo.zip");
    assertNotNull(cpUrl);
    final File cp = new File(cpUrl.toURI());

    final HttpClient c = loginWithCookie("administrator", "olat");
    final PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", cp), new StringPart("filename", "cp-demo.zip"), new StringPart("resourcename", "CP demo"),
            new StringPart("displayname", "CP demo") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class);
    assertNotNull(vo);

    final Long key = vo.getKey();
    final RepositoryEntry re = RepositoryServiceImpl.getInstance().lookupRepositoryEntry(key);
    assertNotNull(re);
    assertNotNull(re.getOwnerGroup());
    assertNotNull(re.getOlatResource());
    assertEquals("CP demo", re.getDisplayname());
}
 
Example #26
Source File: HeadMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Overrides {@link HttpMethodBase} method to <i>not</i> read a response
 * body, despite the presence of a <tt>Content-Length</tt> or
 * <tt>Transfer-Encoding</tt> header.
 * 
 * @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.
 *
 * @see #readResponse
 * @see #processResponseBody
 * 
 * @since 2.0
 */
protected void readResponseBody(HttpState state, HttpConnection conn)
throws HttpException, IOException {
    LOG.trace(
        "enter HeadMethod.readResponseBody(HttpState, HttpConnection)");
    
    int bodyCheckTimeout = 
        getParams().getIntParameter(HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, -1);

    if (bodyCheckTimeout < 0) {
        responseBodyConsumed();
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Check for non-compliant response body. Timeout in " 
             + bodyCheckTimeout + " ms");    
        }
        boolean responseAvailable = false;
        try {
            responseAvailable = conn.isResponseAvailable(bodyCheckTimeout);
        } catch (IOException e) {
            LOG.debug("An IOException occurred while testing if a response was available,"
                + " we will assume one is not.", 
                e);
            responseAvailable = false;
        }
        if (responseAvailable) {
            if (getParams().isParameterTrue(HttpMethodParams.REJECT_HEAD_BODY)) {
                throw new ProtocolException(
                    "Body content may not be sent in response to HTTP HEAD request");
            } else {
                LOG.warn("Body content returned in response to HTTP HEAD");    
            }
            super.readResponseBody(state, conn);
        }
    }

}
 
Example #27
Source File: AuthenticationITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnkownUser() throws HttpException, IOException {
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path("treuitr").queryParam("password", "blabla").build();
    final GetMethod method = createGet(uri, MediaType.TEXT_PLAIN, true);
    final HttpClient c = getHttpClient();
    final int code = c.executeMethod(method);
    assertEquals(401, code);
}
 
Example #28
Source File: NotificationsITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testExecuteService() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final String request = "/notifications";
    final GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
}
 
Example #29
Source File: RestApiLoginFilterITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Test if a session cookie is created
 * 
 * @throws HttpException
 * @throws IOException
 */
@Test
public void testCookieAuthentication() throws HttpException, IOException {
    final HttpClient c = getAuthenticatedCookieBasedClient("administrator", "olat");
    final Cookie[] cookies = c.getState().getCookies();
    assertNotNull(cookies);
    assertTrue(cookies.length > 0);
}
 
Example #30
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Login the HttpClient based on the session cookie
 * 
 * @param username
 * @param password
 * @param c
 * @throws HttpException
 * @throws IOException
 */
public void loginWithCookie(final String username, final String password, final HttpClient c) throws HttpException, IOException {
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build();
    final GetMethod method = new GetMethod(uri.toString());
    method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    final int response = c.executeMethod(method);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    assertTrue(response == 200);
    assertTrue(body != null && body.length() > "<hello></hello>".length());
}