Java Code Examples for org.apache.commons.httpclient.HttpClient#executeMethod()

The following examples show how to use org.apache.commons.httpclient.HttpClient#executeMethod() . These examples are extracted from open source projects. 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 Project: ci.maven   File: RunTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void endpointTest() throws Exception {
      HttpClient client = new HttpClient();

     GetMethod method = new GetMethod(URL);
      try {
         int statusCode = client.executeMethod(method);

         assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode);

         String response = method.getResponseBodyAsString();

         assertTrue("Unexpected response body", response.contains("hello world"));
         // Note that checkLogMessage returns true if it does NOT find the message.
         // So I am verifying that SLF4J loaded properly.
         assertTrue(checkLogMessage(2000, "SLF4J: Failed to load class"));
         // And then verify the logging message was successfully logged.
         assertFalse(checkLogMessage(2000, "SLF4J Logger is ready for messages."));
      } finally {
         method.releaseConnection();
      }
}
 
Example 2
@Test
public void testBareBoneConfig() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    // create an contact node
    final URI newContactUri = getElementsUri(course1).path("contact").queryParam("parentNodeId", rootNodeId).queryParam("position", "0")
            .queryParam("shortTitle", "Contact-0").queryParam("longTitle", "Contact-long-0").queryParam("objectives", "Contact-objectives-0").build();
    final PutMethod method = createPut(newContactUri, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();

    assertEquals(200, code);
    final CourseNodeVO contactNode = parse(body, CourseNodeVO.class);
    assertNotNull(contactNode);
    assertNotNull(contactNode.getId());
    assertEquals(contactNode.getShortTitle(), "Contact-0");
    assertEquals(contactNode.getLongTitle(), "Contact-long-0");
    assertEquals(contactNode.getLearningObjectives(), "Contact-objectives-0");
    assertEquals(contactNode.getParentId(), rootNodeId);
}
 
Example 3
Source Project: tomee   File: SessionScopeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldBeAbleToAccessServletAndEjb() throws Exception {
    final String sessionUrl = webappUrl.toExternalForm() + "session";
    String[] sessionResult = new String[2];
    for (int i = 0; i < sessionResult.length; i++) {
        HttpClient client = new HttpClient();
        HttpMethod get = new GetMethod(sessionUrl);
        String[] contents = new String[2];
        try {
            for (int j = 0; j < contents.length; j++) {
                int out = client.executeMethod(get);
                if (out != 200) {
                    throw new RuntimeException("get " + sessionUrl + " returned " + out);
                }
                contents[j] = get.getResponseBodyAsString();
            }

            assertEquals(contents[0], contents[1]);
        } finally {
            get.releaseConnection();
        }
        sessionResult[i] = contents[0];
    }

    assertNotSame(sessionResult[0], sessionResult[1]);
}
 
Example 4
Source Project: olat   File: GroupMgmtITCase.java    License: 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 5
Source Project: javabase   File: OldHttpClientApi.java    License: Apache License 2.0 6 votes vote down vote up
public void  get() throws UnsupportedEncodingException {
    HttpClient client = new HttpClient();
    String APIKEY = "4b441cb500f431adc6cc0cb650b4a5d0";
    String INFO =new URLCodec().encode("who are you","utf-8");
    String requesturl = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO;
    GetMethod getMethod = new GetMethod(requesturl);
    try {
        int stat = client.executeMethod(getMethod);
        if (stat != HttpStatus.SC_OK)
           log.error("get失败!");
        byte[] responseBody = getMethod.getResponseBody();
        String content=new String(responseBody ,"utf-8");
        log.info(content);
    }catch (Exception e){
       log.error(""+e.getLocalizedMessage());
    }finally {
        getMethod.releaseConnection();
    }
}
 
Example 6
Source Project: olat   File: CourseITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteCourses() throws IOException {
    final ICourse course = CoursesWebService.createEmptyCourse(admin, "courseToDel", "course to delete", null);
    DBFactory.getInstance().intermediateCommit();

    final HttpClient c = loginWithCookie("administrator", "olat");
    final DeleteMethod method = createDelete("/repo/courses/" + course.getResourceableId(), MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);

    final List<String> courseType = new ArrayList<String>();
    courseType.add(CourseModule.getCourseTypeName());
    final Roles roles = new Roles(true, true, true, true, false, true, false);
    final List<RepositoryEntry> repoEntries = RepositoryServiceImpl.getInstance().genericANDQueryWithRolesRestriction("*", "*", "*", courseType, roles, "");
    assertNotNull(repoEntries);

    for (final RepositoryEntry entry : repoEntries) {
        assertNotSame(entry.getOlatResource().getResourceableId(), course.getResourceableId());
    }
}
 
Example 7
/**
 * Test that blob upload requests are intercepted by the blob upload filter.
 *
 * @throws Exception
 */
public void testBlobUpload() throws Exception {
  String postData = "--==boundary\r\n" + "Content-Type: message/external-body; "
          + "charset=ISO-8859-1; blob-key=\"blobkey:blob-0\"\r\n" + "Content-Disposition: form-data; "
          + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n" + "Content-Type: image/jpeg\r\n"
          + "Content-Length: 1024\r\n" + "X-AppEngine-Upload-Creation: 2009-04-30 17:12:51.675929\r\n"
          + "Content-Disposition: form-data; " + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n"
          + "\r\n" + "--==boundary\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n"
          + "Content-Disposition: form-data; name=text1\r\n" + "Content-Length: 10\r\n" + "\r\n"
          + "Testing.\r\n" + "\r\n" + "\r\n" + "--==boundary--";

  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  PostMethod blobPost = new PostMethod(createUrl("/upload-blob").toString());
  blobPost.addRequestHeader("Content-Type", "multipart/form-data; boundary=\"==boundary\"");
  blobPost.addRequestHeader("X-AppEngine-BlobUpload", "true");
  blobPost.setRequestBody(postData);
  int httpCode = httpClient.executeMethod(blobPost);

  assertEquals(302, httpCode);
  Header redirUrl = blobPost.getResponseHeader("Location");
  assertEquals("http://" + getServerHost() + "/serve-blob?key=blobkey:blob-0",
          redirUrl.getValue());
}
 
Example 8
Source Project: olat   File: GroupMgmtITCase.java    License: 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 9
@Test(groups = "wso2.esb", description = "Testing functionality of FORCE_SC_ACCEPTED " +
                                         "Enabled True  - " +
                                         "Client should receive 202 message",
      dependsOnMethods = "testFORCE_SC_ACCEPTEDPropertyEnabledFalseScenario")
public void testWithFORCE_SC_ACCEPTEDPropertyEnabledTrueScenario() throws Exception {
    verifyProxyServiceExistence("FORCE_SC_ACCEPTED_TrueTestProxy");

    int responseStatus = 0;

    String strXMLFilename = FrameworkPathUtil.getSystemResourceLocation() + "artifacts"
                            + File.separator + "ESB" + File.separator + "mediatorconfig" +
                            File.separator + "property" + File.separator + "PlaceOrder.xml";

    File input = new File(strXMLFilename);
    PostMethod post = new PostMethod(getProxyServiceURLHttp("FORCE_SC_ACCEPTED_TrueTestProxy"));
    RequestEntity entity = new FileRequestEntity(input, "text/xml");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "placeOrder");

    HttpClient httpclient = new HttpClient();

    try {
        responseStatus = httpclient.executeMethod(post);
    } finally {
        post.releaseConnection();
    }

    assertEquals(responseStatus, 202, "Response status should be 202");
}
 
Example 10
Source Project: olat   File: AuthenticationITCase.java    License: 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 11
Source Project: cloudstack   File: HTTPUtils.java    License: 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(HttpClient httpClient, HttpMethod httpMethod) {
    // Execute GetMethod
    try {
        return httpClient.executeMethod(httpMethod);
    } catch (IOException e) {
        LOGGER.warn("Exception while executing HttpMethod " + httpMethod.getName() + " on URL " + httpMethod.getPath());
        return  -1;
    }
}
 
Example 12
Source Project: olat   File: UserMgmtITCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPortrait() throws IOException, URISyntaxException {
    final URL portraitUrl = RepositoryEntriesITCase.class.getResource("portrait.jpg");
    assertNotNull(portraitUrl);
    final File portrait = new File(portraitUrl.toURI());

    final HttpClient c = loginWithCookie("rest-one", "A6B7C8");

    // upload portrait
    final String request = "/users/" + id1.getKey() + "/portrait";
    final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
    method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
    final Part[] parts = { new FilePart("file", portrait), new StringPart("filename", "portrait.jpg") };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    method.releaseConnection();

    // check if big and small portraits exist
    final DisplayPortraitManager dps = DisplayPortraitManager.getInstance();
    final File uploadDir = dps.getPortraitDir(id1);
    assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_SMALL_FILENAME).exists());
    assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_BIG_FILENAME).exists());

    // check get portrait
    final String getRequest = "/users/" + id1.getKey() + "/portrait";
    final GetMethod getMethod = createGet(getRequest, MediaType.APPLICATION_OCTET_STREAM, true);
    final int getCode = c.executeMethod(getMethod);
    assertEquals(getCode, 200);
    final InputStream in = getMethod.getResponseBodyAsStream();
    int b = 0;
    int count = 0;
    while ((b = in.read()) > -1) {
        count++;
    }
    assertEquals(-1, b);// up to end of file
    assertTrue(count > 1000);// enough bytes
    method.releaseConnection();
}
 
Example 13
Source Project: olat   File: CourseSecurityITCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAdminCanEditCourse() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    // create an structure node
    final URI newStructureUri = getElementsUri(course).path("structure").build();
    final PutMethod method = createPut(newStructureUri, MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("position", "0"), new NameValuePair("shortTitle", "Structure-admin-0"),
            new NameValuePair("longTitle", "Structure-long-admin-0"), new NameValuePair("objectives", "Structure-objectives-admin-0") });
    final int code = c.executeMethod(method);
    assertEquals(200, code);
}
 
Example 14
Source Project: olat   File: OlatJerseyTestCase.java    License: 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());
}
 
Example 15
Source Project: olat   File: NotificationsITCase.java    License: 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 16
Source Project: olat   File: NotificationsITCase.java    License: 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 17
public void testAuth_TrustedRealIP() throws Exception {
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrlForHostIP("/admin/test-auth").toString());
  get.addRequestHeader(VmApiProxyEnvironment.REAL_IP_HEADER, "127.0.0.1");
  get.addRequestHeader(VmApiProxyEnvironment.EMAIL_HEADER, "[email protected]");
  get.addRequestHeader(VmApiProxyEnvironment.AUTH_DOMAIN_HEADER, "google.com");
  get.addRequestHeader(VmApiProxyEnvironment.IS_ADMIN_HEADER, "1");
  get.setFollowRedirects(false);
  int httpCode = httpClient.executeMethod(get);
  assertEquals(200, httpCode);
  assertEquals("[email protected]: [email protected]", get.getResponseBodyAsString());
}
 
Example 18
@Override
public boolean loadContentFromURL() {
	boolean returnValue = true;

	// return false;

	if ((type != TYPE_IMAGE) && (type != TYPE_ATTACHMENT)) {
		return false;
	}
	
	HttpClient httpClient = new HttpClient();
	String encodedURI = encodeURI(componentName);
	GetMethod get = new GetMethod(encodedURI);
	get.setFollowRedirects(true);
	
	try {
		NetworkUtil.setHttpClientProxyFromSystem(httpClient, encodedURI);
		
		httpClient.getParams().setParameter("http.connection.timeout", 5000);

		if (httpClient.executeMethod(get) == 200) {
			get.getResponseHeaders();
			
			// TODO: Due to data types of DB columns binblock and emmblock, replacing getResponseBody() cannot be replaced by safer getResponseBodyAsStream(). Better solutions?
			Header contentType = get.getResponseHeader("Content-Type");
			String contentTypeValue = "";
			if(contentType != null) {
				contentTypeValue = contentType.getValue();
			} else {
				logger.debug("No content-type in response from: " + encodedURI);
			}
			setBinaryBlock(get.getResponseBody(), contentTypeValue);
		}
	} catch (Exception e) {
		logger.error("loadContentFromURL: " + encodedURI, e);
		returnValue = false;
	} finally {
		get.releaseConnection();
	}
	
	if( logger.isInfoEnabled()) {
		logger.info("loadContentFromURL: loaded " + componentName);
	}
	
	return returnValue;
}
 
Example 19
Source Project: olat   File: MSNPropertyHandler.java    License: Apache License 2.0 4 votes vote down vote up
/**
*/
  @SuppressWarnings({ "unchecked" })
  @Override
  public boolean isValid(final FormItem formItem, final Map formContext) {
      boolean result;
      final TextElement textElement = (TextElement) formItem;

      if (StringHelper.containsNonWhitespace(textElement.getValue())) {

          // Use an HttpClient to fetch a profile information page from MSN.
          final HttpClient httpClient = HttpClientFactory.getHttpClientInstance();
          final HttpClientParams httpClientParams = httpClient.getParams();
          httpClientParams.setConnectionManagerTimeout(2500);
          httpClient.setParams(httpClientParams);
          final HttpMethod httpMethod = new GetMethod(MSN_NAME_VALIDATION_URL);
          final NameValuePair idParam = new NameValuePair(MSN_NAME_URL_PARAMETER, textElement.getValue());
          httpMethod.setQueryString(new NameValuePair[] { idParam });
          // Don't allow redirects since otherwise, we won't be able to get the correct status
          httpMethod.setFollowRedirects(false);
          try {
              // Get the user profile page
              httpClient.executeMethod(httpMethod);
              final int httpStatusCode = httpMethod.getStatusCode();
              // Looking at the HTTP status code tells us whether a user with the given MSN name exists.
              if (httpStatusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
                  // If the user exists, we get a 301...
                  result = true;
              } else if (httpStatusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                  // ...and if the user doesn't exist, MSN sends a 500.
                  textElement.setErrorKey("form.name.msn.error", null);
                  result = false;
              } else {
                  // For HTTP status codes other than 301 and 500 we will assume that the given MSN name is valid, but inform the user about this.
                  textElement.setExampleKey("form.example.msnname.notvalidated", null);
                  log.warn("MSN name validation: Expected HTTP status 301 or 500, but got " + httpStatusCode);
                  result = true;
              }
          } catch (final Exception e) {
              // In case of any exception, assume that the given MSN name is valid (The opposite would block easily upon network problems), and inform the user about
              // this.
              textElement.setExampleKey("form.example.msnname.notvalidated", null);
              log.warn("MSN name validation: Exception: " + e.getMessage());
              result = true;
          }
      } else {
          result = true;
      }
      return result;
  }
 
Example 20
Source Project: olat   File: TunnelComponent.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @param tuReq
 * @param client
 * @return HttpMethod
 */
public HttpMethod fetch(final TURequest tuReq, final HttpClient client) {

    final String modulePath = tuReq.getUri();

    HttpMethod meth = null;
    final String method = tuReq.getMethod();
    if (method.equals("GET")) {
        final GetMethod cmeth = new GetMethod(modulePath);
        final String queryString = tuReq.getQueryString();
        if (queryString != null) {
            cmeth.setQueryString(queryString);
        }
        meth = cmeth;
        if (meth == null) {
            return null;
        }
        // if response is a redirect, follow it
        meth.setFollowRedirects(true);

    } else if (method.equals("POST")) {
        final String type = tuReq.getContentType();
        if (type == null || type.equals("application/x-www-form-urlencoded")) {
            // regular post, no file upload
        }

        final PostMethod pmeth = new PostMethod(modulePath);
        final Set postKeys = tuReq.getParameterMap().keySet();
        for (final Iterator iter = postKeys.iterator(); iter.hasNext();) {
            final String key = (String) iter.next();
            final String vals[] = (String[]) tuReq.getParameterMap().get(key);
            for (int i = 0; i < vals.length; i++) {
                pmeth.addParameter(key, vals[i]);
            }
            meth = pmeth;
        }
        if (meth == null) {
            return null;
            // Redirects are not supported when using POST method!
            // See RFC 2616, section 10.3.3, page 62
        }
    }

    // Add olat specific headers to the request, can be used by external
    // applications to identify user and to get other params
    // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py
    meth.addRequestHeader("X-OLAT-USERNAME", tuReq.getUserName());
    meth.addRequestHeader("X-OLAT-LASTNAME", tuReq.getLastName());
    meth.addRequestHeader("X-OLAT-FIRSTNAME", tuReq.getFirstName());
    meth.addRequestHeader("X-OLAT-EMAIL", tuReq.getEmail());

    try {
        client.executeMethod(meth);
        return meth;
    } catch (final Exception e) {
        meth.releaseConnection();
    }
    return null;
}