@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"));
  }
  @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"));
  }
Example #3
0
  /**
   * Method that can be executed in order to test if Head.png is being served.
   *
   * @throws Exception if the image is not being served.
   */
  @Test
  public void testHead() throws Exception {

    /*
     * Information given by a GET petition to the URL specified by the first
     * parameter is stored on an ResponseEntity.
     */
    final ResponseEntity<byte[]> entity =
        new TestRestTemplate()
            .getForEntity("http:/" + "/localhost:" + this.port + "/images/Head.png", byte[].class);

    /*
     * Check if the StatusCode is equal to 200 (HttpStatus.OK) which is the
     * standard response for succesful HTTP requests. If correct, it means
     * that is available to connect and the connection has been succesful.
     */

    assertEquals("the code is reachable", HttpStatus.OK, entity.getStatusCode());

    /*
     * Checks if the 'Content-type' field of the GET petition is correct.
     * This means, the returned entity is a PNG file. If the verification
     * is not positive it throws an error with the given message.
     */
    assertEquals(
        "Wrong content type:\n" + entity.getHeaders().getContentType(),
        MediaType.valueOf("image/png;charset=UTF-8"),
        entity.getHeaders().getContentType());
  }
  /**
   * 转换异常信息为format格式
   *
   * @param httpServletResponse
   * @param format
   * @param mainError
   * @throws IOException
   */
  public void convertData(
      HttpServletRequest request, HttpServletResponse httpServletResponse, MainError mainError)
      throws IOException {
    final String format = (String) request.getAttribute(Constants.SYS_PARAM_KEY_FORMAT);

    if (Constants.DATA_FORMAT_JSON.equals(format)) {
      jsonMessageConverter.write(
          mainError,
          MediaType.valueOf("application/json;charset=UTF-8"),
          new ServletServerHttpResponse(httpServletResponse));
    } else {
      xmlMessageConverter.write(
          mainError,
          MediaType.valueOf("application/xml;charset=UTF-8"),
          new ServletServerHttpResponse(httpServletResponse));
    }
  }
 @Test
 public void testCommenceWithEmptyAccept() throws Exception {
   entryPoint.commence(request, response, new BadCredentialsException("Bad"));
   assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
   assertEquals(
       "{\"error\":\"unauthorized\",\"error_description\":\"Bad\"}",
       response.getContentAsString());
   assertTrue(
       MediaType.APPLICATION_JSON.isCompatibleWith(MediaType.valueOf(response.getContentType())));
   assertEquals(null, response.getErrorMessage());
 }
 @Test
 public void testCss() throws Exception {
   ResponseEntity<String> entity =
       getRestTemplate().getForEntity("http://localhost:8080/css/bootstrap.min.css", String.class);
   assertEquals(HttpStatus.OK, entity.getStatusCode());
   assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body"));
   assertEquals(
       "Wrong content type:\n" + entity.getHeaders().getContentType(),
       MediaType.valueOf("text/css"),
       entity.getHeaders().getContentType());
 }
Example #7
0
  /**
   * @testCss Method that can be executed in order to test the connection to styles sheet If the
   *     connection goes wrong or the CSS file is not well formed, this method throws an Exception
   * @throws Exception if the connection to the styles sheet is wrong or if it's bad formed.
   */
  @Test
  public void testCss() throws Exception {
    /*
     * Information given by a GET petition to the URL specified by the first
     * parameter is stored on an ResponseEntity.
     */
    final ResponseEntity<String> entity =
        new TestRestTemplate()
            .getForEntity(
                "http://localhost:" + this.port + "/webjars/bootstrap/3.3.5/css/bootstrap.min.css",
                String.class);

    /*
     * Checks done for verifying the correctness of the connection with these three
     * assertions who will
     * return an exception if one of them is not correct.
     */

    /*
     * Check if the StatusCode is equal to 200 (HttpStatus.OK) which is the
     * standard response
     * for successful HTTP requests. If correct, it means that is available
     * to connect and the connection has been successful.
     */
    assertEquals("the code is reachable", HttpStatus.OK, entity.getStatusCode());

    /*
     * These assertion check if the information given by the GET petition
     * (if the body of the GET petition is
     * correct(contains the word 'body')), which has been saved in an
     * entity, contains a correct CSS format.
     */
    /*
     * For more information about CSS (Cascading Style Sheets), you can read
     * about it in the
     * W3C page (http://www.w3.org/TR/CSS/) or in the W3 schools page
     * (http://www.w3schools.com/css/)
     * If the verification is not positive it throws an error with the given
     * message.
     */
    assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body"));

    /*
     * Checks if the 'Content-type' field of the GET petition is correct.
     * If the verification is not positive it throws an error with the given
     * message.
     */
    assertEquals(
        "Wrong content type:\n" + entity.getHeaders().getContentType(),
        MediaType.valueOf("text/css;charset=UTF-8"),
        entity.getHeaders().getContentType());
  }
  @Bean
  List<HttpMessageConverter<?>> httpMessageConverters() {
    Assert.notNull(httpMessageConverters);

    if (httpMessageConverters.isEmpty()) {
      MappingJacksonHttpMessageConverter json = new MappingJacksonHttpMessageConverter();
      json.setSupportedMediaTypes(
          Arrays.asList(
              MediaType.APPLICATION_JSON, MediaType.valueOf("application/x-spring-data+json")));
      httpMessageConverters.add(json);
    }

    return httpMessageConverters;
  }
 @ResponseBody
 @RequestMapping(value = "/admin/orders/export.html", method = RequestMethod.GET)
 public ResponseEntity<byte[]> export() throws Exception {
   Map<String, Object> model = new HashMap<String, Object>();
   List<Order> orders = orderRepository.export();
   model.put("orders", orders);
   XLSTransformer transformer = new XLSTransformer();
   Resource resource = new ClassPathResource("/template/OrderExport.xlsx");
   Workbook workbook = transformer.transformXLS(resource.getInputStream(), model);
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   workbook.write(baos);
   final HttpHeaders headers = new HttpHeaders();
   headers.setContentType(
       MediaType.valueOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
   headers.set("Content-Disposition", "attachment;Filename=OrderExport.xlsx");
   headers.setCacheControl("no-cache");
   return new ResponseEntity<byte[]>(baos.toByteArray(), headers, HttpStatus.OK);
 }
  @RequestMapping(value = "/load/{id}", method = RequestMethod.GET)
  public ResponseEntity<byte[]> loadAvatar(@PathVariable("id") Long id) {
    Avatar avatar = avatarService.findById(id);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf(avatar.getTipo()));
    InputStream is = new ByteArrayInputStream(avatar.getAvatar());
    try {
      return new ResponseEntity<byte[]>(IOUtils.toByteArray(is), headers, HttpStatus.OK);
    } catch (IOException e) {
      LOGGER.error(e.getMessage());
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        LOGGER.error(e.getMessage());
      }
    }
    return null;
  }
Example #11
0
  static {
    // variable names refer to RFC 2616, section 2.2
    BitSet ctl = new BitSet(128);
    for (int i = 0; i <= 31; i++) {
      ctl.set(i);
    }
    ctl.set(127);

    BitSet separators = new BitSet(128);
    separators.set('(');
    separators.set(')');
    separators.set('<');
    separators.set('>');
    separators.set('@');
    separators.set(',');
    separators.set(';');
    separators.set(':');
    separators.set('\\');
    separators.set('\"');
    separators.set('/');
    separators.set('[');
    separators.set(']');
    separators.set('?');
    separators.set('=');
    separators.set('{');
    separators.set('}');
    separators.set(' ');
    separators.set('\t');

    TOKEN = new BitSet(128);
    TOKEN.set(0, 128);
    TOKEN.andNot(ctl);
    TOKEN.andNot(separators);

    ALL = MediaType.valueOf(ALL_VALUE);
    APPLICATION_ATOM_XML = MediaType.valueOf(APPLICATION_ATOM_XML_VALUE);
    APPLICATION_RSS_XML = MediaType.valueOf(APPLICATION_RSS_XML_VALUE);
    APPLICATION_FORM_URLENCODED = MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE);
    APPLICATION_JSON = MediaType.valueOf(APPLICATION_JSON_VALUE);
    APPLICATION_OCTET_STREAM = MediaType.valueOf(APPLICATION_OCTET_STREAM_VALUE);
    APPLICATION_XHTML_XML = MediaType.valueOf(APPLICATION_XHTML_XML_VALUE);
    APPLICATION_XML = MediaType.valueOf(APPLICATION_XML_VALUE);
    APPLICATION_WILDCARD_XML = MediaType.valueOf(APPLICATION_WILDCARD_XML_VALUE);
    IMAGE_GIF = MediaType.valueOf(IMAGE_GIF_VALUE);
    IMAGE_JPEG = MediaType.valueOf(IMAGE_JPEG_VALUE);
    IMAGE_PNG = MediaType.valueOf(IMAGE_PNG_VALUE);
    MULTIPART_FORM_DATA = MediaType.valueOf(MULTIPART_FORM_DATA_VALUE);
    TEXT_HTML = MediaType.valueOf(TEXT_HTML_VALUE);
    TEXT_PLAIN = MediaType.valueOf(TEXT_PLAIN_VALUE);
    TEXT_XML = MediaType.valueOf(TEXT_XML_VALUE);
  }