Exemplo n.º 1
1
 public static List<User> all() {
   login();
   return Arrays.asList(
       template
           .exchange(endpoint, HttpMethod.GET, new HttpEntity<>(null, credentials()), User[].class)
           .getBody());
 }
  @Test
  public void testCreateZoneWithNonUniqueSubdomain() {
    IdentityZone idZone1 = new IdentityZone();
    String id1 = UUID.randomUUID().toString();
    idZone1.setId(id1);
    idZone1.setSubdomain(id1 + "non-unique");
    idZone1.setName("testCreateZone() " + id1);
    ResponseEntity<Void> response1 =
        client.exchange(
            serverRunning.getUrl("/identity-zones"),
            HttpMethod.POST,
            new HttpEntity<>(idZone1),
            new ParameterizedTypeReference<Void>() {},
            id1);
    assertEquals(HttpStatus.CREATED, response1.getStatusCode());

    IdentityZone idZone2 = new IdentityZone();
    String id2 = UUID.randomUUID().toString();
    idZone2.setId(id2);
    idZone2.setSubdomain(id1 + "non-unique");
    idZone2.setName("testCreateZone() " + id2);
    ResponseEntity<Map<String, String>> response2 =
        client.exchange(
            serverRunning.getUrl("/identity-zones"),
            HttpMethod.POST,
            new HttpEntity<>(idZone2),
            new ParameterizedTypeReference<Map<String, String>>() {},
            id2);
    assertEquals(HttpStatus.CONFLICT, response2.getStatusCode());
    Assert.assertTrue(
        response2.getBody().get("error_description").toLowerCase().contains("subdomain"));
  }
  @RequestMapping("/{userPseudo}/validateStep4")
  public ResponseEntity<Void> validateStep4(
      @PathVariable("userPseudo") String userPseudo,
      @RequestParam("userHostAndPort") String userHostAndPort) {
    log.info("Validation step 4 for player {} with data {}", userPseudo, userHostAndPort);

    ResponseEntity<Void> result = new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);

    String url = "http://" + userHostAndPort + "/zen/env";

    ResponseEntity<String> responseEntityShouldFail =
        restTemplate.exchange(
            url, HttpMethod.GET, new HttpEntity<>(new HttpHeaders()), String.class);

    byte[] encodedAuth = Base64.encodeBase64("zenika:technozaure".getBytes());
    String authHeader = "Basic " + new String(encodedAuth);

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.set("Authorization", authHeader);
    HttpEntity<String> entity = new HttpEntity<>(headers);

    ResponseEntity<String> responseEntityShouldSucceed =
        restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

    if (responseEntityShouldFail.getStatusCode() != HttpStatus.OK
        && responseEntityShouldSucceed.getStatusCode() == HttpStatus.OK) {
      gameStepRepository.save(new GameStep(userPseudo, Step._4));
      result = new ResponseEntity<Void>(HttpStatus.OK);
      broadcastGameStatus();
    }

    return result;
  }
 private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) {
   String baseUrl = "http://localhost:" + this.context.getEmbeddedServletContainer().getPort();
   RestTemplate rest = new TestRestTemplate();
   // First, verify the web endpoint can't be reached
   assertEndpointUnauthorized(baseUrl, rest);
   // Since we can't reach it, need to collect an authorization token
   HttpHeaders headers = getHeaders(config);
   String url = baseUrl + "/oauth/token";
   JsonNode tokenResponse =
       rest.postForObject(
           url, new HttpEntity<MultiValueMap<String, Object>>(getBody(), headers), JsonNode.class);
   String authorizationToken = tokenResponse.findValue("access_token").asText();
   String tokenType = tokenResponse.findValue("token_type").asText();
   String scope = tokenResponse.findValues("scope").get(0).toString();
   assertThat(tokenType, equalTo("bearer"));
   assertThat(scope, equalTo("\"read\""));
   // Now we should be able to see that endpoint.
   headers.set("Authorization", "BEARER " + authorizationToken);
   ResponseEntity<String> securedResponse =
       rest.exchange(
           new RequestEntity<Void>(headers, HttpMethod.GET, URI.create(baseUrl + "/securedFind")),
           String.class);
   assertThat(securedResponse.getStatusCode(), equalTo(HttpStatus.OK));
   assertThat(
       securedResponse.getBody(),
       equalTo("You reached an endpoint " + "secured by Spring Security OAuth2"));
   ResponseEntity<String> entity =
       rest.exchange(
           new RequestEntity<Void>(headers, HttpMethod.POST, URI.create(baseUrl + "/securedSave")),
           String.class);
   assertThat(entity.getStatusCode(), equalTo(finalStatus));
 }
Exemplo n.º 5
0
  @Bean
  public Token getToken() {
    Token token;

    String creds = authUser + ":" + authPassword;
    byte[] credsBytes = creds.getBytes();
    byte[] credsB64 = Base64.getEncoder().encode(credsBytes);

    String credsStr = new String(credsB64);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + credsStr);
    headers.add("Content-Type", "application/x-www-form-urlencoded");
    headers.add("Accept", "application/json");
    headers.add("Accept-Charset", "UTF-8"); // не работает !

    HttpEntity<String> request = new HttpEntity<String>(authParam, headers);
    log.info("Request token from server...");
    try {
      ResponseEntity resp = rest.exchange(authUri, HttpMethod.POST, request, Token.class);
      token = (Token) (resp.getBody());
    } catch (HttpClientErrorException e) {
      log.error(e.getMessage());
      token = new Token();
    }
    log.debug("Token=" + token.access_token);
    log.info("End of request token from server...");
    return token;
  }
Exemplo n.º 6
0
 public static User byId(String username) {
   login();
   return template
       .exchange(
           endpoint + username, HttpMethod.GET, new HttpEntity<>(null, credentials()), User.class)
       .getBody();
 }
  public Map<String, Map<String, List<String>>>
      getMapOfSenderAndRecieverValidationObjectivesWithReferenceFiles() {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<GithubResponseWrapper> responseEntity =
        restTemplate.exchange(
            GITHUB_URL,
            HttpMethod.GET,
            null,
            new ParameterizedTypeReference<GithubResponseWrapper>() {});

    Map<String, Map<String, List<String>>> messageTypeValidationObjectiveReferenceFilesMap =
        new HashMap<>();
    for (TestDataTreeWrapper testDataTreeWrapper : responseEntity.getBody().getTree()) {
      if (!(testDataTreeWrapper.getPath().equalsIgnoreCase("license")
          || testDataTreeWrapper.getPath().equalsIgnoreCase("README.md"))) {
        if (isMessageTypeInMap(
            messageTypeValidationObjectiveReferenceFilesMap, testDataTreeWrapper)) {
          if (isValidationObjectiveInMap(
              messageTypeValidationObjectiveReferenceFilesMap, testDataTreeWrapper)) {
            addReferenceFileNameToListInValidationObjectiveMap(
                messageTypeValidationObjectiveReferenceFilesMap, testDataTreeWrapper);
          } else {
            addValidationObjectiveToMap(
                messageTypeValidationObjectiveReferenceFilesMap, testDataTreeWrapper);
          }
        } else {
          addMessageTypeToMap(messageTypeValidationObjectiveReferenceFilesMap, testDataTreeWrapper);
        }
      }
    }
    return messageTypeValidationObjectiveReferenceFilesMap;
  }
    @Override
    protected List<State> doInBackground(Void... params) {
      try {
        // The URL for making the GET request
        final String url = getString(R.string.base_uri) + "/states";

        // Set the Accept header for "application/json"
        HttpHeaders requestHeaders = new HttpHeaders();
        List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
        acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
        requestHeaders.setAccept(acceptableMediaTypes);

        // Populate the headers in an HttpEntity object to use for the request
        HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

        // Create a new RestTemplate instance
        RestTemplate restTemplate = new RestTemplate();

        // Perform the HTTP GET request
        ResponseEntity<State[]> responseEntity =
            restTemplate.exchange(url, HttpMethod.GET, requestEntity, State[].class);

        // convert the array to a list and return it
        return Arrays.asList(responseEntity.getBody());
      } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
      }

      return null;
    }
 public JHttpResponse execute(JHttpEndpoint endpoint) {
   URI endpointURI = endpoint.getURI();
   RequestEntity requestEntity = mapToRequestEntity(endpointURI);
   ResponseEntity responseEntity =
       restTemplate.exchange(endpointURI, HttpMethod.GET, requestEntity, byte[].class);
   return mapToJHttpResponse(responseEntity);
 }
Exemplo n.º 10
0
  @Override
  public OrderDetailDTO payComplete(AliPayNotifyDTO notify) throws ApiLogicException {
    ResponseEntity<Response<OrderDetailDTO>> responseEntity;
    try {
      responseEntity =
          restTemplate.exchange(
              this.buildBizAppURI(
                  APPURIConstant.Order.REQUEST_MAPPING,
                  APPURIConstant.Order.REQUEST_MAPPING_PAY_BACK),
              HttpMethod.POST,
              new HttpEntity<AliPayNotifyDTO>(notify),
              new ParameterizedTypeReference<Response<OrderDetailDTO>>() {});
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      throw new ApiLogicException("未找到订单", HttpStatus.BAD_REQUEST);
    }

    Response<OrderDetailDTO> response = responseEntity.getBody();

    if (!response.isSuccess() || response.getData() == null) {
      throw new ApiLogicException("未找到订单", HttpStatus.BAD_REQUEST);
    }

    return response.getData();
  }
 public static void createDoctorListByAdmin() throws JsonProcessingException {
   // speciality.setId(2);
   // doctor.setSpeciality(speciality);
   ObjectMapper mapper = new ObjectMapper();
   RestTemplate restTemplate = new RestTemplate();
   HttpHeaders headers = new HttpHeaders();
   headers.set("auth-token", StaticStrings.ADMIN_AUTH_TOKEN);
   List<Integer> ids = new ArrayList<>();
   ids.add(17);
   ids.add(18);
   doctor.setInstitutionIds(ids);
   doctor2.setInstitutionIds(ids);
   List<Doctor> list = new ArrayList<>();
   list.add(doctor);
   list.add(doctor2);
   HttpEntity entity = new HttpEntity(list, headers);
   // System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(entity.getBody()));
   HttpEntity<Response> response =
       restTemplate.exchange(
           StaticStrings.CREATE_DOCTOR_LIST_URI, HttpMethod.POST, entity, Response.class);
   mapper = new ObjectMapper();
   System.out.println(
       mapper.writerWithDefaultPrettyPrinter().writeValueAsString(entity.getBody()));
   System.out.println(
       mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getBody()));
 }
Exemplo n.º 12
0
    private TermList getTermlist() {
      // TODO Auto-generated method stub
      MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
      ResponseEntity<TermList> responseEntity = null;

      HttpHeaders requestHeaders = new HttpHeaders();
      requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "xml")));
      HttpEntity<?> requestEntity = new HttpEntity<Object>(body, requestHeaders);

      String newurl = "http://www.dcapp.org/export/category.xml";

      try {
        RestTemplate restTemplate = new DCAppRestTemplate(10000);
        SimpleXmlHttpMessageConverter converter = new SimpleXmlHttpMessageConverter();
        HttpMessageConverter<?> formHttpMessageConverter = new FormHttpMessageConverter();
        HttpMessageConverter<?> stringHttpMessageConverternew = new StringHttpMessageConverter();

        restTemplate.getMessageConverters().add(converter);
        restTemplate.getMessageConverters().add(formHttpMessageConverter);
        restTemplate.getMessageConverters().add(stringHttpMessageConverternew);
        // responseEntity = restTemplate.exchange(this.url, HttpMethod.POST, requestEntity,
        // TermList.class);
        responseEntity =
            restTemplate.exchange(newurl, HttpMethod.GET, requestEntity, TermList.class);
      } catch (RestClientException e) {
        Log.e("DirectoryFragment", "Exception while retrieving terms listing.", e.getCause());
      }

      TermList terms = responseEntity.getBody();

      terms.setIsParent();

      return terms;
    }
    @Override
    protected Message doInBackground(Void... params) {
      final String url = getString(R.string.base_uri) + "/getmessage";

      // Populate the HTTP Basic Authentitcation header with the username and password
      HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
      HttpHeaders requestHeaders = new HttpHeaders();
      requestHeaders.setAuthorization(authHeader);
      requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

      // Create a new RestTemplate instance
      RestTemplate restTemplate = new RestTemplate();
      restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

      try {
        // Make the network request
        Log.d(TAG, url);
        ResponseEntity<Message> response =
            restTemplate.exchange(
                url, HttpMethod.GET, new HttpEntity<Object>(requestHeaders), Message.class);
        return response.getBody();
      } catch (HttpClientErrorException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        return new Message(0, e.getStatusText(), e.getLocalizedMessage());
      } catch (ResourceAccessException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        return new Message(0, e.getClass().getSimpleName(), e.getLocalizedMessage());
      }
    }
  @Test
  public void putTest() throws RestClientException, URISyntaxException {
    String url = dirFrontEnd + "/empresa/nifPrueba";
    String acceptHeaderValue = "application/json";

    HttpHeaders requestHeaders = new HttpHeaders();
    List<MediaType> mediaTypes = new ArrayList<MediaType>();
    mediaTypes.add(MediaType.valueOf(acceptHeaderValue));
    requestHeaders.setAccept(mediaTypes);
    requestHeaders.setContentType(MediaType.valueOf(acceptHeaderValue));
    HttpMethod put = HttpMethod.PUT;

    String body = "{\"nombre\":\"nombrePruebaModificado\"}";
    HttpEntity<String> entity = new HttpEntity<String>(body, requestHeaders);

    ResponseEntity<String> response = restTemplate.exchange(url, put, entity, String.class);
    assertTrue(response.getStatusCode().equals(HttpStatus.NO_CONTENT));
    String nombreEmpresa =
        (String)
            jdbcTemplate.queryForObject(
                "SELECT NOMBRE FROM EMPRESA WHERE NIF= ?",
                new Object[] {"nifPrueba"},
                String.class);
    assertTrue(nombreEmpresa.equals("nombrePruebaModificado"));
  }
  /**
   * Call recurly API.
   *
   * @param <T> the generic type
   * @param <E> the element type
   * @param path the path
   * @param payload the payload
   * @param responseClass the response class
   * @param method the method
   * @param headers the headers
   * @return the t
   * @throws RecurlyException the recurly exception
   */
  protected <T, E> T call(
      String path, E payload, Class<T> responseClass, HttpMethod method, HttpHeaders headers)
      throws RecurlyException {

    URI uri = null;
    ResponseEntity<T> responseEntity = null;
    T reponse = null;
    HttpEntity<?> entity = null;
    try {
      if (headers == null) {
        entity = new HttpEntity<>(payload, recurly.getRecurlyHeaders());
      } else {
        entity = new HttpEntity<>(payload, headers);
      }
      uri = new URI(URIUtil.encodeQuery(recurly.getRecurlyServerURL() + path, "UTF-8"));
      getLogger().debug("Calling Recurly URL {}, method: {}", uri.toString(), method.toString());
      responseEntity = restTemplate.exchange(uri, method, entity, responseClass);
      if (responseEntity != null) reponse = responseEntity.getBody();

    } catch (URIException | UnsupportedEncodingException | URISyntaxException e) {
      throw new RecurlyException("Not able to reach recurly. Please check the URL.", e);
    } catch (RestClientException e) {
      String err = ((HttpStatusCodeException) e).getResponseBodyAsString();
      int code = ((HttpStatusCodeException) e).getStatusCode().value();
      publishError(uri.toString(), err, code);
      RecurlyException ex = handleError(err, code, e);
      throw ex;
    }
    return reponse;
  }
Exemplo n.º 16
0
    private void getDCAppTerms() {
      final String url = "http://www.dcapp.org/rest/taxonomy_vocabulary/getTree";
      MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
      body.add("vid", "12");
      ResponseEntity<TermList> responseEntity = null;

      HttpHeaders requestHeaders = new HttpHeaders();
      requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "xml")));
      HttpEntity<?> requestEntity = new HttpEntity<Object>(body, requestHeaders);
      TermList termlist = null;

      try {
        RestTemplate restTemplate = new DCAppRestTemplate(10 * 1000);
        SimpleXmlHttpMessageConverter converter = new SimpleXmlHttpMessageConverter();
        HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
        HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter();

        restTemplate.getMessageConverters().add(converter);
        restTemplate.getMessageConverters().add(formHttpMessageConverter);
        restTemplate.getMessageConverters().add(stringHttpMessageConverternew);
        responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, TermList.class);
        termlist = responseEntity.getBody();
      } catch (RestClientException e) {
        Log.e("DirectoryFragment", "Exception while retrieving terms listing.", e.getCause());
      }

      if (termlist != null) {
        termlist.setIsParent();
        DCAppApplication app = (DCAppApplication) getApplication();
        app.setTermList(termlist);
      }
    }
Exemplo n.º 17
0
  @Override
  public OrderDetailDTO findOne(String id) throws ApiLogicException {

    ResponseEntity<Response<OrderDetailDTO>> responseEntity;

    try {
      responseEntity =
          restTemplate.exchange(
              this.buildBizAppURI(
                  APPURIConstant.Order.REQUEST_MAPPING,
                  APPURIConstant.Order.REQUEST_MAPPING_FIND_BY_ID),
              HttpMethod.GET,
              null,
              new ParameterizedTypeReference<Response<OrderDetailDTO>>() {},
              id);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      throw new ApiLogicException("订单未找到", HttpStatus.NOT_FOUND);
    }

    Response<OrderDetailDTO> response = responseEntity.getBody();

    if (!response.isSuccess() || response.getData() == null) {
      throw new ApiLogicException("订单未找到", HttpStatus.NOT_FOUND);
    }

    return response.getData();
  }
Exemplo n.º 18
0
  @Override
  protected Object doInBackground(Object[] params) {
    try {
      RestTemplate restTemplate = new RestTemplate();
      restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

      HttpHeaders requestHeaders = new HttpHeaders();

      String restUrl = ServerConstants.SERVER_API_URL + "user/login";

      User user = new User(username, password);
      SingleUser singleUser = new SingleUser();
      singleUser.setUser(user);

      HttpEntity<SingleUser> requestEntity = new HttpEntity<>(singleUser, requestHeaders);

      ResponseEntity<Boolean> responseEntity =
          restTemplate.exchange(restUrl, HttpMethod.POST, requestEntity, Boolean.class);

      boolean loginSuccessful = responseEntity.getBody();

      Log.d("Login", Boolean.toString(loginSuccessful));

      return loginSuccessful;
    } catch (Exception ex) {
      ex.printStackTrace();

      return false;
    }
  }
Exemplo n.º 19
0
  @Override
  public Response<PageDTO<OrderDetailDTO>> listByAccount(
      String account, String clientId, PageRequestDTO pageRequest) {
    OrderRequestDTO requestDTO = new OrderRequestDTO();
    requestDTO.setAccount(account);
    requestDTO.setClientId(clientId);
    requestDTO.setPageRequest(pageRequest);
    ResponseEntity<Response<PageDTO<OrderDetailDTO>>> responseEntity;
    try {
      responseEntity =
          restTemplate.exchange(
              this.buildBizAppURI(
                  APPURIConstant.Order.REQUEST_MAPPING,
                  APPURIConstant.Order.REQUEST_MAPPING_FIND_BY_ACCOUNT_AND_APP_ID),
              HttpMethod.POST,
              new HttpEntity<OrderRequestDTO>(requestDTO),
              new ParameterizedTypeReference<Response<PageDTO<OrderDetailDTO>>>() {});
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      throw new ApiLogicException("未找到订单", HttpStatus.BAD_REQUEST);
    }

    Response<PageDTO<OrderDetailDTO>> response = responseEntity.getBody();

    if (!response.isSuccess() || response.getData() == null) {
      throw new ApiLogicException("未找到订单", HttpStatus.BAD_REQUEST);
    }
    return response;
  }
  @Test
  public void postTest() throws RestClientException, URISyntaxException {
    String url = dirFrontEnd + "/empresa/";
    String acceptHeaderValue = "application/json";

    HttpHeaders requestHeaders = new HttpHeaders();
    List<MediaType> mediaTypes = new ArrayList<MediaType>();
    mediaTypes.add(MediaType.valueOf(acceptHeaderValue));
    requestHeaders.setAccept(mediaTypes);
    requestHeaders.setContentType(MediaType.valueOf(acceptHeaderValue));
    HttpMethod post = HttpMethod.POST;

    String body =
        "{\"nif\":\"nifPrueba\",\"nombre\":\"nombrePrueba\",\"direccionFiscal\":\"DirPrueba\",\"fechaInicioActividades\":\"2014-01-10\",\"version\":\"0\"}";
    HttpEntity<String> entity = new HttpEntity<String>(body, requestHeaders);

    ResponseEntity<String> response = restTemplate.exchange(url, post, entity, String.class);
    assertTrue(response.getStatusCode().equals(HttpStatus.CREATED));
    String nombreEmpresa =
        (String)
            jdbcTemplate.queryForObject(
                "SELECT NOMBRE FROM EMPRESA WHERE NIF= ?",
                new Object[] {"nifPrueba"},
                String.class);
    assertTrue(nombreEmpresa.equals("nombrePrueba"));
  }
Exemplo n.º 21
0
  @Test
  public void testOverwriteContentTypeHeader() {
    HttpMessageSender messageSender = new HttpMessageSender();
    String requestUrl = "http://localhost:8088/test";

    final String responseBody = "<TestResponse><Message>Hello World!</Message></TestResponse>";

    messageSender.setReplyMessageHandler(replyMessageHandler);

    messageSender.setRequestMethod(HttpMethod.POST);
    messageSender.setRequestUrl(requestUrl);
    messageSender.setContentType("text/xml");
    messageSender.setCharset("ISO-8859-1");

    Message<?> requestMessage =
        MessageBuilder.withPayload("<TestRequest><Message>Hello World!</Message></TestRequest>")
            .setHeader("Content-Type", "application/xml;charset=UTF-8")
            .setHeader("Accept", "application/xml")
            .build();

    messageSender.setRestTemplate(restTemplate);

    reset(restTemplate, replyMessageHandler);

    restTemplate.setErrorHandler(anyObject(ResponseErrorHandler.class));
    expectLastCall().once();

    expect(
            restTemplate.exchange(
                eq(requestUrl), eq(HttpMethod.POST), anyObject(HttpEntity.class), eq(String.class)))
        .andAnswer(
            new IAnswer<ResponseEntity<String>>() {
              public ResponseEntity<String> answer() throws Throwable {
                HttpEntity<?> httpRequest = (HttpEntity<?>) getCurrentArguments()[2];

                Assert.assertEquals(
                    httpRequest.getBody().toString(),
                    "<TestRequest><Message>Hello World!</Message></TestRequest>");
                Assert.assertEquals(httpRequest.getHeaders().size(), 2);

                Assert.assertEquals(
                    httpRequest.getHeaders().getContentType().toString(),
                    "application/xml;charset=UTF-8");
                Assert.assertEquals(
                    httpRequest.getHeaders().getAccept().get(0).toString(), "application/xml");

                return new ResponseEntity<String>(responseBody, HttpStatus.OK);
              }
            })
        .once();

    replyMessageHandler.onReplyMessage(anyObject(Message.class));
    expectLastCall().once();

    replay(restTemplate, replyMessageHandler);

    messageSender.send(requestMessage);

    verify(restTemplate, replyMessageHandler);
  }
 @Test
 public void testRestTemplateClient() throws Exception {
   String[] uriVariables = {"aaaa签名", "001"};
   ResponseEntity<String> exchange =
       restTemplate.exchange(TEST_URL_ONE, HttpMethod.POST, null, String.class, uriVariables);
   log.info(exchange.getBody());
   assertEquals(exchange.getStatusCode(), HttpStatus.OK);
 }
 @Override
 public String delete(Customer entity) {
   final String url = BASE_URL + "customer/delete/" + entity.getId().toString();
   HttpEntity<Customer> requestEntity = new HttpEntity<Customer>(entity, requestHeaders);
   ResponseEntity<String> responseEntity =
       restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class);
   return responseEntity.getBody();
 }
Exemplo n.º 24
0
  @Override
  public JHttpResponse execute(JHttpEndpoint endpoint, JHttpQuery query) {
    if (query == null) return execute(endpoint);

    URI endpointURI = endpoint.getURI(query.getPath(), query.getQueryParams());
    RequestEntity requestEntity = mapToRequestEntity(query, endpointURI);
    ResponseEntity responseEntity;
    if (query.getResponseBodyType() != null) {
      responseEntity =
          restTemplate.exchange(
              endpointURI, query.getMethod(), requestEntity, query.getResponseBodyType());
    } else {
      responseEntity =
          restTemplate.exchange(endpointURI, query.getMethod(), requestEntity, byte[].class);
    }
    return mapToJHttpResponse(responseEntity);
  }
 @Override
 public T getById(String endpoint, Long id, Class clazz) {
   RestTemplate template = new RestTemplate();
   @SuppressWarnings("unchecked")
   ResponseEntity<T> city =
       template.exchange(endpoint + "/" + id, HttpMethod.GET, RequestEntity.EMPTY, clazz);
   return city.getBody();
 }
Exemplo n.º 26
0
 @Override
 public String delete(Subject entity) {
   final String url = BASE_URL + "subject/delete/" + entity.getId().toString();
   HttpEntity<Subject> requestEntity = new HttpEntity<Subject>(entity, requestHeaders);
   ResponseEntity<String> responseEntity =
       restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, String.class);
   return responseEntity.getBody();
 }
 @Override
 public Customer get(Long id) {
   final String url = BASE_URL + "customer/" + id.toString();
   HttpEntity<Customer> requestEntity = new HttpEntity<Customer>(requestHeaders);
   ResponseEntity<Customer> responseEntity =
       restTemplate.exchange(url, HttpMethod.GET, requestEntity, Customer.class);
   Customer subject = responseEntity.getBody();
   return subject;
 }
 @Override
 public String post(Customer entity) {
   final String url = BASE_URL + "customer/create";
   HttpEntity<Customer> requestEntity = new HttpEntity<Customer>(entity, requestHeaders);
   ResponseEntity<String> responseEntity =
       restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
   String result = responseEntity.getBody();
   return result;
 }
Exemplo n.º 29
0
 @Override
 public Subject get(Long id) {
   final String url = BASE_URL + "subject/" + id.toString();
   HttpEntity<Subject> requestEntity = new HttpEntity<Subject>(requestHeaders);
   ResponseEntity<Subject> responseEntity =
       restTemplate.exchange(url, HttpMethod.GET, requestEntity, Subject.class);
   Subject subject = responseEntity.getBody();
   return subject;
 }
Exemplo n.º 30
0
  public int getEventCount() throws IOException {
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Accept", "application/json");
    HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    ResponseEntity<String> entity =
        template.exchange(url, HttpMethod.GET, requestEntity, String.class);

    return new ObjectMapper().readTree(entity.getBody()).get("count").getIntValue();
  }