Java Code Examples for org.restlet.Request#setEntity()

The following examples show how to use org.restlet.Request#setEntity() . 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: 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 3
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 4
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 5
Source File: FormRequestWriter.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 instanceof Form)
   {
      // Form as query parameters
      if (request.getMethod().equals(Method.GET))
         request.getResourceRef().setQuery(((Form)requestObject).getQueryString());
      else
         request.setEntity(((Form)requestObject).getWebRepresentation(CharacterSet.UTF_8));

      return true;
   }

   return false;
}
 
Example 6
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 7
Source File: TestClusterManagementWebapp.java    From helix with Apache License 2.0 6 votes vote down vote up
private void postConfig(Client client, String url, ObjectMapper mapper, String command,
    String configs) throws Exception {
  Map<String, String> params = new HashMap<String, String>();

  params.put(JsonParameters.MANAGEMENT_COMMAND, command);
  params.put(JsonParameters.CONFIGS, configs);

  Request request = new Request(Method.POST, new Reference(url));
  request.setEntity(
      JsonParameters.JSON_PARAMETERS + "=" + ClusterRepresentationUtil.ObjectToJson(params),
      MediaType.APPLICATION_ALL);

  Response response = client.handle(request);
  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();
  result.write(sw);
  String responseStr = sw.toString();
  Assert.assertTrue(responseStr.toLowerCase().indexOf("error") == -1);
  Assert.assertTrue(responseStr.toLowerCase().indexOf("exception") == -1);
}
 
Example 8
Source File: ApiHelper.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public Response setProperty(String key, String value) {
	Request request = new Request(Method.POST, "http://localhost:8182/platform/properties/create");

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

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

	return client.handle(request);
}
 
Example 9
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);
}
 
Example 10
Source File: ApiHelper.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public Response startTask(String taskId) {
	Request request = new Request(Method.POST, "http://localhost:8182/analysis/task/start");

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

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

	return client.handle(request);
}
 
Example 11
Source File: TestProjectResource.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testPostInsert() throws Exception {
	Request request = new Request(Method.POST, "http://localhost:8182/projects/");

	ObjectMapper mapper = new ObjectMapper();
	
	ObjectNode p = mapper.createObjectNode();
	p.put("name", "test");
	p.put("shortName", "test-short");
	p.put("description", "this is a description");

	request.setEntity(p.toString(), MediaType.APPLICATION_JSON);
	
	Client client = new Client(Protocol.HTTP);
	Response response = client.handle(request);
	
	System.out.println(response.getEntity().getText() + " " + response.isEntityAvailable());
	
	validateResponse(response, 201);
	
	// Now try again, it should fail
	response = client.handle(request);
	validateResponse(response, 409);
	
	// Clean up
	Mongo mongo = new Mongo();
	DB db = mongo.getDB("scava");
	DBCollection col = db.getCollection("projects");
	BasicDBObject query = new BasicDBObject("name", "test");
	col.remove(query);

	mongo.close();
}
 
Example 12
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 13
Source File: ControllerRequestURLBuilder.java    From uReplicator with Apache License 2.0 4 votes vote down vote up
public Request getTopicCreationRequestUrl(String topic, int numPartitions) {
  Request request = new Request(Method.POST, _baseUrl + "/topics/");
  TopicPartition topicPartitionInfo = new TopicPartition(topic, numPartitions);
  request.setEntity(topicPartitionInfo.toJSON().toJSONString(), MediaType.APPLICATION_JSON);
  return request;
}
 
Example 14
Source File: ControllerRequestURLBuilder.java    From uReplicator with Apache License 2.0 4 votes vote down vote up
public Request getTopicExpansionRequestUrl(String topic, int numPartitions) {
  Request request = new Request(Method.PUT, _baseUrl + "/topics/");
  TopicPartition topicPartitionInfo = new TopicPartition(topic, numPartitions);
  request.setEntity(topicPartitionInfo.toJSON().toJSONString(), MediaType.APPLICATION_JSON);
  return request;
}
 
Example 15
Source File: ValueCompositeRequestWriter.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Override
public boolean writeRequest(Object requestObject, Request request) throws ResourceException
{
   if (requestObject instanceof ValueComposite)
   {
      // Value as parameter
      final ValueComposite valueObject = (ValueComposite) requestObject;
      if (request.getMethod().equals(Method.GET))
      {
         StateHolder holder = spi.stateOf( valueObject );
         final ValueDescriptor descriptor = spi.valueDescriptorFor( valueObject );

          final Reference ref = request.getResourceRef();
          ref.setQuery( null );
          descriptor.state().properties().forEach( propertyDescriptor -> {
              try
              {
                  Object value = holder.propertyFor( propertyDescriptor.accessor() ).get();
                  String param;
                  if( value == null )
                  {
                      param = null;
                  }
                  else
                  {
                      param = serializer.serialize( value );
                  }
                  ref.addQueryParameter( propertyDescriptor.qualifiedName().name(), param );
              }
              catch( SerializationException e )
              {
                  throw new ResourceException( e );
              }
          } );
      }
      else
      {
         request.setEntity(new WriterRepresentation( MediaType.APPLICATION_JSON )
         {
             @Override
             public void write( Writer writer )
                 throws IOException
             {
                setCharacterSet( CharacterSet.UTF_8 );
                serializer.serialize( writer, valueObject );
             }
         });
      }

      return true;
   }

   return false;
}
 
Example 16
Source File: TestHelixAdminScenariosRest.java    From helix with Apache License 2.0 4 votes vote down vote up
static String assertSuccessPostOperation(String url, Map<String, String> jsonParameters,
    Map<String, String> extraForm, boolean hasException) throws IOException {
  Reference resourceRef = new Reference(url);

  int numRetries = 0;
  while (numRetries <= MAX_RETRIES) {
    Request request = new Request(Method.POST, resourceRef);

    if (extraForm != null) {
      String entity =
          JsonParameters.JSON_PARAMETERS + "="
              + ClusterRepresentationUtil.ObjectToJson(jsonParameters);
      for (String key : extraForm.keySet()) {
        entity = entity + "&" + (key + "=" + extraForm.get(key));
      }
      request.setEntity(entity, MediaType.APPLICATION_ALL);
    } else {
      request
          .setEntity(
              JsonParameters.JSON_PARAMETERS + "="
                  + ClusterRepresentationUtil.ObjectToJson(jsonParameters),
              MediaType.APPLICATION_ALL);
    }

    Response response = _gClient.handle(request);
    Representation result = response.getEntity();
    StringWriter sw = new StringWriter();

    if (result != null) {
      result.write(sw);
    }

    int code = response.getStatus().getCode();
    boolean successCode =
        code == Status.SUCCESS_NO_CONTENT.getCode() || code == Status.SUCCESS_OK.getCode();
    if (successCode || numRetries == MAX_RETRIES) {
      Assert.assertTrue(successCode);
      Assert.assertTrue(hasException == sw.toString().toLowerCase().contains("exception"));
      return sw.toString();
    }
    numRetries++;
  }
  Assert.fail("Request failed after all retries");
  return null;
}