org.springframework.http.HttpEntity Java Examples

The following examples show how to use org.springframework.http.HttpEntity. 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: HomeController.java    From jVoiD with Apache License 2.0 8 votes vote down vote up
@RequestMapping("/order")
public @ResponseBody String orderProductNowById(@RequestParam("cartId") String cartId, @RequestParam("prodId") String productId) {
	RestTemplate restTemplate = new RestTemplate();
	HttpHeaders headers = new HttpHeaders();
	headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

	JSONObject jsonObj = new JSONObject();
	try {
		jsonObj.put("cartId", Integer.parseInt(cartId));
		jsonObj.put("productId", Integer.parseInt(productId));
		jsonObj.put("attributeId", 1);
		jsonObj.put("quantity", 1);
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	System.out.println("param jsonObj=>"+jsonObj.toString());
	
	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(ServerUris.QUOTE_SERVER_URI+URIConstants.ADD_PRODUCT_TO_CART)
	        .queryParam("params", jsonObj);	
	HttpEntity<?> entity = new HttpEntity<>(headers);
	HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class);
	return returnString.getBody();
}
 
Example #2
Source File: CorsAuthenticationTest.java    From camunda-bpm-platform with Apache License 2.0 7 votes vote down vote up
@Test
public void shouldPassAuthenticatedCorsRequest() {
  // given
  // cross origin but allowed through wildcard
  String origin = "http://other.origin";

  HttpHeaders headers = new HttpHeaders();
  headers.add(HttpHeaders.ORIGIN, origin);

  Group group = new GroupEntity("groupId");
  
  // create group
  processEngine.getIdentityService().saveGroup(new GroupEntity("groupId"));

  group.setName("updatedGroupName");

  // when
  ResponseEntity<String> response = authTestRestTemplate.exchange(CONTEXT_PATH + "/group/" + group.getId(), HttpMethod.PUT, new HttpEntity<>(group, headers),
      String.class);

  // then
  assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
  assertThat(response.getHeaders().getAccessControlAllowOrigin()).contains("*");
}
 
Example #3
Source File: CorsAuthenticationTest.java    From camunda-bpm-platform with Apache License 2.0 7 votes vote down vote up
@Test
public void shouldPassNonAuthenticatedPreflightRequest() {
  // given
  // cross origin but allowed through wildcard
  String origin = "http://other.origin";

  HttpHeaders headers = new HttpHeaders();
  headers.add(HttpHeaders.HOST, "localhost");
  headers.add(HttpHeaders.ORIGIN, origin);
  headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.PUT.name());
  headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, HttpHeaders.ORIGIN);

  // when
  ResponseEntity<String> response = testRestTemplate.exchange(CONTEXT_PATH + "/task", HttpMethod.OPTIONS, new HttpEntity<>(headers), String.class);

  // then
  assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
 
Example #4
Source File: RequestMappingHandlerAdapterIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void handleHttpEntity() throws Exception {
	Class<?>[] parameterTypes = new Class<?>[] {HttpEntity.class};

	request.addHeader("Content-Type", "text/plain; charset=utf-8");
	request.setContent("Hello Server".getBytes("UTF-8"));

	HandlerMethod handlerMethod = handlerMethod("handleHttpEntity", parameterTypes);

	ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod);

	assertNull(mav);
	assertEquals(HttpStatus.ACCEPTED.value(), response.getStatus());
	assertEquals("Handled requestBody=[Hello Server]", new String(response.getContentAsByteArray(), "UTF-8"));
	assertEquals("headerValue", response.getHeader("header"));
	// set because of @SesstionAttributes
	assertEquals("no-store", response.getHeader("Cache-Control"));
}
 
Example #5
Source File: MicrosoftTeamsNotifierTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void test_onClientApplicationDeRegisteredEvent_resolve() {
    InstanceDeregisteredEvent event = new InstanceDeregisteredEvent(instance.getId(), 1L);

    StepVerifier.create(notifier.doNotify(event, instance)).verifyComplete();

    ArgumentCaptor<HttpEntity<Message>> entity = ArgumentCaptor.forClass(HttpEntity.class);
    verify(mockRestTemplate).postForEntity(eq(URI.create("http://example.com")),
        entity.capture(),
        eq(Void.class)
    );

    assertThat(entity.getValue().getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
    assertMessage(entity.getValue().getBody(),
        notifier.getDeRegisteredTitle(),
        notifier.getMessageSummary(),
        String.format(notifier.getDeregisterActivitySubtitlePattern(),
            instance.getRegistration().getName(),
            instance.getId()
        )
    );
}
 
Example #6
Source File: RestTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void postForLocationEntityContentType() throws Exception {
	mockSentRequest(POST, "http://example.com");
	mockTextPlainHttpMessageConverter();
	mockResponseStatus(HttpStatus.OK);

	String helloWorld = "Hello World";
	HttpHeaders responseHeaders = new HttpHeaders();
	URI expected = new URI("http://example.com/hotels");
	responseHeaders.setLocation(expected);
	given(response.getHeaders()).willReturn(responseHeaders);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_PLAIN);
	HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);

	URI result = template.postForLocation("http://example.com", entity);
	assertEquals("Invalid POST result", expected, result);

	verify(response).close();
}
 
Example #7
Source File: CredHubCertificateTemplateUnitTests.java    From spring-credhub with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void bulkRegenerate() {
	Map<String, List<CredentialName>> expectedResponse = Collections.singletonMap(
			CredHubCertificateTemplate.REGENERATED_CREDENTIALS_RESPONSE_FIELD,
			Arrays.asList(new SimpleCredentialName("example-certificate1"),
					new SimpleCredentialName("example-certificate2")));

	Map<String, Object> request = new HashMap<String, Object>() {
		{
			put(CredHubCertificateTemplate.SIGNED_BY_REQUEST_FIELD, NAME.getName());
		}
	};

	given(this.restTemplate.exchange(eq(CredHubCertificateTemplate.BULK_REGENERATE_URL_PATH), eq(HttpMethod.POST),
			eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class)))
					.willReturn(new ResponseEntity<>(expectedResponse, HttpStatus.OK));

	List<CredentialName> response = this.credHubTemplate.regenerate(NAME);

	assertThat(response).isNotNull();
	assertThat(response)
			.isEqualTo(expectedResponse.get(CredHubCertificateTemplate.REGENERATED_CREDENTIALS_RESPONSE_FIELD));
}
 
Example #8
Source File: LetsChatNotifierTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void test_onApplicationEvent_resolve_with_custom_message() {
    notifier.setMessage("TEST");
    StepVerifier.create(notifier.notify(
        new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofDown())))
                .verifyComplete();
    clearInvocations(restTemplate);

    StepVerifier.create(
        notifier.notify(new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofUp())))
                .verifyComplete();

    HttpEntity<?> expected = expectedMessage("TEST");
    verify(restTemplate).exchange(eq(URI.create(String.format("%s/rooms/%s/messages", host, room))),
        eq(HttpMethod.POST), eq(expected), eq(Void.class));
}
 
Example #9
Source File: OauthResourceTokenConfig.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 本地没有公钥的时候,从服务器上获取
 * 需要进行 Basic 认证
 *
 * @return public key
 */
private String getKeyFromAuthorizationServer() {
    ObjectMapper objectMapper = new ObjectMapper();
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add(HttpHeaders.AUTHORIZATION, encodeClient());
    HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
    String pubKey = new RestTemplate()
        .getForObject(resourceServerProperties.getJwt().getKeyUri(), String.class, requestEntity);
    try {
        JSONObject body = objectMapper.readValue(pubKey, JSONObject.class);
        log.info("Get Key From Authorization Server.");
        return body.getStr("value");
    } catch (IOException e) {
        log.error("Get public key error: {}", e.getMessage());
    }
    return null;
}
 
Example #10
Source File: AddStaffServiceListener.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 用户赋权
 *
 * @return
 */
private void privilegeUserDefault(DataFlowContext dataFlowContext, JSONObject paramObj) {
    ResponseEntity responseEntity = null;
    AppService appService = DataFlowFactory.getService(dataFlowContext.getAppId(), ServiceCodeConstant.SERVICE_CODE_SAVE_USER_DEFAULT_PRIVILEGE);
    if (appService == null) {
        responseEntity = new ResponseEntity<String>("当前没有权限访问" + ServiceCodeConstant.SERVICE_CODE_SAVE_USER_DEFAULT_PRIVILEGE, HttpStatus.UNAUTHORIZED);
        dataFlowContext.setResponseEntity(responseEntity);
        return;
    }
    String requestUrl = appService.getUrl();
    HttpHeaders header = new HttpHeaders();
    header.add(CommonConstant.HTTP_SERVICE.toLowerCase(), ServiceCodeConstant.SERVICE_CODE_SAVE_USER_DEFAULT_PRIVILEGE);
    userBMOImpl.freshHttpHeader(header, dataFlowContext.getRequestCurrentHeaders());
    JSONObject paramInObj = new JSONObject();
    paramInObj.put("userId", paramObj.getString("userId"));
    paramInObj.put("storeTypeCd", paramObj.getString("storeTypeCd"));
    paramInObj.put("userFlag", "staff");
    HttpEntity<String> httpEntity = new HttpEntity<String>(paramInObj.toJSONString(), header);
    doRequest(dataFlowContext, appService, httpEntity);
    responseEntity = dataFlowContext.getResponseEntity();

    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        dataFlowContext.setResponseEntity(responseEntity);
    }
}
 
Example #11
Source File: JaxrsIntegrationTestBase.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void ableToPostWithHeader() {
  Person person = new Person();
  person.setName("person name");

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(APPLICATION_JSON);
  headers.add("prefix", "prefix  prefix");

  HttpEntity<Person> requestEntity = new HttpEntity<>(person, headers);
  for (String url : urls) {
    ResponseEntity<String> responseEntity = restTemplate
        .postForEntity(url + "saysomething", requestEntity, String.class);

    assertEquals("prefix  prefix person name", jsonBodyOf(responseEntity, String.class));
  }
}
 
Example #12
Source File: RestTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void postForLocationEntityContentType() throws Exception {
	mockSentRequest(POST, "https://example.com");
	mockTextPlainHttpMessageConverter();
	mockResponseStatus(HttpStatus.OK);

	String helloWorld = "Hello World";
	HttpHeaders responseHeaders = new HttpHeaders();
	URI expected = new URI("https://example.com/hotels");
	responseHeaders.setLocation(expected);
	given(response.getHeaders()).willReturn(responseHeaders);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_PLAIN);
	HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);

	URI result = template.postForLocation("https://example.com", entity);
	assertEquals("Invalid POST result", expected, result);

	verify(response).close();
}
 
Example #13
Source File: GrantByImplicitProviderTest.java    From demo-spring-boot-security-oauth2 with MIT License 6 votes vote down vote up
@Test
public void getJwtTokenByImplicitGrant() throws JsonParseException, JsonMappingException, IOException {
    String redirectUrl = "http://localhost:"+port+"/resources/user";
    ResponseEntity<String> response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port 
       + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}", null, String.class,redirectUrl);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    List<String> setCookie = response.getHeaders().get("Set-Cookie");
    String jSessionIdCookie = setCookie.get(0);
    String cookieValue = jSessionIdCookie.split(";")[0];

    HttpHeaders headers = new HttpHeaders();
    headers.add("Cookie", cookieValue);
    response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port 
            + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}&user_oauth_approval=true&authorize=Authorize",
            new HttpEntity<>(headers), String.class, redirectUrl);
    assertEquals(HttpStatus.FOUND, response.getStatusCode());
    assertNull(response.getBody());
    String location = response.getHeaders().get("Location").get(0);

    //FIXME: Is this a bug with redirect URL?
    location = location.replace("#", "?");

    response = new TestRestTemplate().getForEntity(location, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
}
 
Example #14
Source File: AsyncRestTemplateIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void exchangeGetCallback() throws Exception {
	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.set("MyHeader", "MyValue");
	HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
	ListenableFuture<ResponseEntity<String>> responseFuture =
			template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get");
	responseFuture.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
		@Override
		public void onSuccess(ResponseEntity<String> result) {
			assertEquals("Invalid content", helloWorld, result.getBody());
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	waitTillDone(responseFuture);
}
 
Example #15
Source File: TaskControllerIntTest.java    From taskana with Apache License 2.0 6 votes vote down vote up
/**
 * TSK-926: If Planned and Due Date is provided to create a task and not matching to service level
 * throw an exception One is calculated by other other date +- service level.
 */
@Test
void testCreateWithPlannedAndDueDate() {
  TaskRepresentationModel taskRepresentationModel = getTaskResourceSample();
  Instant now = Instant.now();
  taskRepresentationModel.setPlanned(now);
  taskRepresentationModel.setDue(now);

  ThrowingCallable httpCall =
      () ->
          template.exchange(
              restHelper.toUrl(Mapping.URL_TASKS),
              HttpMethod.POST,
              new HttpEntity<>(taskRepresentationModel, restHelper.getHeadersUser_1_1()),
              TASK_MODEL_TYPE);
  assertThatThrownBy(httpCall).isInstanceOf(HttpClientErrorException.class);
}
 
Example #16
Source File: CloudSalesOrderService.java    From cloud-espm-cloud-native with Apache License 2.0 6 votes vote down vote up
private String getTaxUrlFromDestinationService() {
	try {
		final DestinationService destination = getDestinationServiceDetails("destination");
		final String accessToken = getOAuthToken(destination);
		headers.set("Authorization", "Bearer " + accessToken);
		HttpEntity entity = new HttpEntity(headers);
		final String taxUrl = destination.uri + DESTINATION_PATH + taxDestination;
		final ResponseEntity<String> response = restTemplate.exchange(taxUrl, HttpMethod.GET, entity, String.class);
		final JsonNode root = mapper.readTree(response.getBody());
		final String texDestination = root.path("destinationConfiguration").path("URL").asText();
		return texDestination;
	} catch (IOException e) {
		logger.error("No proper destination Service available: {}", e.getMessage());

	}
	return "";
}
 
Example #17
Source File: BeanParamRestTemplateClient.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void testUpload() {
  BufferedInputStream bufferedInputStream0 = new BufferedInputStream(new ByteArrayInputStream("up0".getBytes()));
  BufferedInputStream bufferedInputStream1 = new BufferedInputStream(new ByteArrayInputStream("up1".getBytes()));
  BufferedInputStream bufferedInputStream2 = new BufferedInputStream(new ByteArrayInputStream("up2".getBytes()));

  HashMap<String, Object> formData = new HashMap<>();
  formData.put("up0", bufferedInputStream0);
  formData.put("up1", bufferedInputStream1);
  formData.put("up2", bufferedInputStream2);
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.MULTIPART_FORM_DATA);
  HttpEntity<Map<String, Object>> entity = new HttpEntity<>(formData, headers);

  String result = restTemplate.postForObject("cse://jaxrs/beanParamTest/upload?query=fromTemplate&extraQuery=ex",
      entity,
      String.class);
  TestMgr.check(
      "testBeanParameter=TestBeanParameterWithUpload{queryStr='fromTemplate'}|extraQuery=ex|up0=up0|up1=up1|up2=up2",
      result);
}
 
Example #18
Source File: AttachmentApi.java    From onboard with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/api/{companyId}/projects/{projectId}/attachments/{attachmentId}/download", method = RequestMethod.GET)
@ResponseBody
public HttpEntity<byte[]> downloadAttachment(@PathVariable("companyId") int companyId,
        @PathVariable("projectId") int projectId, @PathVariable("attachmentId") int attachmentId, HttpServletRequest request)
        throws IOException {
    String byteUri = String.format(ATTACHMENT_BYTE, companyId, projectId, attachmentId);
    String attachmentUri = String.format(ATTACHMENT_ID, companyId, projectId, attachmentId);
    byte[] bytes = netService.getForObject(byteUri, byte[].class);
    AttachmentDTO attachment = netService.getForObject(attachmentUri, AttachmentDTO.class);
    if (attachment == null || bytes == null) {
        throw new com.onboard.frontend.exception.ResourceNotFoundException();
    }
    HttpHeaders header = new HttpHeaders();
    String filename = new String(attachment.getName().getBytes("GB2312"), "ISO_8859_1");
    header.setContentDispositionFormData("attachment", filename);
    return new HttpEntity<byte[]>(bytes, header);
}
 
Example #19
Source File: MetricImporter.java    From SkaETL with Apache License 2.0 6 votes vote down vote up
private void sendToRegistry(String action) {
    if (registryConfiguration.getActive()) {
        RegistryWorker registry = null;
        try {
            registry = RegistryWorker.builder()
                    .workerType(WorkerType.METRIC_PROCESS)
                    .ip(InetAddress.getLocalHost().getHostName())
                    .name(InetAddress.getLocalHost().getHostName())
                    .port(processConfiguration.getPortClient())
                    .statusConsumerList(statusExecutor())
                    .build();
            RestTemplate restTemplate = new RestTemplate();
            HttpEntity<RegistryWorker> request = new HttpEntity<>(registry);
            String url = processConfiguration.getUrlRegistry();
            String res = restTemplate.postForObject(url + "/process/registry/" + action, request, String.class);
            log.debug("sendToRegistry result {}", res);
        } catch (Exception e) {
            log.error("Exception on sendToRegistry", e);
        }
    }
}
 
Example #20
Source File: RestfulTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublishContentIs10K() {
    MultiValueMap<String, String> eventData = new LinkedMultiValueMap<>();
    eventData.add("topic", this.topicName);
    eventData.add("content", get10KStr());

    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.APPLICATION_FORM_URLENCODED;
    headers.setContentType(type);
    headers.add("Accept", MediaType.APPLICATION_JSON.toString());

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(eventData, headers);
    ResponseEntity<SendResult> rsp = rest.postForEntity(url + "publish", request, SendResult.class);
    log.info("publish, status: " + rsp.getStatusCode() + " body: " + rsp.getBody());
    Assert.assertEquals(200, rsp.getStatusCodeValue());
    Assert.assertNotNull(rsp.getBody());
    Assert.assertTrue(rsp.getBody().getEventId().contains("-"));
}
 
Example #21
Source File: WorkerController.java    From DataLink with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/doEditLogback")
public String saveLogback(String workerId, String content) {
    logger.info("Receive a request to save logback.xml, with workerId " + workerId + "\r\n with content " + content);

    if (StringUtils.isBlank(content)) {
        return "content can not be null";
    }
    try {
        WorkerInfo workerInfo = workerService.getById(Long.valueOf(workerId));
        if (workerInfo != null) {
            String url = "http://" + workerInfo.getWorkerAddress() + ":" + workerInfo.getRestPort() + "/worker/doEditLogback/" + workerId;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            Map<String, String> map = new HashMap<>();
            map.put("content", content);
            HttpEntity request = new HttpEntity(map, headers);
            new RestTemplate(Lists.newArrayList(new FastJsonHttpMessageConverter())).postForObject(url, request, String.class);
            return "success";
        }
        return "fail";
    } catch (Exception e) {
        logger.info("request to save logback.xml error:", e);
        return e.getMessage();
    }
}
 
Example #22
Source File: IngredientServiceClient.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@HystrixCommand(fallbackMethod="getDefaultIngredients",
    commandProperties={
        @HystrixProperty(
            name="execution.isolation.thread.timeoutInMilliseconds",
            value="500"),
            @HystrixProperty(
                name="circuitBreaker.requestVolumeThreshold",
                value="30"),
            @HystrixProperty(
                name="circuitBreaker.errorThresholdPercentage",
                value="25"),
            @HystrixProperty(
                name="metrics.rollingStats.timeInMilliseconds",
                value="20000"),
            @HystrixProperty(
                name="circuitBreaker.sleepWindowInMilliseconds",
                value="60000")
    })
public Iterable<Ingredient> getAllIngredients() {
  ParameterizedTypeReference<List<Ingredient>> stringList =
      new ParameterizedTypeReference<List<Ingredient>>() {};
  return rest.exchange(
      "http://ingredient-service/ingredients", HttpMethod.GET,
      HttpEntity.EMPTY, stringList).getBody();
}
 
Example #23
Source File: RestApiSecurityApplicationTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
public void testCmmnRestApiIntegrationWithAuthentication() {
    String processDefinitionsUrl = "http://localhost:" + serverPort + "/cmmn-api/cmmn-repository/case-definitions";

    HttpEntity<?> request = new HttpEntity<>(createHeaders("filiphr", "password"));
    ResponseEntity<DataResponse<CaseDefinitionResponse>> response = restTemplate
        .exchange(processDefinitionsUrl, HttpMethod.GET, request, new ParameterizedTypeReference<DataResponse<CaseDefinitionResponse>>() {
        });

    assertThat(response.getStatusCode())
        .as("Status code")
        .isEqualTo(HttpStatus.OK);
    DataResponse<CaseDefinitionResponse> caseDefinitions = response.getBody();
    assertThat(caseDefinitions).isNotNull();
    CaseDefinitionResponse defResponse = caseDefinitions.getData().get(0);
    assertThat(defResponse.getKey()).isEqualTo("case1");
    assertThat(defResponse.getUrl()).startsWith("http://localhost:" + serverPort + "/cmmn-api/cmmn-repository/case-definitions/");
}
 
Example #24
Source File: SMPPrimaryStorageSimulator.java    From zstack with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value=KvmBackend.DELETE_BITS_PATH, method= RequestMethod.POST)
public @ResponseBody
String deleteBits(HttpEntity<String> entity) {
    DeleteBitsCmd cmd = JSONObjectUtil.toObject(entity.getBody(), DeleteBitsCmd.class);
    config.deleteBitsCmds.add(cmd);
    reply(entity, new AgentRsp());
    return null;
}
 
Example #25
Source File: WorkbasketControllerIntTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void testMarkWorkbasketForDeletionAsBusinessAdminWithoutExplicitReadPermission() {

  String workbasketID = "WBI:100000000000000000000000000000000005";

  ResponseEntity<?> response =
      TEMPLATE.exchange(
          restHelper.toUrl(Mapping.URL_WORKBASKET_ID, workbasketID),
          HttpMethod.DELETE,
          new HttpEntity<>(restHelper.getHeadersBusinessAdmin()),
          Void.class);
  assertThat(response.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED);
}
 
Example #26
Source File: SonarServerConfigurationServiceTest.java    From code-quality-game with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testConnectsToServer() {
    final SonarServerStatus body = new SonarServerStatus(SonarServerStatus.Key.UP);
    when(restTemplateMock.exchange(any(String.class), eq(HttpMethod.GET), any(HttpEntity.class), eq(SonarServerStatus.class)))
            .thenReturn(new ResponseEntity<>(body, HttpStatus.OK));
    final SonarServerStatus serverStatus = configurationService.checkServerDetails(config);
    assertEquals(SonarServerStatus.STATUS_UP, serverStatus.getStatus());
}
 
Example #27
Source File: KVMSimulatorController.java    From zstack with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value=KVMConstant.KVM_ATTACH_ISO_PATH, method=RequestMethod.POST)
public @ResponseBody String attachIso(HttpServletRequest req) {
    HttpEntity<String> entity = restf.httpServletRequestToHttpEntity(req);
    AttachIsoCmd cmd = JSONObjectUtil.toObject(entity.getBody(), AttachIsoCmd.class);
    config.attachIsoCmds.add(cmd);
    reply(entity, new AttachIsoRsp());
    return null;
}
 
Example #28
Source File: HttpEntityMethodProcessorMockTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
	dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
	dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

	messageConverter = mock(HttpMessageConverter.class);
	given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));

	processor = new HttpEntityMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(messageConverter));
	reset(messageConverter);

	Method handle1 = getClass().getMethod("handle1", HttpEntity.class, ResponseEntity.class, Integer.TYPE, RequestEntity.class);
	paramHttpEntity = new MethodParameter(handle1, 0);
	paramRequestEntity = new MethodParameter(handle1, 3);
	paramResponseEntity = new MethodParameter(handle1, 1);
	paramInt = new MethodParameter(handle1, 2);
	returnTypeResponseEntity = new MethodParameter(handle1, -1);
	returnTypeResponseEntityProduces = new MethodParameter(getClass().getMethod("handle4"), -1);
	returnTypeHttpEntity = new MethodParameter(getClass().getMethod("handle2", HttpEntity.class), -1);
	returnTypeHttpEntitySubclass = new MethodParameter(getClass().getMethod("handle2x", HttpEntity.class), -1);
	returnTypeInt = new MethodParameter(getClass().getMethod("handle3"), -1);

	mavContainer = new ModelAndViewContainer();
	servletRequest = new MockHttpServletRequest("GET", "/foo");
	servletResponse = new MockHttpServletResponse();
	webRequest = new ServletWebRequest(servletRequest, servletResponse);
}
 
Example #29
Source File: FlowableIdmApplicationSecurityTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
public void idmUserShouldBeAbleToAccessInternalRestApp() {
    String authenticateUrl = "http://localhost:" + serverPort + "/flowable-idm/app/rest/admin/groups";
    HttpHeaders headers = new HttpHeaders();
    headers.set(HttpHeaders.COOKIE, rememberMeCookie("idm", "test-idm-value"));
    HttpEntity<?> request = new HttpEntity<>(headers);
    ResponseEntity<Object> result = restTemplate.exchange(authenticateUrl, HttpMethod.GET, request, Object.class);

    assertThat(result.getStatusCode())
        .as("GET App Groups")
        .isEqualTo(HttpStatus.OK);
}
 
Example #30
Source File: TaskControllerIntTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void testGetAllTasksWithAdminRole() {
  ResponseEntity<TaskanaPagedModel<TaskSummaryRepresentationModel>> response =
      TEMPLATE.exchange(
          restHelper.toUrl(Mapping.URL_TASKS),
          HttpMethod.GET,
          new HttpEntity<>(restHelper.getHeadersAdmin()),
          TASK_SUMMARY_PAGE_MODEL_TYPE);
  assertThat(response.getBody()).isNotNull();
  assertThat((response.getBody()).getLink(IanaLinkRelations.SELF)).isNotNull();
  assertThat(response.getBody().getContent()).hasSize(73);
}