Java Code Examples for com.sun.jersey.api.client.WebResource#get()

The following examples show how to use com.sun.jersey.api.client.WebResource#get() . 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: ProtocolTest.java    From jerseyoauth2 with MIT License 6 votes vote down vote up
@Test
public void testAuthUrl()
{
	String code = authClient.authorizeClient(clientEntity, "test1 test2").getCode();
	assertNotNull(code);
	restClient.setFollowRedirects(false);
	
	ResourceClient client = new ResourceClient(clientEntity);
	String authUrl = client.getAuthUrl(null);
	
	WebResource webResource = restClient.resource(authUrl);
	ClientResponse clientResponse = webResource.get(ClientResponse.class);
	assertEquals(302, clientResponse.getStatus());
	assertTrue(clientResponse.getLocation().toString().startsWith("http://localhost:9998/testsuite?code="));
	
	authUrl = client.getAuthUrl("stateTest");
	
	webResource = restClient.resource(authUrl);
	clientResponse = webResource.get(ClientResponse.class);
	assertEquals(302, clientResponse.getStatus());
	assertTrue(clientResponse.getLocation().toString().contains("state=stateTest"));		
}
 
Example 2
Source File: BaseSearcher.java    From q with Apache License 2.0 6 votes vote down vote up
public Set<String> getResults(String q, List<String> languages, String dataSetId) throws Throwable
{
	String urlForGettingDoc = getUrlForGettingDoc(q, languages, dataSetId);

	if (Properties.isPrintUrl.get())
		logger.info(urlForGettingDoc);

	String jsonString = getJsonForQuery(q, languages, dataSetId);

	WebResource webResource = client.resource(urlForGettingDoc);
	ClientResponse response = null;

	if (jsonString != null)
		response = webResource.type("application/json").post(ClientResponse.class, jsonString);
	else
		response = webResource.get(ClientResponse.class);
	if (response == null || (response.getStatus() != 201 && response.getStatus() != 200))
		throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
	String output = response.getEntity(String.class);
	Set<String> results = getResultsFromServerResponse(output);
	return results;
}
 
Example 3
Source File: RepositoryCleanupUtil.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Use REST API to authenticate provided credentials
 * 
 * @throws Exception
 */
@VisibleForTesting
void authenticateLoginCredentials() throws Exception {
  KettleClientEnvironment.init();

  if ( client == null ) {
    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
    client = Client.create( clientConfig );
    client.addFilter( new HTTPBasicAuthFilter( username, Encr.decryptPasswordOptionallyEncrypted( password ) ) );
  }

  WebResource resource = client.resource( url + AUTHENTICATION + AdministerSecurityAction.NAME );
  String response = resource.get( String.class );

  if ( !response.equals( "true" ) ) {
    throw new Exception( Messages.getInstance().getString( "REPOSITORY_CLEANUP_UTIL.ERROR_0012.ACCESS_DENIED" ) );
  }
}
 
Example 4
Source File: ImplicitGrantTest.java    From jerseyoauth2 with MIT License 6 votes vote down vote up
@Test
public void testAccessToken()
{
	String code = authClient.authorizeClient(clientEntity, "test1 test2").getCode();
	assertNotNull(code);
	restClient.setFollowRedirects(false);
	
	ResourceClient client = new ResourceClient(clientEntity.getClientId(), GrantType.AUTHORIZATION_REQUEST, ResponseType.TOKEN);
	String authUrl = client.getAuthUrl(null);
	
	WebResource webResource = restClient.resource(authUrl);
	ClientResponse clientResponse = webResource.get(ClientResponse.class);
	assertEquals(302, clientResponse.getStatus());
	String fragment = clientResponse.getLocation().getFragment();
	assertNotNull(fragment);
}
 
Example 5
Source File: BekwamDotNetDAO.java    From examples-javafx-repos1 with Apache License 2.0 6 votes vote down vote up
public PreferredColleges findPreferredColleges() {

        if( logger.isDebugEnabled() ) {
            logger.debug("[FIND]");
        }

        Client client = new Client();
        WebResource webResource = client.resource("http://www.bekwam.net/data/colleges.json");
        String json = webResource.get(String.class);
        PreferredColleges retval = new Gson().fromJson(json, PreferredColleges.class);

        if( logger.isDebugEnabled() ) {
            logger.debug("[FIND] json=" + retval);
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException ignore) {}

        return retval;
    }
 
Example 6
Source File: OracleStorageService.java    From front50 with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Long> listObjectKeys(ObjectType objectType) {
  WebResource wr =
      client.resource(
          UriBuilder.fromPath(endpoint + "/n/{arg1}/b/{arg2}/o")
              .queryParam("prefix", objectType.group)
              .queryParam("fields", "name,timeCreated")
              .build(region, namespace, bucketName));
  wr.accept(MediaType.APPLICATION_JSON_TYPE);
  ListObjects listObjects = wr.get(ListObjects.class);
  Map<String, Long> results = new HashMap<>();
  for (ObjectSummary summary : listObjects.getObjects()) {
    if (summary.getName().endsWith(objectType.defaultMetadataFilename)) {
      results.put(
          buildObjectKey(objectType, summary.getName()), summary.getTimeCreated().getTime());
    }
  }
  return results;
}
 
Example 7
Source File: OracleStorageService.java    From front50 with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Timestamped> T loadObject(ObjectType objectType, String objectKey)
    throws NotFoundException {
  WebResource wr =
      client.resource(
          UriBuilder.fromPath(endpoint + "/n/{arg1}/b/{arg2}/o/{arg3}")
              .build(
                  region,
                  namespace,
                  bucketName,
                  buildOSSKey(objectType.group, objectKey, objectType.defaultMetadataFilename)));
  wr.accept(MediaType.APPLICATION_JSON_TYPE);
  try {
    T obj = (T) wr.get(objectType.clazz);
    return obj;
  } catch (UniformInterfaceException e) {
    if (e.getResponse().getStatus() == 404) {
      throw new NotFoundException("Object not found (key: " + objectKey + ")");
    }
    throw e;
  }
}
 
Example 8
Source File: Carte.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that Carte is running and if so, shuts down the Carte server
 *
 * @param hostname
 * @param port
 * @param username
 * @param password
 * @throws ParseException
 * @throws CarteCommandException
 */
@VisibleForTesting
static void callStopCarteRestService( String hostname, String port, String username, String password )
  throws ParseException, CarteCommandException {
  // get information about the remote connection
  try {
    KettleClientEnvironment.init();

    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
    Client client = Client.create( clientConfig );

    client.addFilter( new HTTPBasicAuthFilter( username, Encr.decryptPasswordOptionallyEncrypted( password ) ) );

    // check if the user can access the carte server. Don't really need this call but may want to check it's output at
    // some point
    String contextURL = "http://" + hostname + ":" + port + "/kettle";
    WebResource resource = client.resource( contextURL + "/status/?xml=Y" );
    String response = resource.get( String.class );
    if ( response == null || !response.contains( "<serverstatus>" ) ) {
      throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.NoServerFound", hostname, ""
          + port ) );
    }

    // This is the call that matters
    resource = client.resource( contextURL + "/stopCarte" );
    response = resource.get( String.class );
    if ( response == null || !response.contains( "Shutting Down" ) ) {
      throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.NoShutdown", hostname, ""
          + port ) );
    }
  } catch ( Exception e ) {
    throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.NoServerFound", hostname, ""
        + port ), e );
  }
}
 
Example 9
Source File: ProtocolTest.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
@Test
public void testInvalidScopes()
{
	String code = authClient.authorizeClient(clientEntity, "test1 someScope").getCode();
	assertNotNull(code);
	restClient.setFollowRedirects(false);
	
	ResourceClient client = new ResourceClient(clientEntity.getClientId(), clientEntity.getClientSecret(), "test1 test2");
	String authUrl = client.getAuthUrl(null);
	
	WebResource webResource = restClient.resource(authUrl);
	ClientResponse clientResponse = webResource.get(ClientResponse.class);
	assertEquals(302, clientResponse.getStatus());
	assertTrue(clientResponse.getLocation().toString().startsWith("http://localhost:9998/testsuite?code="));
}
 
Example 10
Source File: ImplicitGrantTest.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
@Test
public void testAuthCodeWithImplicit() throws ClientException
{
	String code = authClient.authorizeClient(clientEntity, "test1 test2").getCode();
	assertNotNull(code);
	restClient.setFollowRedirects(false);
	
	ResourceClient client = new ResourceClient(clientEntity.getClientId(), GrantType.AUTHORIZATION_REQUEST, ResponseType.CODE);
	String authUrl = client.getAuthUrl(null);
	
	WebResource webResource = restClient.resource(authUrl);
	ClientResponse clientResponse = webResource.get(ClientResponse.class);
	assertTrue(clientResponse.getLocation().toString().startsWith("http://localhost:9998/testsuite?error=unsupported_response_type"));
}
 
Example 11
Source File: OccurrenceWsClientIT.java    From occurrence with Apache License 2.0 5 votes vote down vote up
/**
 * The Annosys methods are implemented specifically to support Annosys and are not advertised or
 * documented in the public API. <em>They may be removed at any time without notice</em>.
 */
@Test
public void testAnnosysVerbatimXml() {
  Client client = Client.create();
  WebResource webResource = client.resource(wsBaseUrl).path(OccurrencePaths.OCCURRENCE_PATH)
          .path(OccurrenceResource.ANNOSYS_PATH).path("10").path(OccurrencePaths.VERBATIM_PATH);

  ClientResponse response = webResource.get(ClientResponse.class);
  assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
  assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
  assertTrue(response.getLength() > 0);
  client.destroy();
}
 
Example 12
Source File: OracleStorageService.java    From front50 with Apache License 2.0 5 votes vote down vote up
@Override
public long getLastModified(ObjectType objectType) {
  WebResource wr =
      client.resource(
          UriBuilder.fromPath(endpoint + "/n/{arg1}/b/{arg2}/o/{arg3}")
              .build(region, namespace, bucketName, objectType.group + "/last-modified.json"));
  wr.accept(MediaType.APPLICATION_JSON_TYPE);
  try {
    LastModified lastModified = wr.get(LastModified.class);
    return lastModified.getLastModified();
  } catch (Exception e) {
    return 0L;
  }
}
 
Example 13
Source File: CubeWsClient.java    From occurrence with Apache License 2.0 5 votes vote down vote up
@Override
public long get(ReadBuilder addressBuilder) throws IllegalArgumentException {
  Preconditions.checkNotNull(addressBuilder, "The cube address is mandatory");
  MultivaluedMap<String, String> params = new MultivaluedMapImpl();
  for (Entry<Dimension<?>, String> d : addressBuilder.build().entrySet()) {
    params.putSingle(d.getKey().getKey(), d.getValue());
  }
  WebResource res = getResource(OCCURRENCE_COUNT_PATH).queryParams(params);
  return res.get(Long.class);
}
 
Example 14
Source File: AuthenticationTool.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
private JSONObject getCloudInfo(String ccEndpoint) throws ServletException, IOException{
    String infoUrl = ccEndpoint + "/v2/info";
    Client restClient = RestUtil.getHTTPSRestClient();  

    WebResource infoResource = restClient.resource(infoUrl);
    logger.debug("infoUrl: " + infoUrl);
    ClientResponse infoResponse = infoResource.get(ClientResponse.class);

    if(infoResponse.getStatus() == 200){
        return new JSONObject(infoResponse.getEntity(String.class));
    } else {
        throw new ServletException("Can not get the oauth information from " + infoUrl + ", code: " + infoResponse.getStatus());
    }
}
 
Example 15
Source File: CachingTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
private ClientResponse getCountryAndCity(String country, String city, String apiKey) {
    String uri = format("/explicit/country/%s/city/%s", country, city);
    WebResource resource = _resourceTestRule.client().resource(uri);
    if (apiKey != null) {
        return resource.header(ApiKeyRequest.AUTHENTICATION_HEADER, apiKey).get(ClientResponse.class);
    }
    return resource.get(ClientResponse.class);
}
 
Example 16
Source File: ResourcePermissionsTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
private ClientResponse getCountryAndCity(PermissionCheck permissionCheck, String country, String city, String apiKey)
        throws Exception {
    String uri = format(_uriFormatMap.get(permissionCheck), URLEncoder.encode(country, "UTF-8"), URLEncoder.encode(city, "UTF-8"));
    WebResource resource = _resourceTestRule.client().resource(uri);
    if (apiKey != null) {
        return resource.header(ApiKeyRequest.AUTHENTICATION_HEADER, apiKey).get(ClientResponse.class);
    }
    return resource.get(ClientResponse.class);
}
 
Example 17
Source File: BaseIndexer.java    From q with Apache License 2.0 5 votes vote down vote up
void commit()
{
	WebResource webResource = client.resource(getUrlForCommitting());
	ClientResponse response = webResource.get(ClientResponse.class);
	if (response == null || (response.getStatus() != 201 && response.getStatus() != 200))
	{
		throw new RuntimeException("Failed : HTTP error code on commit: " + response.getStatus());
	}
	response.close();
}
 
Example 18
Source File: NeoGraphDatabase.java    From navex with GNU General Public License v3.0 5 votes vote down vote up
private static void checkDatabaseIsRunning()
{
	// START SNIPPET: checkServer
	WebResource resource = Client.create()
			.resource( SERVER_ROOT_URI );
	ClientResponse response = resource.get( ClientResponse.class );

	System.out.println( String.format( "GET on [%s], status code [%d]",
			SERVER_ROOT_URI, response.getStatus() ) );
	response.close();
	// END SNIPPET: checkServer
}
 
Example 19
Source File: TestRMWebServicesAppsModification.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 120000)
public void testSingleAppKill() throws Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  String[] mediaTypes =
      { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML };
  MediaType[] contentTypes =
      { MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE };
  for (String mediaType : mediaTypes) {
    for (MediaType contentType : contentTypes) {
      RMApp app = rm.submitApp(CONTAINER_MB, "", webserviceUserName);
      amNodeManager.nodeHeartbeat(true);

      AppState targetState =
          new AppState(YarnApplicationState.KILLED.toString());

      Object entity;
      if (contentType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        entity = appStateToJSON(targetState);
      } else {
        entity = targetState;
      }
      ClientResponse response =
          this
            .constructWebResource("apps", app.getApplicationId().toString(),
              "state").entity(entity, contentType).accept(mediaType)
            .put(ClientResponse.class);

      if (!isAuthenticationEnabled()) {
        assertEquals(Status.UNAUTHORIZED, response.getClientResponseStatus());
        continue;
      }
      assertEquals(Status.ACCEPTED, response.getClientResponseStatus());
      if (mediaType.equals(MediaType.APPLICATION_JSON)) {
        verifyAppStateJson(response, RMAppState.FINAL_SAVING,
          RMAppState.KILLED, RMAppState.KILLING, RMAppState.ACCEPTED);
      } else {
        verifyAppStateXML(response, RMAppState.FINAL_SAVING,
          RMAppState.KILLED, RMAppState.KILLING, RMAppState.ACCEPTED);
      }

      String locationHeaderValue =
          response.getHeaders().getFirst(HttpHeaders.LOCATION);
      Client c = Client.create();
      WebResource tmp = c.resource(locationHeaderValue);
      if (isAuthenticationEnabled()) {
        tmp = tmp.queryParam("user.name", webserviceUserName);
      }
      response = tmp.get(ClientResponse.class);
      assertEquals(Status.OK, response.getClientResponseStatus());
      assertTrue(locationHeaderValue.endsWith("/ws/v1/cluster/apps/"
          + app.getApplicationId().toString() + "/state"));

      while (true) {
        Thread.sleep(100);
        response =
            this
              .constructWebResource("apps",
                app.getApplicationId().toString(), "state").accept(mediaType)
              .entity(entity, contentType).put(ClientResponse.class);
        assertTrue((response.getClientResponseStatus() == Status.ACCEPTED)
            || (response.getClientResponseStatus() == Status.OK));
        if (response.getClientResponseStatus() == Status.OK) {
          assertEquals(RMAppState.KILLED, app.getState());
          if (mediaType.equals(MediaType.APPLICATION_JSON)) {
            verifyAppStateJson(response, RMAppState.KILLED);
          } else {
            verifyAppStateXML(response, RMAppState.KILLED);
          }
          break;
        }
      }
    }
  }

  rm.stop();
}
 
Example 20
Source File: TestRMWebServicesAppsModification.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 120000)
public void testSingleAppKill() throws Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  String[] mediaTypes =
      { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML };
  MediaType[] contentTypes =
      { MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE };
  for (String mediaType : mediaTypes) {
    for (MediaType contentType : contentTypes) {
      RMApp app = rm.submitApp(CONTAINER_MB, "", webserviceUserName);
      amNodeManager.nodeHeartbeat(true);

      AppState targetState =
          new AppState(YarnApplicationState.KILLED.toString());

      Object entity;
      if (contentType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        entity = appStateToJSON(targetState);
      } else {
        entity = targetState;
      }
      ClientResponse response =
          this
            .constructWebResource("apps", app.getApplicationId().toString(),
              "state").entity(entity, contentType).accept(mediaType)
            .put(ClientResponse.class);

      if (!isAuthenticationEnabled()) {
        assertEquals(Status.UNAUTHORIZED, response.getClientResponseStatus());
        continue;
      }
      assertEquals(Status.ACCEPTED, response.getClientResponseStatus());
      if (mediaType.equals(MediaType.APPLICATION_JSON)) {
        verifyAppStateJson(response, RMAppState.FINAL_SAVING,
          RMAppState.KILLED, RMAppState.KILLING, RMAppState.ACCEPTED);
      } else {
        verifyAppStateXML(response, RMAppState.FINAL_SAVING,
          RMAppState.KILLED, RMAppState.KILLING, RMAppState.ACCEPTED);
      }

      String locationHeaderValue =
          response.getHeaders().getFirst(HttpHeaders.LOCATION);
      Client c = Client.create();
      WebResource tmp = c.resource(locationHeaderValue);
      if (isAuthenticationEnabled()) {
        tmp = tmp.queryParam("user.name", webserviceUserName);
      }
      response = tmp.get(ClientResponse.class);
      assertEquals(Status.OK, response.getClientResponseStatus());
      assertTrue(locationHeaderValue.endsWith("/ws/v1/cluster/apps/"
          + app.getApplicationId().toString() + "/state"));

      while (true) {
        Thread.sleep(100);
        response =
            this
              .constructWebResource("apps",
                app.getApplicationId().toString(), "state").accept(mediaType)
              .entity(entity, contentType).put(ClientResponse.class);
        assertTrue((response.getClientResponseStatus() == Status.ACCEPTED)
            || (response.getClientResponseStatus() == Status.OK));
        if (response.getClientResponseStatus() == Status.OK) {
          assertEquals(RMAppState.KILLED, app.getState());
          if (mediaType.equals(MediaType.APPLICATION_JSON)) {
            verifyAppStateJson(response, RMAppState.KILLED);
          } else {
            verifyAppStateXML(response, RMAppState.KILLED);
          }
          break;
        }
      }
    }
  }

  rm.stop();
}