Java Code Examples for org.apache.commons.httpclient.methods.GetMethod

The following examples show how to use org.apache.commons.httpclient.methods.GetMethod. 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: otroslogviewer   Author: otros-systems   File: JumpToCodeClient.java    License: Apache License 2.0 6 votes vote down vote up
private HttpMethod buildMethod(String url, LocationInfo locationInfo, HttpOperation httpOperation) {
  HttpMethod method = new GetMethod(url);
  ArrayList<NameValuePair> list = new ArrayList<>(5);
  list.add(new NameValuePair("o", httpOperation.getOperation()));

  locationInfo.getPackageName().ifPresent(p -> list.add(new NameValuePair("p", p)));
  locationInfo.getClassName().ifPresent(p -> list.add(new NameValuePair("c", p)));
  locationInfo.getFileName().ifPresent(p -> list.add(new NameValuePair("f", p)));
  locationInfo.getMessage().ifPresent(m -> list.add(new NameValuePair("m", m)));
  locationInfo.getLineNumber().map(i -> Integer.toString(i)).ifPresent(l -> list.add(new NameValuePair("l", l)));


  NameValuePair[] pair = list.toArray(new NameValuePair[0]);

  method.setQueryString(pair);
  return method;
}
 
Example #2
Source Project: document-management-system   Author: openkm   File: MailUtils.java    License: 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 #3
Source Project: submarine   Author: apache   File: SubmarineServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
// SUBMARINE-422. Fix refreshing page returns 404 error
public void testRefreshingURL() throws IOException {
  ArrayList<String> arrUrls = new ArrayList();
  arrUrls.add("/user/login");
  arrUrls.add("/workbench/manager/user");

  for (int i = 0; i < arrUrls.size(); i++) {
    GetMethod response = httpGet(arrUrls.get(i));
    LOG.info(response.toString());

    String requestBody = response.getResponseBodyAsString();
    LOG.info(requestBody);
    assertFalse(requestBody.contains("Error 404 Not Found"));
  }
}
 
Example #4
Source Project: OfficeAutomatic-System   Author: BerserkerHercules   File: HttpUtil.java    License: 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 #5
Source Project: openemm   Author: agnitas-org   File: NetworkUtil.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public static byte[] loadUrlData(String url) throws Exception {
	HttpClient httpClient = new HttpClient();
	setHttpClientProxyFromSystem(httpClient, url);
	GetMethod get = new GetMethod(url);		
	get.setFollowRedirects(true);
	
	try {			
		httpClient.getParams().setParameter("http.connection.timeout", 5000);
		int httpReturnCode = httpClient.executeMethod(get); 

		if (httpReturnCode == 200) {
			// Don't use get.getResponseBody, it causes a warning in log
			try (InputStream inputStream = get.getResponseBodyAsStream()) {
				return IOUtils.toByteArray(inputStream);
			}
		} else {
			throw new Exception("ERROR: Received httpreturncode " + httpReturnCode);
		}
	} finally {
		get.releaseConnection();
	}
}
 
Example #6
Source Project: olat   Author: huihoo   File: CourseGroupMgmtITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCourseGroups() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final String request = "/repo/courses/" + course.getResourceableId() + "/groups";
    final GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(200, code);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<GroupVO> vos = parseGroupArray(body);
    assertNotNull(vos);
    assertEquals(2, vos.size());// g1 and g2
    assertTrue(vos.get(0).getKey().equals(g1.getKey()) || vos.get(0).getKey().equals(g2.getKey()));
    assertTrue(vos.get(1).getKey().equals(g1.getKey()) || vos.get(1).getKey().equals(g2.getKey()));
}
 
Example #7
Source Project: yeti   Author: sensepost   File: NetworkTools.java    License: 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 #8
Source Project: MyVirtualDirectory   Author: TremoloSecurity   File: GetSSLCert.java    License: Apache License 2.0 6 votes vote down vote up
public static javax.security.cert.X509Certificate getCert(String host, int port) {
	GetCertSSLProtocolSocketFactory certFactory = new GetCertSSLProtocolSocketFactory();
	Protocol myhttps = new Protocol("https", certFactory, port);
	HttpClient httpclient = new HttpClient();
	httpclient.getHostConfiguration().setHost(host, port, myhttps);
	GetMethod httpget = new GetMethod("/");
	try {
	  httpclient.executeMethod(httpget);
	  //System.out.println(httpget.getStatusLine());
	} catch (Throwable t) {
		//do nothing
	}
	
	finally {
	  httpget.releaseConnection();
	}
	
	return certFactory.getCertificate();
}
 
Example #9
Source Project: boost   Author: MicroShed   File: EndpointIT.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testServlet() throws Exception {
    HttpClient client = new HttpClient();

    GetMethod method = new GetMethod(URL + "/hello");

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

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

        String response = method.getResponseBodyAsString(10000);

        assertTrue("Unexpected response body",
                response.contains("Hello World From Your Friends at Liberty Boost EE!"));
    } finally {
        method.releaseConnection();
    }
}
 
Example #10
Source Project: zeppelin   Author: apache   File: HeliumRestApiTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testVisualizationPackageOrder() throws IOException {
  GetMethod get1 = httpGet("/helium/order/visualization");
  assertThat(get1, isAllowed());
  Map<String, Object> resp1 = gson.fromJson(get1.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() { }.getType());
  List<Object> body1 = (List<Object>) resp1.get("body");
  assertEquals(body1.size(), 0);

  //We assume allPackages list has been refreshed before sorting
  helium.getAllPackageInfo();

  String postRequestJson = "[name2, name1]";
  PostMethod post = httpPost("/helium/order/visualization", postRequestJson);
  assertThat(post, isAllowed());
  post.releaseConnection();

  GetMethod get2 = httpGet("/helium/order/visualization");
  assertThat(get2, isAllowed());
  Map<String, Object> resp2 = gson.fromJson(get2.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() { }.getType());
  List<Object> body2 = (List<Object>) resp2.get("body");
  assertEquals(body2.size(), 2);
  assertEquals(body2.get(0), "name2");
  assertEquals(body2.get(1), "name1");
}
 
Example #11
Source Project: zeppelin   Author: apache   File: AbstractTestRestApi.java    License: Apache License 2.0 6 votes vote down vote up
protected static boolean checkIfServerIsRunning() {
  GetMethod request = null;
  boolean isRunning;
  try {
    request = httpGet("/version");
    isRunning = request.getStatusCode() == 200;
  } catch (IOException e) {
    LOG.error("AbstractTestRestApi.checkIfServerIsRunning() fails .. ZeppelinServer is not " +
            "running");
    isRunning = false;
  } finally {
    if (request != null) {
      request.releaseConnection();
    }
  }
  return isRunning;
}
 
Example #12
Source Project: swellrt   Author: SwellRT   File: SolrSearchProviderImpl.java    License: Apache License 2.0 6 votes vote down vote up
private JsonArray sendSearchRequest(String solrQuery,
    Function<InputStreamReader, JsonArray> function) throws IOException {
  JsonArray docsJson;
  GetMethod getMethod = new GetMethod();
  HttpClient httpClient = new HttpClient();
  try {
    getMethod.setURI(new URI(solrQuery, false));
    int statusCode = httpClient.executeMethod(getMethod);
    docsJson = function.apply(new InputStreamReader(getMethod.getResponseBodyAsStream()));
    if (statusCode != HttpStatus.SC_OK) {
      LOG.warning("Failed to execute query: " + solrQuery);
      throw new IOException("Search request status is not OK: " + statusCode);
    }
  } finally {
    getMethod.releaseConnection();
  }
  return docsJson;
}
 
Example #13
Source Project: development   Author: servicecatalog   File: PortFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the content under the given URL with username and passwort
 * authentication.
 * 
 * @param url
 * @param username
 * @param password
 * @return
 * @throws IOException
 */
private static byte[] getUrlContent(URL url, String username,
        String password) throws IOException {
    final HttpClient client = new HttpClient();

    // Set credentials:
    client.getParams().setAuthenticationPreemptive(true);
    final Credentials credentials = new UsernamePasswordCredentials(
            username, password);
    client.getState()
            .setCredentials(
                    new AuthScope(url.getHost(), url.getPort(),
                            AuthScope.ANY_REALM), credentials);

    // Retrieve content:
    final GetMethod method = new GetMethod(url.toString());
    final int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        throw new IOException("Error " + status + " while retrieving "
                + url);
    }
    return method.getResponseBody();
}
 
Example #14
Source Project: zeppelin   Author: apache   File: DirAccessTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDirAccessOk() throws Exception {
  synchronized (this) {
    try {
      System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_SERVER_DEFAULT_DIR_ALLOWED
              .getVarName(), "true");
      AbstractTestRestApi.startUp(DirAccessTest.class.getSimpleName());
      HttpClient httpClient = new HttpClient();
      GetMethod getMethod = new GetMethod(getUrlToTest() + "/app/");
      LOG.info("Invoke getMethod");
      httpClient.executeMethod(getMethod);
      assertEquals(getMethod.getResponseBodyAsString(),
              HttpStatus.SC_OK, getMethod.getStatusCode());
    } finally {
      AbstractTestRestApi.shutDown();
    }
  }
}
 
Example #15
Source Project: olat   Author: huihoo   File: UserMgmtITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFindUsersByLogin() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("login", "administrator"), new NameValuePair("authProvider", "OLAT") });
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<UserVO> vos = parseUserArray(body);
    final String[] authProviders = new String[] { "OLAT" };
    final List<Identity> identities = securityManager.getIdentitiesByPowerSearch("administrator", null, true, null, null, authProviders, null, null, null, null,
            Identity.STATUS_VISIBLE_LIMIT);

    assertNotNull(vos);
    assertFalse(vos.isEmpty());
    assertEquals(vos.size(), identities.size());
    boolean onlyLikeAdmin = true;
    for (final UserVO vo : vos) {
        if (!vo.getLogin().startsWith("administrator")) {
            onlyLikeAdmin = false;
        }
    }
    assertTrue(onlyLikeAdmin);
}
 
Example #16
Source Project: olat   Author: huihoo   File: GroupMgmtITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetGroupInfos() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final String request = "/groups/" + g1.getKey() + "/infos";
    final GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final GroupInfoVO vo = parse(body, GroupInfoVO.class);
    assertNotNull(vo);
    assertEquals(Boolean.TRUE, vo.getHasWiki());
    assertEquals("<p>Hello world</p>", vo.getNews());
    assertNotNull(vo.getForumKey());
}
 
Example #17
Source Project: cloudstack   Author: apache   File: UriUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static InputStream getInputStreamFromUrl(String url, String user, String password) {

        try {
            Pair<String, Integer> hostAndPort = validateUrl(url);
            HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
            if ((user != null) && (password != null)) {
                httpclient.getParams().setAuthenticationPreemptive(true);
                Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
                httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
                s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
            }
            // Execute the method.
            GetMethod method = new GetMethod(url);
            int statusCode = httpclient.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                s_logger.error("Failed to read from URL: " + url);
                return null;
            }

            return method.getResponseBodyAsStream();
        } catch (Exception ex) {
            s_logger.error("Failed to read from URL: " + url);
            return null;
        }
    }
 
Example #18
Source Project: neoscada   Author: eclipse   File: HdHttpClient.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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 ();
    }
}
 
Example #19
Source Project: cloudstack   Author: apache   File: User.java    License: Apache License 2.0 6 votes vote down vote up
public void launchUser() throws IOException {
    String encodedUsername = URLEncoder.encode(this.getUserName(), "UTF-8");
    this.encryptedPassword = TestClientWithAPI.createMD5Password(this.getPassword());
    String encodedPassword = URLEncoder.encode(this.encryptedPassword, "UTF-8");
    String url =
        this.server + "?command=createUser&username=" + encodedUsername + "&password=" + encodedPassword +
            "&firstname=Test&lastname=Test&[email protected]&domainId=1";
    String userIdStr = 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> userIdValues = TestClientWithAPI.getSingleValueFromXML(is, new String[] {"id"});
        userIdStr = userIdValues.get("id");
        if ((userIdStr != null) && (Long.parseLong(userIdStr) != -1)) {
            this.setUserId(userIdStr);
        }
    }
}
 
Example #20
Source Project: h2o-2   Author: h2oai   File: WebAPI.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Exports a model to a JSON file.
 */
static void exportModel() throws Exception {
  HttpClient client = new HttpClient();
  GetMethod get = new GetMethod(URL + "/2/ExportModel.json?model=MyInitialNeuralNet");
  int status = client.executeMethod(get);
  if( status != 200 )
    throw new Exception(get.getStatusText());
  JsonObject response = (JsonObject) new JsonParser().parse(new InputStreamReader(get.getResponseBodyAsStream()));
  JsonElement model = response.get("model");
  JsonWriter writer = new JsonWriter(new FileWriter(JSON_FILE));
  writer.setLenient(true);
  writer.setIndent("  ");
  Streams.write(model, writer);
  writer.close();
  get.releaseConnection();
}
 
Example #21
Source Project: zeppelin   Author: apache   File: HeliumRestApiTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEnableDisablePackage() throws IOException {
  String packageName = "name1";
  PostMethod post1 = httpPost("/helium/enable/" + packageName, "");
  assertThat(post1, isAllowed());
  post1.releaseConnection();

  GetMethod get1 = httpGet("/helium/package/" + packageName);
  Map<String, Object> resp1 = gson.fromJson(get1.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() { }.getType());
  List<StringMap<Object>> body1 = (List<StringMap<Object>>) resp1.get("body");
  assertEquals(body1.get(0).get("enabled"), true);

  PostMethod post2 = httpPost("/helium/disable/" + packageName, "");
  assertThat(post2, isAllowed());
  post2.releaseConnection();

  GetMethod get2 = httpGet("/helium/package/" + packageName);
  Map<String, Object> resp2 = gson.fromJson(get2.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() { }.getType());
  List<StringMap<Object>> body2 = (List<StringMap<Object>>) resp2.get("body");
  assertEquals(body2.get(0).get("enabled"), false);
}
 
Example #22
Source Project: orion.server   Author: eclipse   File: GetRouteByGuidCommand.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public ServerStatus _doIt() {
	try {
		URI targetURI = URIUtil.toURI(getCloud().getUrl());

		// Get the app
		URI appsURI = targetURI.resolve("/v2/routes/" + routeGuid);
		GetMethod getRoutesMethod = new GetMethod(appsURI.toString());
		ServerStatus confStatus = HttpUtil.configureHttpMethod(getRoutesMethod, getCloud());
		if (!confStatus.isOK())
			return confStatus;

		ServerStatus getStatus = HttpUtil.executeMethod(getRoutesMethod);
		if (!getStatus.isOK())
			return getStatus;

		JSONObject routeJSON = getStatus.getJsonData();
		this.route = new Route().setCFJSON(routeJSON);

		return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, this.route.toJSON());
	} catch (Exception e) {
		String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
		logger.error(msg, e);
		return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
	}
}
 
Example #23
Source Project: cloudstack   Author: apache   File: StressTestDirectAttach.java    License: 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 #24
Source Project: samza   Author: apache   File: YarnRestJobStatusProvider.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Issues a HTTP Get request to the provided url and returns the response
 * @param requestUrl the request url
 * @return the response
 * @throws IOException if there are problems with the http get request.
 */
byte[] httpGet(String requestUrl)
    throws IOException {
  GetMethod getMethod = new GetMethod(requestUrl);
  try {
    int responseCode = this.httpClient.executeMethod(getMethod);
    LOGGER.debug("Received response code: {} for the get request on the url: {}", responseCode, requestUrl);
    byte[] response = getMethod.getResponseBody();
    if (responseCode != HttpStatus.SC_OK) {
      throw new SamzaException(
          String.format("Received response code: %s for get request on: %s, with message: %s.", responseCode,
              requestUrl, StringUtils.newStringUtf8(response)));
    }
    return response;
  } finally {
    getMethod.releaseConnection();
  }
}
 
Example #25
Source Project: olat   Author: huihoo   File: CoursesResourcesFoldersITCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFilesDeeper() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final URI uri = UriBuilder.fromUri(getCourseFolderURI()).path("SubDir").path("SubSubDir").path("SubSubSubDir").build();
    final GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);

    final String body = method.getResponseBodyAsString();
    final List<LinkVO> links = parseLinkArray(body);
    assertNotNull(links);
    assertEquals(1, links.size());
    assertEquals("3_singlepage.html", links.get(0).getTitle());
}
 
Example #26
Source Project: olat   Author: huihoo   File: AuthenticationITCase.java    License: 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 #27
Source Project: olat   Author: huihoo   File: MorphologicalServiceDEImpl.java    License: Apache License 2.0 5 votes vote down vote up
private InputStream retreiveXMLReply(String partOfSpeech, String word) {
    HttpClient client = HttpClientFactory.getHttpClientInstance();
    HttpMethod method = new GetMethod(MORPHOLOGICAL_SERVICE_ADRESS);
    NameValuePair posValues = new NameValuePair(PART_OF_SPEECH_PARAM, partOfSpeech);
    NameValuePair wordValues = new NameValuePair(GLOSS_TERM_PARAM, word);
    if (log.isDebugEnabled()) {
        String url = MORPHOLOGICAL_SERVICE_ADRESS + "?" + PART_OF_SPEECH_PARAM + "=" + partOfSpeech + "&" + GLOSS_TERM_PARAM + "=" + word;
        log.debug("Send GET request to morph-service with URL: " + url);
    }
    method.setQueryString(new NameValuePair[] { posValues, 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());
        } else {
            log.error("Unexpected HTTP Status::" + method.getStatusLine().toString());
        }
    } 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!");
    }
    HttpRequestMediaResource mr = new HttpRequestMediaResource(method);
    InputStream inputStream = mr.getInputStream();

    return inputStream;
}
 
Example #28
Source Project: zeppelin   Author: apache   File: ZeppelinRestApiTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetParagraph() throws IOException {
  Note note = null;
  try {
    note = TestUtils.getInstance(Notebook.class).createNote("note1_testGetParagraph", anonymous);

    Paragraph p = note.addNewParagraph(AuthenticationInfo.ANONYMOUS);
    p.setTitle("hello");
    p.setText("world");
    TestUtils.getInstance(Notebook.class).saveNote(note, anonymous);

    GetMethod get = httpGet("/notebook/" + note.getId() + "/paragraph/" + p.getId());
    LOG.info("testGetParagraph response\n" + get.getResponseBodyAsString());
    assertThat("Test get method: ", get, isAllowed());
    get.releaseConnection();

    Map<String, Object> resp = gson.fromJson(get.getResponseBodyAsString(),
            new TypeToken<Map<String, Object>>() {}.getType());

    assertNotNull(resp);
    assertEquals("OK", resp.get("status"));

    Map<String, Object> body = (Map<String, Object>) resp.get("body");

    assertEquals(p.getId(), body.get("id"));
    assertEquals("hello", body.get("title"));
    assertEquals("world", body.get("text"));
  } finally {
    //cleanup
    if (null != note) {
      TestUtils.getInstance(Notebook.class).removeNote(note, anonymous);
    }
  }
}
 
Example #29
Source Project: appengine-java-vm-runtime   Author: GoogleCloudPlatform   File: VmRuntimeJettySessionTest.java    License: Apache License 2.0 5 votes vote down vote up
public void LUDOTODOtestWithInvalidInboundIp() throws Exception {
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrlForHostIP("/test-ssl").toString());
  int httpCode = httpClient.executeMethod(get);
  assertEquals(403, httpCode);
}
 
Example #30
Source Project: rome   Author: rometools   File: ClientMediaEntry.java    License: Apache License 2.0 5 votes vote down vote up
private InputStream getResourceAsStream() throws ProponoException {
    if (getEditURI() == null) {
        throw new ProponoException("ERROR: not yet saved to server");
    }
    final GetMethod method = new GetMethod(((Content) getContents()).getSrc());
    try {
        getCollection().getHttpClient().executeMethod(method);
        if (method.getStatusCode() != 200) {
            throw new ProponoException("ERROR HTTP status=" + method.getStatusCode());
        }
        return method.getResponseBodyAsStream();
    } catch (final IOException e) {
        throw new ProponoException("ERROR: getting media entry", e);
    }
}