Java Code Examples for org.restlet.Response

The following examples show how to use org.restlet.Response. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@Test
@Ignore
public void asyncMethodReturnsSuccessStatus() throws Exception {

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

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

  classUnderTest = new GeoWaveOperationServiceWrapper(operation, null);
  classUnderTest.setResponse(new Response(null));
  classUnderTest.restPost(null);

  // TODO: Returns 500. Error Caught at
  // "final Context appContext = Application.getCurrent().getContext();"
  Assert.assertEquals(
      successStatusIs200,
      classUnderTest.getResponse().getStatus().equals(Status.SUCCESS_OK));
}
 
Example 2
Source Project: scava   Source File: ApiHelper.java    License: 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
@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 4
Source Project: scava   Source File: TestProjectImportResource.java    License: 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 5
Source Project: container   Source File: ExceptionProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {

    ExceptionProcessor.LOG.debug("Exception handling...");

    final Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);

    if (exchange.getIn().getBody() instanceof ParseException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity("JSON is not valid: " + exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    } else if (exchange.getIn().getBody() instanceof NullPointerException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity("Needed information not specified.", MediaType.TEXT_ALL);
    } else if (exchange.getIn().getBody() instanceof ApplicationBusExternalException) {
        response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        response.setEntity(exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    } else if (exchange.getIn().getBody() instanceof ApplicationBusInternalException) {
        response.setStatus(Status.SERVER_ERROR_INTERNAL);
        response.setEntity(exchange.getIn().getBody(String.class), MediaType.TEXT_ALL);
    }

    exchange.getOut().setBody(response);
}
 
Example 6
Source Project: attic-polygene-java   Source File: RootResource.java    License: Apache License 2.0 6 votes vote down vote up
@SubResource
public void administration()
{
    ChallengeResponse challenge = Request.getCurrent().getChallengeResponse();
    if( challenge == null )
    {
        Response.getCurrent()
            .setChallengeRequests( Collections.singletonList( new ChallengeRequest( ChallengeScheme.HTTP_BASIC, "Forum" ) ) );
        throw new ResourceException( Status.CLIENT_ERROR_UNAUTHORIZED );
    }

    User user = select( Users.class, Users.USERS_ID ).userNamed( challenge.getIdentifier() );
    if( user == null || !user.isCorrectPassword( new String( challenge.getSecret() ) ) )
    {
        throw new ResourceException( Status.CLIENT_ERROR_UNAUTHORIZED );
    }

    current().select( user );

    subResource( AdministrationResource.class );
}
 
Example 7
Source Project: attic-polygene-java   Source File: ContextResource.java    License: Apache License 2.0 6 votes vote down vote up
private boolean shouldShowCommandForm( Method interactionMethod )
{
    // Show form on GET/HEAD
    if( Request.getCurrent().getMethod().isSafe() )
    {
        return true;
    }

    if( interactionMethod.getParameterTypes().length > 0 )
    {
        return !( interactionMethod.getParameterTypes()[ 0 ].equals( Response.class ) || Request.getCurrent()
            .getEntity()
            .isAvailable() || Request.getCurrent().getEntityAsText() != null || Request.getCurrent()
                                                                                    .getResourceRef()
                                                                                    .getQuery() != null );
    }

    return false;
}
 
Example 8
Source Project: attic-polygene-java   Source File: LinksResponseWriter.java    License: Apache License 2.0 6 votes vote down vote up
private Representation createTextHtmlRepresentation( final Object result, final Response response )
{
    return new WriterRepresentation( MediaType.TEXT_HTML )
                {
                    @Override
                    public void write( Writer writer )
                        throws IOException
                    {
                        Map<String, Object> context = new HashMap<>();
                        context.put( "request", response.getRequest() );
                        context.put( "response", response );
                        context.put( "result", result );
                        try
                        {
                            cfg.getTemplate( "links.htm" ).process( context, writer );
                        }
                        catch( TemplateException e )
                        {
                            throw new IOException( e );
                        }
                    }
                };
}
 
Example 9
Source Project: attic-polygene-java   Source File: LinksResponseWriter.java    License: Apache License 2.0 6 votes vote down vote up
private Representation createAtomRepresentation( final Object result, final Response response )
{
    return new WriterRepresentation( MediaType.APPLICATION_ATOM )
    {
        @Override
        public void write( Writer writer )
            throws IOException
        {
            Map<String, Object> context = new HashMap<>();
            context.put( "request", response.getRequest() );
            context.put( "response", response );
            context.put( "result", result );
            try
            {
                cfg.getTemplate( "links.atom" ).process( context, writer );
            }
            catch( TemplateException e )
            {
                throw new IOException( e );
            }
        }
    };
}
 
Example 10
Source Project: attic-polygene-java   Source File: DefaultResponseReader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object readResponse( Response response, Class<?> resultType ) throws ResourceException
{
    if( MediaType.APPLICATION_JSON.equals( response.getEntity().getMediaType() ) )
    {
        if( resultType.equals( String.class ) || Number.class.isAssignableFrom( resultType ) )
        {
            try
            {
                return jsonDeserializer.deserialize( module, resultType, response.getEntityAsText() );
            }
            catch( Exception e )
            {
                throw new ResourceException( e );
            }
        }
    }
    return null;
}
 
Example 11
Source Project: attic-polygene-java   Source File: ContextResourceClient.java    License: Apache License 2.0 6 votes vote down vote up
public <T> ContextResourceClient onResource( final ResultHandler<T> handler)
{
    resourceHandler = new ResponseHandler()
    {
        @Override
        public HandlerCommand handleResponse( Response response, ContextResourceClient client )
        {
            final Class<T> resultType = (Class<T>) Classes.RAW_CLASS.apply(( (ParameterizedType) handler.getClass().getGenericInterfaces()[ 0 ] ).getActualTypeArguments()[0]);
            T result = contextResourceFactory.readResponse( response, resultType );

            if (result instanceof Resource)
            {
                resource = (Resource) result;
            }

            return handler.handleResult( result, client );
        }
    };
    return this;
}
 
Example 12
/**
 * Overridden method from super class.  
 */
@Override
public int verify(Request request, Response response) {
	
	ChallengeResponse cr = request.getChallengeResponse();
	
	if (cr == null){
		logger.info("Missing credentials in request from a client with IP " 
									+ request.getClientInfo().getAddress() + ".");
		return Verifier.RESULT_MISSING;
	}
	
	String objectId = cr.getIdentifier();
	String password = new String(cr.getSecret());
	
	if (communicationManager.isConnected(objectId)){
		// if the client is already connected, just verify the password
		if (!communicationManager.verifyPassword(objectId, password)){
			logger.info("Invalid credentials in request from a client with IP " 
					+ request.getClientInfo().getAddress() + ".");
			return Verifier.RESULT_INVALID;
		}
	} else {
		// if not, establish a connection
		StatusMessage statusMessage = communicationManager.establishConnection(objectId, password); 
		if (statusMessage.isError()){
			logger.info("Invalid credentials in request from a client with IP " 
										+ request.getClientInfo().getAddress() + ".");
			return Verifier.RESULT_INVALID;
		}
	}
	
	logger.info("Valid credentials received from a client with IP " + request.getClientInfo().getAddress() + ".");
	return Verifier.RESULT_VALID;
}
 
Example 13
Source Project: scava   Source File: ProjectAnalysisTests.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Ignore
@Test
public void testAllMetricsOnASM() throws Exception {
	String analysisTaskId = "AsmTask";
	String projectId = "asm";

	// Set token
	// TODO: Valid GitLab token here
	Response res = helper.setProperty("gitlabToken", "-------------------------");
	assertEquals(201, res.getStatus().getCode());

	// Import project
	res = helper.importProject("https://gitlab.ow2.org/asm/asm");
	assertEquals(201, res.getStatus().getCode());

	// Create task
	List<MetricProviderDTO> providers = helper.getMetricProviders();
	List<String> metricProviders = new ArrayList<String>();
	for (MetricProviderDTO provider : providers) {
		metricProviders.add(provider.getMetricProviderId());
	}

	res = helper.createTask(projectId, analysisTaskId, "ASM Task", AnalysisExecutionMode.SINGLE_EXECUTION,
			metricProviders, "01/03/2019", "05/03/2019");
	assertEquals(201, res.getStatus().getCode());

	// Start task
	res = helper.startTask(analysisTaskId);
	assertEquals(200, res.getStatus().getCode());

	// Start execution
	Project project = platform.getProjectRepositoryManager().getProjectRepository().getProjects()
			.findOneByShortName(projectId);
	platform.getAnalysisRepositoryManager().getWorkerService().assignTask(analysisTaskId, WORKER_ID);
	ProjectAnalyser projectAnalyser = new ProjectAnalyser(platform);
	projectAnalyser.executeAnalyse(analysisTaskId, WORKER_ID);
	platform.getAnalysisRepositoryManager().getWorkerService().completeTask(WORKER_ID);

	assertFalse(project.getExecutionInformation().getInErrorState());
}
 
Example 14
@Test
public void should_set_response_status_to_423_when_catching_a_LockedResourceException() throws Exception {
    workspaceServerResource.setResponse(new Response(null));
    workspaceServerResource.doCatch(new ResourceException(new LockedResourceException()));

    final Response response = workspaceServerResource.getResponse();
    assertThat(response).isNotNull();
    final Status status = response.getStatus();
    assertThat(status).isNotNull();
    assertThat(status.getCode()).isEqualTo(Status.CLIENT_ERROR_LOCKED.getCode());
}
 
Example 15
Source Project: scava   Source File: ApiHelper.java    License: 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 16
Source Project: helix   Source File: TestClusterManagementWebapp.java    License: 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 17
Source Project: ontopia   Source File: PagedResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
private int getIntHeader(Response response, String header) {
	try {
		return Integer.parseInt(response.getHeaders().getFirstValue(header));
	} catch (NumberFormatException nfe) {
		return -1;
	}
}
 
Example 18
Source Project: scava   Source File: TestProjectResource.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGet() {
	Client client = new Client(Protocol.HTTP);
	Request request = new Request(Method.GET, "http://localhost:8182/projects/p/ant");
	Response response = client.handle(request);
	
	validateResponse(response, 200);
	
	// TODO: check the JSON
}
 
Example 19
Source Project: ipst   Source File: ITeslaRules.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void init(Context context, Request request, Response response) {
    super.init(context, request, response);

    algoType = (String)getRequest().getAttributes().get("algoType");
    contingencyId = (String)getRequest().getAttributes().get("contingencyId");
    indexType = (String)getRequest().getAttributes().get("indexType");
}
 
Example 20
Source Project: uReplicator   Source File: TestAdminManagement.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPostRebalance() {
  Request request = ManagerRequestURLBuilder.baseUrl(REQUEST_URL).postInstanceRebalance();
  Response response = HTTP_CLIENT.handle(request);
  String responseString = response.getEntityAsText();
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(responseString, "{\"opt\":\"force_rebalance\",\"status\":200}");
}
 
Example 21
Source Project: uReplicator   Source File: TestAdminManagement.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPostControllerRebalance() {
  Request request = ManagerRequestURLBuilder.baseUrl(REQUEST_URL).postSetControllerRebalance(true);
  Response response = HTTP_CLIENT.handle(request);
  String responseString = response.getEntityAsText();
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(responseString, "{\"execution\":{},\"managerAutoscaling\":true,\"status\":{}}");
  request = ManagerRequestURLBuilder.baseUrl(REQUEST_URL).postSetControllerRebalance("sjc1a", "sjc1-agg1", true);
  response = HTTP_CLIENT.handle(request);
  responseString = response.getEntityAsText();
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(responseString, "{\"execution\":{},\"managerAutoscaling\":true,\"status\":{}}");
}
 
Example 22
Source Project: uReplicator   Source File: TestAdminManagement.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetControllerRebalance() {
  Request request = ManagerRequestURLBuilder.baseUrl(REQUEST_URL).getControllerRebalanceStatus();
  Response response = HTTP_CLIENT.handle(request);
  String responseString = response.getEntityAsText();
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(responseString, "{}");
}
 
Example 23
Source Project: FoxBPM   Source File: FoxbpmStatusService.java    License: Apache License 2.0 5 votes vote down vote up
public Representation getRepresentation(Status status, Request request, Response response) {
	if (status != null && status.isError()) {
		RestError error = new RestError();
		error.setStatusCode(status.getCode());
		error.setErrorMessage(status.getDescription());
		return new JacksonRepresentation<RestError>(error);
	} else {
		return super.getRepresentation(status, request, response);
	}
}
 
Example 24
Source Project: attic-polygene-java   Source File: PolygeneEntityRestlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle( Request request, Response response )
{
    try
    {
        super.handle( request, response );
        Method method = request.getMethod();
        if( method.equals( Method.GET ) )
        {
            get( request, response );
        }
        if( method.equals( Method.DELETE ) )
        {
            delete( request, response );
        }
        if( method.equals( Method.POST ) )
        {
            post( request, response );
        }
        if( method.equals( Method.PUT ) )
        {
            put( request, response );
        }
    }
    catch( RuntimeException e )
    {
        e.printStackTrace();
        throw e;
    }
}
 
Example 25
@Test
public void testPost() {
  EasyMock.reset(_helixMirrorMakerManager);

  // input validation
  Request request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .postBlacklistRequestUrl("testTopic", "2", null);
  Response response = RestTestBase.HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.CLIENT_ERROR_BAD_REQUEST);
  Assert.assertEquals(response.getEntityAsText(), "Invalid parameter opt");


  request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .postBlacklistRequestUrl("testTopic", "t", null);
  response = RestTestBase.HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.CLIENT_ERROR_BAD_REQUEST);
  Assert.assertEquals(response.getEntityAsText(), "Parameter partition should be Integer");


  _helixMirrorMakerManager.updateTopicPartitionStateInMirrorMaker("testTopic", 2, Constants.HELIX_ONLINE_STATE);
  EasyMock.expectLastCall();

  request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .postBlacklistRequestUrl("testTopic", "2", "whitelist");
  response = RestTestBase.HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(response.getEntityAsText(), "OK");

  _helixMirrorMakerManager.updateTopicPartitionStateInMirrorMaker("testTopic", 3,Constants.HELIX_OFFLINE_STATE);
  EasyMock.expectLastCall();

  request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .postBlacklistRequestUrl("testTopic", "3", "blacklist");
  response = RestTestBase.HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(response.getEntityAsText(), "OK");
}
 
Example 26
Source Project: uReplicator   Source File: AdminRestletResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetControllerWorkload() {
  EasyMock.reset(_helixMirrorMakerManager);
  EasyMock.expect(_helixMirrorMakerManager.getCurrentServingInstance()).andReturn(fakeItphList);
  EasyMock.expect(_helixMirrorMakerManager.getWorkloadInfoRetriever()).andReturn(_workloadInfoRetriever).anyTimes();

  EasyMock.expect(_workloadInfoRetriever.isInitialized()).andReturn(true);
  EasyMock.expect(_workloadInfoRetriever.topicWorkload(fakeTopics.get(0))).andReturn(fakeWorkload1).times(2);
  EasyMock.expect(_workloadInfoRetriever.topicWorkload(fakeTopics.get(1))).andReturn(fakeWorkload2).times(2);

  EasyMock.expect(_helixMirrorMakerManager.calculateLagTime(faketp1)).andReturn(null);
  EasyMock.expect(_helixMirrorMakerManager.calculateLagTime(faketp2)).andReturn(null);
  EasyMock.expect(_helixMirrorMakerManager.calculateLagTime(faketp3)).andReturn(null);
  faketplag.setLagTime(1243L);
  EasyMock.expect(_helixMirrorMakerManager.calculateLagTime(faketp4)).andReturn(faketplag);

  EasyMock.expect(_helixMirrorMakerManager.getMaxDedicatedInstancesRatio()).andReturn(0.2);
  EasyMock.expect(_helixMirrorMakerManager.getMaxWorkloadPerWorkerBytes()).andReturn(700.0);


  EasyMock.replay(_helixMirrorMakerManager, _workloadInfoRetriever);


  Request request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .getWorkloadInfoUrl();
  Response response = RestTestBase.HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);

  ControllerWorkloadInfo controllerWorkloadInfo = JSONObject.parseObject(response.getEntityAsText(), ControllerWorkloadInfo.class);
  Assert.assertEquals((int) controllerWorkloadInfo.getTopicWorkload().getBytesPerSecond(), 1264);

  Assert.assertEquals(controllerWorkloadInfo.getWorkerInstances().size(), 2);
  Assert.assertEquals(controllerWorkloadInfo.getNumOfLaggingWorkers(), 1);
  Assert.assertEquals(controllerWorkloadInfo.getNumOfExpectedWorkers(), 4);
}
 
Example 27
Source Project: uReplicator   Source File: ControllerStarterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPost() {
  // Create topic
  Request request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .getTopicCreationRequestUrl("testTopic1", 16);
  Response response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(response.getEntityAsText(),
      "Successfully add new topic: {topic: testTopic1, partition: 16, pipeline: null}");
  Assert.assertTrue(ZK_CLIENT.exists("/" + HELIX_CLUSTER_NAME + "/CONFIGS/RESOURCE/testTopic1"));

  // Create existed topic
  request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .getTopicCreationRequestUrl("testTopic1", 16);
  response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.CLIENT_ERROR_NOT_FOUND);
  Assert.assertEquals(response.getEntityAsText(),
      "Failed to add new topic: testTopic1, it is already existed!");

  // Delete topic
  request =
      ControllerRequestURLBuilder.baseUrl(REQUEST_URL).getTopicDeleteRequestUrl("testTopic1");
  response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(response.getEntityAsText(),
      "Successfully finished delete topic: testTopic1");

}
 
Example 28
Source Project: helix   Source File: TestHelixAdminScenariosRest.java    License: 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 29
Source Project: uReplicator   Source File: ControllerStarterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDelete() {
  Request request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .getTopicCreationRequestUrl("testTopic3", 8);
  Response response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(response.getEntityAsText(),
      "Successfully add new topic: {topic: testTopic3, partition: 8, pipeline: null}");
  Assert.assertTrue(ZK_CLIENT.exists("/" + HELIX_CLUSTER_NAME + "/CONFIGS/RESOURCE/testTopic3"));

  request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .getTopicExternalViewRequestUrl("testTopic3");
  response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);

  request =
      ControllerRequestURLBuilder.baseUrl(REQUEST_URL).getTopicDeleteRequestUrl("testTopic3");
  response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(response.getEntityAsText(),
      "Successfully finished delete topic: testTopic3");

  request =
      ControllerRequestURLBuilder.baseUrl(REQUEST_URL).getTopicDeleteRequestUrl("testTopic4");
  response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.CLIENT_ERROR_NOT_FOUND);
  Assert.assertEquals(response.getEntityAsText(),
      "Failed to delete not existed topic: testTopic4");

  request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .getTopicExternalViewRequestUrl("testTopic3");
  response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.CLIENT_ERROR_NOT_FOUND);

}
 
Example 30
@Test
public void testGet() {
  // Get call
  Request request = ControllerRequestURLBuilder.baseUrl(REQUEST_URL)
      .getNoProgressRequestUrl();
  Response response = HTTP_CLIENT.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Assert.assertEquals(response.getEntityAsText(), "{}");
  System.out.println(response.getEntityAsText());
}