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

The following examples show how to use com.sun.jersey.api.client.WebResource#queryParam() . 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: ApplicationWsDelegate.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Changes the state of an instance.
 * <p>
 * Notice that these actions, like of most of the others, are performed asynchronously.
 * It means invoking these REST operations is equivalent to submitting a request. How it
 * will be processed concretely will depend then on the agent.
 * </p>
 *
 * @param applicationName the application name
 * @param newStatus the new state of the instance
 * @param instancePath the instance path (not null)
 * @throws ApplicationWsException if something went wrong
 */
public void changeInstanceState( String applicationName, InstanceStatus newStatus, String instancePath )
throws ApplicationWsException {

	this.logger.finer( "Changing state of " + instancePath + " to '" + newStatus + "' in " + applicationName + "."  );

	WebResource path = this.resource.path( UrlConstants.APP ).path( applicationName ).path( "change-state" );
	if( instancePath != null )
		path = path.queryParam( "instance-path", instancePath );

	if( newStatus != null )
		path = path.queryParam( "new-state", newStatus.toString());

	ClientResponse response = this.wsClient.createBuilder( path )
				.accept( MediaType.APPLICATION_JSON )
				.post( ClientResponse.class );

	handleResponse( response );
	this.logger.finer( String.valueOf( response.getStatusInfo()));
}
 
Example 2
Source File: AtlasClient.java    From atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Get the entity audit events in decreasing order of timestamp for the given entity id
 * @param entityId entity id
 * @param startKey key for the first event to be returned, used for pagination
 * @param numResults number of results to be returned
 * @return list of audit events for the entity id
 * @throws AtlasServiceException
 */
public List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults)
        throws AtlasServiceException {
    WebResource resource = getResource(API_V1.LIST_ENTITY_AUDIT, entityId, URI_ENTITY_AUDIT);
    if (StringUtils.isNotEmpty(startKey)) {
        resource = resource.queryParam(START_KEY, startKey);
    }
    resource = resource.queryParam(NUM_RESULTS, String.valueOf(numResults));

    ObjectNode jsonResponse = callAPIWithResource(API_V1.LIST_ENTITY_AUDIT, resource);
    return extractResults(jsonResponse, AtlasClient.EVENTS, new ExtractOperation<EntityAuditEvent, ObjectNode>() {
        @Override
        EntityAuditEvent extractElement(ObjectNode element) {
            return AtlasType.fromV1Json(element.toString(), EntityAuditEvent.class);
        }
    });

}
 
Example 3
Source File: TargetWsDelegate.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Associates or dissociates an application and a target.
 * @param app an application or application template
 * @param targetId a target ID
 * @param instancePathOrComponentName an instance path or a component name (can be null)
 * @param bind true to create a binding, false to delete one
 * @throws TargetWsException
 */
public void associateTarget( AbstractApplication app, String instancePathOrComponentName, String targetId, boolean bind )
throws TargetWsException {

	if( bind )
		this.logger.finer( "Associating " + app + " :: " + instancePathOrComponentName + " with " + targetId );
	else
		this.logger.finer( "Dissociating " + app + " :: " + instancePathOrComponentName + " from " + targetId );

	WebResource path = this.resource.path( UrlConstants.TARGETS )
			.path( targetId ).path( "associations" )
			.queryParam( "bind", Boolean.toString( bind ))
			.queryParam( "name", app.getName());

	if( instancePathOrComponentName != null )
		path = path.queryParam( "elt", instancePathOrComponentName );

	if( app instanceof ApplicationTemplate )
		path = path.queryParam( "qualifier", ((ApplicationTemplate) app).getVersion());

	ClientResponse response = this.wsClient.createBuilder( path )
					.accept( MediaType.APPLICATION_JSON )
					.post( ClientResponse.class );

	handleResponse( response );
}
 
Example 4
Source File: ApplicationWsDelegate.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Undeploys several instances at once.
 * @param applicationName the application name
 * @param instancePath the path of the instance to undeploy (null for all the application instances)
 * @throws ApplicationWsException if something went wrong
 */
public void undeployAll( String applicationName, String instancePath )
throws ApplicationWsException {

	this.logger.finer( "Undeploying instances in " + applicationName + " from instance = " + instancePath  );

	WebResource path = this.resource.path( UrlConstants.APP ).path( applicationName ).path( "undeploy-all" );
	if( instancePath != null )
		path = path.queryParam( "instance-path", instancePath );

	ClientResponse response = this.wsClient.createBuilder( path )
					.accept( MediaType.APPLICATION_JSON )
					.post( ClientResponse.class );

	handleResponse( response );
	this.logger.finer( String.valueOf( response.getStatusInfo()));
}
 
Example 5
Source File: ManagementWsDelegate.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Lists applications.
 * @param exactName if not null, the result list will contain at most one application (with this name)
 * @return a non-null list of applications
 * @throws ManagementWsException if a problem occurred with the applications management
 */
public List<Application> listApplications( String exactName ) throws ManagementWsException {

	if( exactName != null )
		this.logger.finer( "List/finding the application named " + exactName + "." );
	else
		this.logger.finer( "Listing all the applications." );

	WebResource path = this.resource.path( UrlConstants.APPLICATIONS );
	if( exactName != null )
		path = path.queryParam( "name", exactName );

	List<Application> result = this.wsClient.createBuilder( path )
			.accept( MediaType.APPLICATION_JSON )
			.get( new GenericType<List<Application>> () {});

	if( result != null )
		this.logger.finer( result.size() + " applications were found on the DM." );
	else
		this.logger.finer( "No application was found on the DM." );

	return result != null ? result : new ArrayList<Application> ();
}
 
Example 6
Source File: ApplicationWsDelegate.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the component names you could instantiate and deploy on an existing instance.
 * @param applicationName the application name
 * @param componentName a component name (null to get root components)
 * @return a non-null list of component names
 */
public List<Component> findComponentChildren( String applicationName, String componentName ) {
	this.logger.finer( "Listing possible children components for component " + componentName + "..." );

	WebResource path = this.resource.path( UrlConstants.APP ).path( applicationName ).path( "components/children" );
	if( componentName != null )
		path = path.queryParam( "component-name", componentName );

	List<Component> result = this.wsClient.createBuilder( path )
				.accept( MediaType.APPLICATION_JSON )
				.get( new GenericType<List<Component>> () {});

	if( result != null ) {
		this.logger.finer( result.size() + " possible children was or were found for " + componentName + "." );
	} else {
		this.logger.finer( "No possible child was found for " + componentName + "." );
		result = new ArrayList<>( 0 );
	}

	return result;
}
 
Example 7
Source File: AtlasClient.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Get the entity audit events in decreasing order of timestamp for the given entity id
 * @param entityId entity id
 * @param startKey key for the first event to be returned, used for pagination
 * @param numResults number of results to be returned
 * @return list of audit events for the entity id
 * @throws AtlasServiceException
 */
public List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults)
        throws AtlasServiceException {
    WebResource resource = getResource(API.LIST_ENTITY_AUDIT, entityId, URI_ENTITY_AUDIT);
    if (StringUtils.isNotEmpty(startKey)) {
        resource = resource.queryParam(START_KEY, startKey);
    }
    resource = resource.queryParam(NUM_RESULTS, String.valueOf(numResults));

    JSONObject jsonResponse = callAPIWithResource(API.LIST_ENTITY_AUDIT, resource);
    return extractResults(jsonResponse, AtlasClient.EVENTS, new ExtractOperation<EntityAuditEvent, JSONObject>() {
        @Override
        EntityAuditEvent extractElement(JSONObject element) throws JSONException {
            return SerDe.GSON.fromJson(element.toString(), EntityAuditEvent.class);
        }
    });

}
 
Example 8
Source File: AtlasClient.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Supports Deletion of an entity identified by its unique attribute value
 * @param entityType Type of the entity being deleted
 * @param uniqueAttributeName Attribute Name that uniquely identifies the entity
 * @param uniqueAttributeValue Attribute Value that uniquely identifies the entity
 * @return List of entity ids updated/deleted(including composite references from that entity)
 */
public EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue)
        throws AtlasServiceException {
    LOG.debug("Deleting entity type: {}, attributeName: {}, attributeValue: {}", entityType, uniqueAttributeName,
            uniqueAttributeValue);
    API api = API.DELETE_ENTITY;
    WebResource resource = getResource(api);
    resource = resource.queryParam(TYPE, entityType);
    resource = resource.queryParam(ATTRIBUTE_NAME, uniqueAttributeName);
    resource = resource.queryParam(ATTRIBUTE_VALUE, uniqueAttributeValue);
    JSONObject jsonResponse = callAPIWithResource(API.DELETE_ENTITIES, resource);
    EntityResult results = extractEntityResult(jsonResponse);
    LOG.debug("Delete entities returned results: {}", results);
    return results;
}
 
Example 9
Source File: RestRequests.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public static WebResource addParams( WebResource resource, CoordinatorFig coordinator ) {
    Preconditions.checkNotNull( resource, "The 'resource' MUST NOT be null." );
    Preconditions.checkNotNull( coordinator, "The 'coordinator' MUST NOT be null." );

    resource = resource.queryParam( RestParams.USERNAME, coordinator.getUsername() );
    return resource.queryParam( RestParams.PASSWORD, coordinator.getPassword() );
}
 
Example 10
Source File: RangerRESTClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
protected static WebResource setQueryParams(WebResource webResource, Map<String, String> params) {
	WebResource ret = webResource;
	if (webResource != null && params != null) {
		Set<Map.Entry<String, String>> entrySet= params.entrySet();
		for (Map.Entry<String, String> entry : entrySet) {
			ret = ret.queryParam(entry.getKey(), entry.getValue());
		}
	}
	return ret;
}
 
Example 11
Source File: HttpGetMapOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
protected WebResource getResourceWithQueryParams(Map<K, V> t)
{
  WebResource wr = wsClient.resource(url);

  for (Entry<K, V> entry : t.entrySet()) {
    wr = wr.queryParam(entry.getKey().toString(), entry.getValue().toString());
  }

  return wr;
}
 
Example 12
Source File: RestRequests.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public static WebResource addParams( WebResource resource, Runner runner ) {
    Preconditions.checkNotNull( resource, "The 'resource' MUST NOT be null." );
    Preconditions.checkNotNull( runner, "The 'runner' MUST NOT be null." );

    resource = resource.queryParam( RestParams.RUNNER_URL, runner.getUrl() );
    resource = resource.queryParam( RestParams.RUNNER_HOSTNAME, runner.getHostname() );
    resource = resource.queryParam( RestParams.RUNNER_IPV4_ADDRESS, runner.getIpv4Address() );
    return resource.queryParam( RestParams.RUNNER_PORT, String.valueOf( runner.getServerPort() ) );
}
 
Example 13
Source File: ClientUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the content at the specified URI using the given query parameters.
 *
 * @param uri the URI to get the content of
 * @param queryParams the query parameters to use in the request
 * @return the client response resulting from getting the content of the URI
 * @throws ClientHandlerException if issues occur handling the request
 * @throws UniformInterfaceException if any interface violations occur
 */
public ClientResponse get(final URI uri, final Map<String, String> queryParams) throws ClientHandlerException, UniformInterfaceException {
    // perform the request
    WebResource webResource = client.resource(uri);
    if (queryParams != null) {
        for (final Map.Entry<String, String> queryEntry : queryParams.entrySet()) {
            webResource = webResource.queryParam(queryEntry.getKey(), queryEntry.getValue());
        }
    }

    return webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
}
 
Example 14
Source File: AtlasBaseClient.java    From atlas with Apache License 2.0 5 votes vote down vote up
private WebResource appendQueryParams(MultivaluedMap<String, String> queryParams, WebResource resource) {
    if (null != queryParams && !queryParams.isEmpty()) {
        for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {
            for (String value : entry.getValue()) {
                if (StringUtils.isNotBlank(value)) {
                    resource = resource.queryParam(entry.getKey(), value);
                }
            }
        }
    }
    return resource;
}
 
Example 15
Source File: AtlasBaseClient.java    From atlas with Apache License 2.0 5 votes vote down vote up
private WebResource getResource(API api, String queryParamKey, List<String> queryParamValues) {
    WebResource resource = service.path(api.getNormalizedPath());
    for (String queryParamValue : queryParamValues) {
        if (StringUtils.isNotBlank(queryParamKey) && StringUtils.isNotBlank(queryParamValue)) {
            resource = resource.queryParam(queryParamKey, queryParamValue);
        }
    }
    return resource;
}
 
Example 16
Source File: AtlasClient.java    From atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Supports Deletion of an entity identified by its unique attribute value
 * @param entityType Type of the entity being deleted
 * @param uniqueAttributeName Attribute Name that uniquely identifies the entity
 * @param uniqueAttributeValue Attribute Value that uniquely identifies the entity
 * @return List of entity ids updated/deleted(including composite references from that entity)
 */
public EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue)
        throws AtlasServiceException {
    LOG.debug("Deleting entity type: {}, attributeName: {}, attributeValue: {}", entityType, uniqueAttributeName,
              uniqueAttributeValue);
    API         api      = API_V1.DELETE_ENTITIES;
    WebResource resource = getResource(api);
    resource = resource.queryParam(TYPE, entityType);
    resource = resource.queryParam(ATTRIBUTE_NAME, uniqueAttributeName);
    resource = resource.queryParam(ATTRIBUTE_VALUE, uniqueAttributeValue);
    ObjectNode   jsonResponse = callAPIWithResource(api, resource);
    EntityResult results      = extractEntityResult(jsonResponse);
    LOG.debug("Delete entities returned results: {}", results);
    return results;
}
 
Example 17
Source File: NiFiTestUser.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Performs a DELETE using the specified url and query parameters.
 *
 * @param url url
 * @param queryParams params
 * @return response
 * @throws java.lang.Exception ex
 */
public ClientResponse testDelete(String url, Map<String, String> queryParams) throws Exception {
    // get the resource
    WebResource resource = client.resource(url);

    // append any query parameters
    if (queryParams != null && !queryParams.isEmpty()) {
        for (String key : queryParams.keySet()) {
            resource = resource.queryParam(key, queryParams.get(key));
        }
    }

    // perform the request
    return addProxiedEntities(resource.type(MediaType.APPLICATION_FORM_URLENCODED)).delete(ClientResponse.class);
}
 
Example 18
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 19
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();
}
 
Example 20
Source File: ManagementWsDelegate.java    From roboconf-platform with Apache License 2.0 4 votes vote down vote up
/**
 * Lists application templates.
 * @param exactName if specified, only the templates with this name will be returned (null to match all)
 * <p>
 * We only consider the application name, not the display name.
 * It means that the parameter should not contain special characters.
 * </p>
 *
 * @param exactQualifier the exact qualifier to search (null to match all)
 * @return a non-null list of application templates
 * @throws ManagementWsException if a problem occurred with the applications management
 */
public List<ApplicationTemplate> listApplicationTemplates( String exactName, String exactQualifier )
throws ManagementWsException {

	// Log
	if( this.logger.isLoggable( Level.FINER )) {
		if( exactName == null && exactQualifier == null ) {
			this.logger.finer( "Listing all the application templates." );

		} else {
			StringBuilder sb = new StringBuilder( "Listing/finding the application templates" );
			if( exactName != null ) {
				sb.append( " with name = " );
				sb.append( exactName );
			}

			if( exactQualifier != null ) {
				if( exactName != null )
					sb.append( " and" );

				sb.append( " qualifier = " );
				sb.append( exactQualifier );
			}

			sb.append( "." );
			this.logger.finer( sb.toString());
		}
	}

	// Search
	WebResource path = this.resource.path( UrlConstants.APPLICATIONS ).path( "templates" );
	if( exactName != null )
		path = path.queryParam( "name", exactName );

	if( exactQualifier != null )
		path = path.queryParam( "qualifier", exactQualifier );

	List<ApplicationTemplate> result = this.wsClient.createBuilder( path )
			.accept( MediaType.APPLICATION_JSON )
			.get( new GenericType<List<ApplicationTemplate>> () {});

	if( result != null )
		this.logger.finer( result.size() + " application templates were found on the DM." );
	else
		this.logger.finer( "No application template was found on the DM." );

	return result != null ? result : new ArrayList<ApplicationTemplate> ();
}