org.restlet.data.Method Java Examples

The following examples show how to use org.restlet.data.Method. 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: AdminTestHelper.java    From helix with Apache License 2.0 7 votes vote down vote up
public static ZNRecord post(Client client, String url, String body)
    throws IOException {
  Reference resourceRef = new Reference(url);
  Request request = new Request(Method.POST, resourceRef);

  request.setEntity(body, MediaType.APPLICATION_ALL);

  Response response = client.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();

  if (result != null) {
    result.write(sw);
  }
  String responseStr = sw.toString();
  Assert.assertTrue(responseStr.toLowerCase().indexOf("error") == -1);
  Assert.assertTrue(responseStr.toLowerCase().indexOf("exception") == -1);

  ObjectMapper mapper = new ObjectMapper();
  ZNRecord record = mapper.readValue(new StringReader(responseStr), ZNRecord.class);
  return record;
}
 
Example #2
Source File: GeoWaveOperationServiceWrapperTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
public void getMethodReturnsSuccessStatus() throws Exception {

  // Rarely used Teapot Code to check.
  final Boolean successStatusIs200 = true;

  final ServiceEnabledCommand operation = mockedOperation(HttpMethod.GET, successStatusIs200);

  classUnderTest = new GeoWaveOperationServiceWrapper(operation, null);
  classUnderTest.setResponse(new Response(null));
  classUnderTest.setRequest(new Request(Method.GET, "foo.bar"));
  classUnderTest.restGet();
  Assert.assertEquals(
      successStatusIs200,
      classUnderTest.getResponse().getStatus().equals(Status.SUCCESS_OK));
}
 
Example #3
Source File: RequestWriterDelegator.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@Override
public boolean writeRequest(Object requestObject, Request request) throws ResourceException
{
   if (requestObject == null)
   {
      if (!Method.GET.equals(request.getMethod()))
         request.setEntity(new EmptyRepresentation());

      return true;
   }

   if (requestObject instanceof Representation)
   {
      request.setEntity((Representation) requestObject);
      return true;
   }

   for (RequestWriter requestWriter : requestWriters)
   {
      if (requestWriter.writeRequest(requestObject, request))
         return true;
   }

   return false;
}
 
Example #4
Source File: AbstractResourceTest.java    From ontopia with Apache License 2.0 6 votes vote down vote up
protected void assertRequestFails(String url, Method method, MediaType preferred, Object object, OntopiaRestErrors expected) {
	OntopiaTestResource cr = new OntopiaTestResource(method, getUrl(url), preferred);
	try {
		cr.request(object, Object.class);
		Assert.fail("Expected Ontopia error " + expected.name() + ", but request succeeded");
	} catch (OntopiaTestResourceException e) {
		Error result = e.getError();
		try {
			Assert.assertNotNull("Expected error, found null", result);
			Assert.assertEquals("Ontopia error code mismatch", expected.getCode(), result.getCode());
			Assert.assertEquals("HTTP status code mismatch", expected.getStatus().getCode(), result.getHttpcode());
			Assert.assertNotNull("Error message is empty", result.getMessage());
		} catch (AssertionError ae) {
			Assert.fail("Expected ontopia error " + expected.name() + 
					", but received [" + result.getHttpcode() + ":" + result.getCode() + ", " + result.getMessage() + "]");
		}
	} catch (ResourceException re) {
		Assert.fail("Expected ontopia error " + expected.name() + 
				", but received [" + re.getStatus().getCode() + ":" + re.getStatus().getDescription() + "]");
	}
}
 
Example #5
Source File: TestProjectImportResource.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGitHub() {
	Client client = new Client(Protocol.HTTP);
	Request request = new Request(Method.POST, "http://localhost:8182/projects/import");
	
	ObjectMapper mapper = new ObjectMapper();
	ObjectNode n = mapper.createObjectNode();
	n.put("url", "https://github.com/jrwilliams/gif-hook");
	
	request.setEntity(n.toString(), MediaType.APPLICATION_JSON);
	
	Response response = client.handle(request);
	
	validateResponse(response, 201);
	
	System.out.println(response.getEntityAsText());
}
 
Example #6
Source File: TestProjectImportResource.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testEclipse() {
	Client client = new Client(Protocol.HTTP);
	Request request = new Request(Method.POST, "http://localhost:8182/projects/import");
	
	ObjectMapper mapper = new ObjectMapper();
	ObjectNode n = mapper.createObjectNode();
	n.put("url", "https://projects.eclipse.org/projects/modeling.epsilon");
	
	request.setEntity(n.toString(), MediaType.APPLICATION_JSON);
	
	Response response = client.handle(request);
	
	validateResponse(response, 201);
	
	System.out.println(response.getEntityAsText());
}
 
Example #7
Source File: ApiHelper.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
public Response createTask(String projectId, String taskId, String label, AnalysisExecutionMode mode,
		List<String> metrics, String start, String end) {
	Request request = new Request(Method.POST, "http://localhost:8182/analysis/task/create");

	ObjectMapper mapper = new ObjectMapper();
	ObjectNode n = mapper.createObjectNode();
	n.put("analysisTaskId", taskId);
	n.put("label", label);
	n.put("type", mode.name());
	n.put("startDate", start);
	n.put("endDate", end);
	n.put("projectId", projectId);
	ArrayNode arr = n.putArray("metricProviders");
	for (String m : metrics)
		arr.add(m);

	request.setEntity(n.toString(), MediaType.APPLICATION_JSON);

	return client.handle(request);
}
 
Example #8
Source File: TestClusterManagementWebapp.java    From helix with Apache License 2.0 5 votes vote down vote up
void verifyAddCluster() throws IOException, InterruptedException {
  String httpUrlBase = "http://localhost:" + ADMIN_PORT + "/clusters";
  Map<String, String> paraMap = new HashMap<String, String>();

  paraMap.put(JsonParameters.CLUSTER_NAME, clusterName);
  paraMap.put(JsonParameters.MANAGEMENT_COMMAND, ClusterSetup.addCluster);

  Reference resourceRef = new Reference(httpUrlBase);

  Request request = new Request(Method.POST, resourceRef);

  request.setEntity(
      JsonParameters.JSON_PARAMETERS + "=" + ClusterRepresentationUtil.ObjectToJson(paraMap),
      MediaType.APPLICATION_ALL);
  Response response = _gClient.handle(request);

  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();
  result.write(sw);

  // System.out.println(sw.toString());

  ObjectMapper mapper = new ObjectMapper();
  ZNRecord zn = mapper.readValue(new StringReader(sw.toString()), ZNRecord.class);
  AssertJUnit.assertTrue(zn.getListField("clusters").contains(clusterName));

}
 
Example #9
Source File: ContextResourceClient.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private HandlerCommand invokeQuery( Reference ref, Object queryRequest, ResponseHandler resourceHandler, ResponseHandler processingErrorHandler )
{
    Request request = new Request( Method.GET, ref );

    if( queryRequest != null )
    {
        contextResourceFactory.writeRequest( request, queryRequest );
    }

    contextResourceFactory.updateQueryRequest( request );

    User user = request.getClientInfo().getUser();
    if ( user != null)
        request.setChallengeResponse( new ChallengeResponse( ChallengeScheme.HTTP_BASIC, user.getName(), user.getSecret() ) );

    Response response = new Response( request );

    contextResourceFactory.getClient().handle( request, response );

    if( response.getStatus().isSuccess() )
    {
        contextResourceFactory.updateCache( response );

        return resourceHandler.handleResponse( response, this );
    } else if (response.getStatus().isRedirection())
    {
        Reference redirectedTo = response.getLocationRef();
        return invokeQuery( redirectedTo, queryRequest, resourceHandler, processingErrorHandler );
    } else
    {
        if (response.getStatus().equals(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY) && processingErrorHandler != null)
        {
            return processingErrorHandler.handleResponse( response, this );
        } else
        {
            // TODO This needs to be expanded to allow custom handling of all the various cases
            return errorHandler.handleResponse( response, this );
        }
    }
}
 
Example #10
Source File: ContextRestlet.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private String getUsecaseName( Request request )
{
    if( request.getMethod().equals( org.restlet.data.Method.DELETE ) )
    {
        return "delete";
    }
    else
    {
        return request.getResourceRef().getLastSegment();
    }
}
 
Example #11
Source File: ResourceBuilder.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public RestForm createNameForm( Reference base )
{
    ValueBuilder<RestForm> builder = vbf.newValueBuilder( RestForm.class );
    builder.prototype().link().set( createRestLink( "form", base, Method.POST ) );
    builder.prototype().fields().set( Collections.singletonList( createFormField( "name", FormField.TEXT ) ) );
    return builder.newInstance();
}
 
Example #12
Source File: EntryPointResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private EntryPoint createEntryPoint()
        {
            Map<String, RestLink> entryPoints = new HashMap<>();
            for( Route r : parameters.router().get().getRoutes() )
            {
                if( r instanceof TemplateRoute)
                {
                    TemplateRoute route = (TemplateRoute) r;
                    Template template = route.getTemplate();
                    // Only include patterns that doesn't have variables, and has a proper name.
                    if( template.getVariableNames().isEmpty() && route.getName().indexOf( '>' ) == -1 )
                    {
                        Reference hostRef = parameters.request().get().getOriginalRef();
//                        Reference reference = new Reference( hostRef, template.getPattern() );
                        RestLink link;
                        if( route.getDescription() == null )
                        {
                            link = resourceBuilder.createRestLink( template.getPattern(), hostRef, Method.GET );
                        }
                        else
                        {
                            link = resourceBuilder.createRestLink( template.getPattern(), hostRef, Method.GET, route.getDescription() );
                        }
                        entryPoints.put( route.getName(), link );
                    }
                }
            }
            ValueBuilder<EntryPoint> builder = vbf.newValueBuilder( EntryPoint.class );
            builder.prototype().identity().set( StringIdentity.identityOf( "/" ) );
            builder.prototype().api().set( entryPoints );
            return builder.newInstance();
        }
 
Example #13
Source File: CreationResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public RestLink post( RestForm form )
{
    String name = form.field( "name" ).value().get();
    Class<? extends HasIdentity> entityType = parameters.entityType().get();
    Identity identity = identityManager.generate( entityType, name );
    locator.find( entityType ).create( identity );
    doParameterization( form, entityType, identity );
    return resourceBuilder.createRestLink( identity.toString(), parameters.request().get().getResourceRef(), Method.GET );
}
 
Example #14
Source File: EntityListResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public RestLink post( RestForm form )
{
    FormField nameField = form.field( "name" );
    String name = null;
    if( nameField != null )
    {
        name = nameField.value().get();
    }
    Reference base = parameters.request().get().getResourceRef();
    Class<T> entityType = parameters.entityType().get();
    Identity identity = identityManager.generate(entityType, name);
    locator.find( entityType ).create( identity );
    return resourceBuilder.createRestLink( identity.toString(), base, Method.GET );
}
 
Example #15
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getBundleRepresentations()
 */
public Collection<BundleDTO> getBundles() throws Exception {
	try {
		final Representation repr = new ClientResource(Method.GET,
				baseUri.resolve("framework/bundles/representations"))
				.get(BUNDLES_REPRESENTATIONS);

		return DTOReflector.getDTOs(BundleDTO.class, repr);
	} catch (final ResourceException e) {
		if (Status.CLIENT_ERROR_NOT_FOUND.equals(e.getStatus())) {
			return null;
		}
		throw e;
	}
}
 
Example #16
Source File: TestHelixAdminScenariosRest.java    From helix with Apache License 2.0 5 votes vote down vote up
void deleteUrl(String url, boolean hasException) throws IOException {
  Reference resourceRef = new Reference(url);
  Request request = new Request(Method.DELETE, resourceRef);
  Response response = _gClient.handle(request);
  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();
  result.write(sw);
  Assert.assertTrue(hasException == sw.toString().toLowerCase().contains("exception"));
}
 
Example #17
Source File: AbstractResourceTest.java    From ontopia with Apache License 2.0 5 votes vote down vote up
protected <T> T request(String url, Method method, Object object, Class<T> expected) {
	try {
		return new OntopiaTestResource(method, getUrl(url), defaultMediatype).request(object, expected);
	} catch (OntopiaTestResourceException e) {
		Assert.fail("Unexpected request error encountered: " + e.getError().getMessage());
	} catch (ResourceException re) {
		Assert.fail("Unexpected request error encountered: " + re.getMessage() + " " + re.getStatus().getReasonPhrase());
	}
	return null;
}
 
Example #18
Source File: ResourceBuilder.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public RestLink createRestLink( String name, Reference base, Method method )
{
    ValueBuilder<RestLink> builder = vbf.newValueBuilder( RestLink.class );
    RestLink prototype = builder.prototype();
    String path = base.toUri().resolve( name ).getPath();
    prototype.path().set( path.endsWith( "/" ) ? path : path + "/" );
    prototype.method().set( method.getName() );
    return builder.newInstance();
}
 
Example #19
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getServiceReference(java.lang.String)
 */
public ServiceReferenceDTO getServiceReference(final String servicePath)
		throws Exception {
	final Representation repr = new ClientResource(Method.GET,
			baseUri.resolve(servicePath)).get(SERVICE);

	return DTOReflector.getDTO(ServiceReferenceDTO.class,
			repr);
}
 
Example #20
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getServices(java.lang.String)
 */
public Collection<String> getServicePaths(final String filter) throws Exception {
	final ClientResource res = new ClientResource(Method.GET,
			baseUri.resolve("framework/services"));

	if (filter != null) {
		res.getQuery().add("filter", filter);
	}

	final Representation repr = res.get(SERVICES);

	return DTOReflector.getStrings(repr);
}
 
Example #21
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#uninstallBundle(java.lang.String)
 */
public BundleDTO uninstallBundle(final String bundlePath) throws Exception {
	final BundleDTO bundle = getBundle(bundlePath);
	
	final ClientResource res = new ClientResource(Method.DELETE,
			baseUri.resolve(bundlePath));
	
	res.delete();
	return bundle;
}
 
Example #22
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#updateBundle(long,
 *      java.io.InputStream)
 */
public BundleDTO updateBundle(final long id, final InputStream in)
		throws Exception {
	new ClientResource(Method.PUT, baseUri.resolve("framework/bundle/"
			+ id)).put(in);
	return getBundle(id);
}
 
Example #23
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#installBundle(java.net.URL)
 */
public BundleDTO installBundle(final String url) throws Exception {
	final ClientResource res = new ClientResource(Method.POST,
			baseUri.resolve("framework/bundles"));
	final Representation repr = res.post(url, MediaType.TEXT_PLAIN);

	return getBundle(repr.getText());
}
 
Example #24
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#setBundleStartLevel(java.lang.String,
 *      org.osgi.dto.framework.startlevel.BundleStartLevelDTO)
 */
public void setBundleStartLevel(final String bundlePath,
		final int startLevel) throws Exception {
	BundleStartLevelDTO bsl = new BundleStartLevelDTO();
	bsl.startLevel = startLevel;
	new ClientResource(Method.PUT, baseUri.resolve(bundlePath
			+ "/startlevel")).put(
			DTOReflector.getJson(BundleStartLevelDTO.class, bsl),
			BUNDLE_STARTLEVEL);
}
 
Example #25
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getBundleStartLevel(java.lang.String)
 */
public BundleStartLevelDTO getBundleStartLevel(final String bundlePath)
		throws Exception {
	final Representation repr = new ClientResource(Method.GET,
			baseUri.resolve(bundlePath + "/startlevel"))
			.get(BUNDLE_STARTLEVEL);

	return DTOReflector.getDTO(BundleStartLevelDTO.class, repr);
}
 
Example #26
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#stopBundle(java.lang.String)
 */
public void stopBundle(final String bundlePath, final int options)
		throws Exception {
	final JSONObject state = new JSONObject();
	state.put("state", 4);
	state.put("options", options);
	new ClientResource(Method.PUT, baseUri.resolve(bundlePath + "/state"))
			.put(state, BUNDLE_STATE);
}
 
Example #27
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#startBundle(java.lang.String)
 */
public void startBundle(final String bundlePath, final int options)
		throws Exception {
	// FIXME: hardcoded to JSON
	final JSONObject state = new JSONObject();
	state.put("state", 32);
	state.put("options", options);
	new ClientResource(Method.PUT, baseUri.resolve(bundlePath + "/state"))
			.put(state, BUNDLE_STATE);
}
 
Example #28
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getBundleState(java.lang.String)
 */
public int getBundleState(final String bundlePath) throws Exception {
	final Representation repr = new ClientResource(Method.GET,
			baseUri.resolve(bundlePath + "/state")).get(BUNDLE_STATE);

	// FIXME: hardcoded to JSON
	final JSONObject obj = new JsonRepresentation(repr).getJsonObject();
	return obj.getInt("state");
}
 
Example #29
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getBundle(java.lang.String)
 */
public BundleDTO getBundle(final String bundlePath) throws Exception {
	try {
		final Representation repr = new ClientResource(Method.GET,
				baseUri.resolve(bundlePath)).get(BUNDLE);
		return DTOReflector.getDTO(BundleDTO.class, repr);
	} catch (final ResourceException e) {
		if (Status.CLIENT_ERROR_NOT_FOUND.equals(e.getStatus())) {
			return null;
		}
		throw e;
	}
}
 
Example #30
Source File: ApiHelper.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public Response importProject(String url) {
	Request request = new Request(Method.POST, "http://localhost:8182/projects/import");

	ObjectMapper mapper = new ObjectMapper();
	ObjectNode n = mapper.createObjectNode();
	n.put("url", url);

	request.setEntity(n.toString(), MediaType.APPLICATION_JSON);

	return client.handle(request);
}