/**
  * Add a header entry for the given name.
  *
  * <p>If there was no entry for that header name before, the value will be used as-is. In case of
  * an existing entry, a String array will be created, adding the given value (more specifically,
  * its toString representation) as further element.
  *
  * <p>Multiple values can only be stored as list of Strings, following the Servlet spec (see
  * <code>getHeaders</code> accessor). As alternative to repeated <code>addHeader</code> calls for
  * individual elements, you can use a single call with an entire array or Collection of values as
  * parameter.
  *
  * @see #getHeaderNames
  * @see #getHeader
  * @see #getHeaders
  * @see #getDateHeader
  * @see #getIntHeader
  */
 public void addHeader(String name, Object value) {
   if (CONTENT_TYPE_HEADER.equalsIgnoreCase(name)) {
     setContentType((String) value);
     return;
   }
   doAddHeaderValue(name, value, false);
 }
  @Test(timeout = 10000)
  public void testClassifier() throws Exception {

    int minSize = 4;
    int maxSize = 20;
    int classCount = 3;

    StringBuilder jsonRequest = new StringBuilder();
    jsonRequest.append("{");
    jsonRequest.append("type:\"PROP_SYMBOLS\",");
    jsonRequest.append(
        "wfs_url:\"http://sigma.openplans.org/geoserver/wfs?service=WFS&request=GetCapabilities\",");
    jsonRequest.append("layer_name:\"topp:states\",");
    jsonRequest.append("attribute_name:\"PERSONS\",");
    jsonRequest.append("class_count:\"" + classCount + "\",");
    jsonRequest.append("min_size:\"" + minSize + "\",");
    jsonRequest.append("max_size:\"" + maxSize + "\"");
    jsonRequest.append("}");

    _requestPost.setRequestURI(DOMAIN_NAME + DocController.SLD_URL); // fake URI, Rest style
    _requestPost.setContent(jsonRequest.toString().getBytes()); // fake body containing json request
    _requestPost.setContentType("application/json");

    _controller.doSLDPost(_requestPost, _responsePost);

    assertEquals(200, _responseGet.getStatus()); // 200 OK
  }
  /**
   * Test a complete scenario. User sends sld file content via POST and gets back the generated file
   * path. Then user asks via GET to get back the sld file stored on the server
   *
   * @throws Exception
   */
  @Test
  public void testSLDService() throws Exception {

    // valid sld file
    String sldContent =
        "<StyledLayerDescriptor version=\"1.1.0\" xsi:schemaLocation=\"http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd\" xmlns=\"http://www.opengis.net/sld\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:se=\"http://www.opengis.net/se\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <NamedLayer><se:Name>OCEANSEA_1M:Foundation</se:Name><UserStyle><se:Name>GEOSYM</se:Name><IsDefault>1</IsDefault><se:FeatureTypeStyle><se:FeatureTypeName>Foundation</se:FeatureTypeName><se:Rule><se:Name>main</se:Name><se:PolygonSymbolizer uom=\"http://www.opengis.net/sld/units/pixel\"><se:Name>MySymbol</se:Name><se:Description><se:Title>Example Symbol</se:Title><se:Abstract>This is just a simple example.</se:Abstract></se:Description><se:Geometry><ogc:PropertyName>GEOMETRY</ogc:PropertyName></se:Geometry><se:Fill><se:SvgParameter name=\"fill\">#96C3F5</se:SvgParameter></se:Fill></se:PolygonSymbolizer></se:Rule></se:FeatureTypeStyle></UserStyle></NamedLayer></StyledLayerDescriptor>";

    _requestPost.setRequestURI(DOMAIN_NAME + DocController.SLD_URL); // fake URI, Rest style
    _requestPost.setContent(sldContent.getBytes()); // fake body containing sld file
    _requestPost.setContentType("application/vnd.ogc.sld+xml");

    _controller.doSLDPost(_requestPost, _responsePost);
    assertEquals(201, _responsePost.getStatus()); // 201 Created

    String sResp = _responsePost.getContentAsString();

    // the response is actually a JSON object
    JSONObject oResp = new JSONObject(sResp);
    String filePath = (String) oResp.get(DocController.FILEPATH_VARNAME);

    // file name contains absolute url + CSV service path
    assertEquals(true, filePath.contains(DocController.SLD_URL));

    _requestGet.setRequestURI(DOMAIN_NAME + filePath); // fake URI, Rest style

    _controller.getSLDFile(_requestGet, _responseGet);
    assertEquals(200, _responseGet.getStatus()); // 200 OK
    assertEquals(sldContent, _responseGet.getContentAsString().trim()); // content sent is
    // back
  }
 @Test
 public void setContentType() {
   String contentType = "test/plain";
   request.setContentType(contentType);
   assertEquals(contentType, request.getContentType());
   assertEquals(contentType, request.getHeader("Content-Type"));
   assertNull(request.getCharacterEncoding());
 }
 @Test
 public void setContentTypeUTF8() {
   String contentType = "test/plain;charset=UTF-8";
   request.setContentType(contentType);
   assertEquals(contentType, request.getContentType());
   assertEquals(contentType, request.getHeader("Content-Type"));
   assertEquals("UTF-8", request.getCharacterEncoding());
 }
 @Test
 public void setCharacterEncodingThenContentType() {
   request.setCharacterEncoding("UTF-8");
   request.setContentType("test/plain");
   assertEquals("test/plain", request.getContentType());
   assertEquals("test/plain;charset=UTF-8", request.getHeader("Content-Type"));
   assertEquals("UTF-8", request.getCharacterEncoding());
 }
예제 #7
0
    public MockHttpServletResponse callInternal(
        Method method, String resourceUri, JSONObject payload) throws Exception {
      MockHttpServletRequest request = super.createRequest(resourceUri);
      request.setMethod(method.getName());
      // set the JSON payload
      request.setContent(payload.toString().getBytes());
      request.setContentType("application/json");

      return dispatch(request, null);
    }
예제 #8
0
    public MockHttpServletResponse callInternal(Method method, String resourceUri, Form form)
        throws Exception {
      MockHttpServletRequest request = super.createRequest(resourceUri);
      request.setMethod(method.getName());
      // set the JSON payload
      request.setContent(form.encode().getBytes());
      request.setContentType("application/x-www-form-urlencoded");

      return dispatch(request, null);
    }
  @Test
  public void testConsumes() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/consumes");
    request.setContentType("text/plain");
    Object handler = this.handlerMapping.getHandler(request).getHandler();
    MockHttpServletResponse response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    String testResponse = response.getContentAsString();
    assertEquals("BAR", testResponse);

    request = new MockHttpServletRequest("GET", "/consumes");
    request.setContentType("text/xml");
    handler = this.handlerMapping.getHandler(request).getHandler();
    response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    testResponse = response.getContentAsString();
    assertEquals("<test>TEXT_XML</test>", testResponse);
  }
 public void testPostAtomSyndFeed() throws Exception {
   MockHttpServletRequest request =
       MockRequestConstructor.constructMockRequest(
           "POST", "/test/atomsyndfeed", "application/atom+xml");
   request.setContentType("application/atom+xml");
   request.setContent(FEED.getBytes());
   MockHttpServletResponse response = invoke(request);
   assertEquals(200, response.getStatus());
   String msg =
       TestUtils.diffIgnoreUpdateWithAttributeQualifier(FEED, response.getContentAsString());
   assertNull(msg, msg);
 }
  private MockHttpServletRequest newMockRequest(
      String method, String requestUri, String host, int port) {
    MockHttpServletRequest req = new MockHttpServletRequest(method, requestUri);
    req.setRemoteHost(host);
    req.setContentType("application/x-www-form-urlencoded");
    req.setRemotePort(port);
    if (port == 443) {
      req.setScheme("https");
      req.setSecure(true);
    } else {
      req.setScheme("http");
      req.setSecure(false);
    }

    return req;
  }
예제 #12
0
  private MockHttpServletRequest constructMockRequest(
      String method, String requestURI, String acceptHeader, String contentType) {
    MockHttpServletRequest mockRequest =
        new MockHttpServletRequest() {
          public String getPathTranslated() {
            return null; // prevent Spring to resolve the file on the filesystem which fails
          }
        };

    mockRequest.setMethod(method);
    mockRequest.setRequestURI(requestURI);
    mockRequest.setServerPort(8080);
    mockRequest.addHeader("Accept", acceptHeader);
    mockRequest.addHeader("Content-Type", contentType);
    mockRequest.setContentType(contentType);
    return mockRequest;
  }
예제 #13
0
    /**
     * Issue a POST request to the provided URL with the given file passed as form data.
     *
     * @param resourceUri the url to issue the request to
     * @param formFieldName the form field name for the file to be posted
     * @param file the file to post
     * @return the response to the request
     */
    public MockHttpServletResponse postFile(String resourceUri, String formFieldName, File file)
        throws Exception {
      Part[] parts = new Part[1];
      parts[0] = new FilePart(formFieldName, file);

      MultipartRequestEntity multipart =
          new MultipartRequestEntity(parts, new PostMethod().getParams());

      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      multipart.writeRequest(bout);

      MockHttpServletRequest req = createRequest(resourceUri);
      req.setContentType(multipart.getContentType());
      req.addHeader("Content-Type", multipart.getContentType());
      req.setMethod("POST");
      req.setContent(bout.toByteArray());

      return dispatch(req);
    }
  @Test(expected = SpelEvaluationException.class)
  // INT-1677
  public void withNameAndExpressionsNoPath() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setContentType("text/plain");
    request.setParameter("foo", "bar");
    request.setContent("hello".getBytes());
    request.setRequestURI("/fname/bill/lname/clinton");

    MockHttpServletResponse response = new MockHttpServletResponse();
    inboundAdapterWithNameNoPath.handleRequest(request, response);
    assertEquals(HttpServletResponse.SC_OK, response.getStatus());
    Message<?> message = requests.receive(0);
    assertNotNull(message);
    Object payload = message.getPayload();
    assertTrue(payload instanceof String);
    assertEquals("hello", payload); // default payload
    assertNull(message.getHeaders().get("lname"));
  }
  @Test // ensure that 'path' takes priority over name
  // INT-1677
  public void withNameAndExpressionsAndPath() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setContentType("text/plain");
    request.setParameter("foo", "bar");
    request.setContent("hello".getBytes());
    request.setRequestURI("/fname/bill/lname/clinton");

    MockHttpServletResponse response = new MockHttpServletResponse();
    inboundAdapterWithNameAndExpressions.handleRequest(request, response);
    assertEquals(HttpServletResponse.SC_OK, response.getStatus());
    Message<?> message = requests.receive(0);
    assertNotNull(message);
    Object payload = message.getPayload();
    assertTrue(payload instanceof String);
    assertEquals("bill", payload);
    assertEquals("clinton", message.getHeaders().get("lname"));
  }
  /**
   * Test a complete scenario. User send JSON data via POST and gets back the generated csv file
   * name. Then user asks via GET to get back the csv file stored on the server
   *
   * @throws Exception
   */
  @Test
  public void testCSVService() throws Exception {

    // json file to be send
    String JSONContent =
        "{"
            + "\"columns\":[\"col1\", \"col2\"],"
            + "\"data\":["
            + "[\"1\",\"2\"],"
            + "[3,4]"
            + "]"
            + "}";

    // csv content that client expect to receive
    String expectedCSVContent = "col1;col2\r\n1;2\r\n3;4";

    _requestPost.setRequestURI(DOMAIN_NAME + DocController.CSV_URL); // fake URI, Rest style
    _requestPost.setContent(JSONContent.getBytes()); // fake body containing json file
    _requestPost.setContentType("application/json");

    _controller.storeCSVFile(_requestPost, _responsePost);
    assertEquals(201, _responsePost.getStatus()); // 201 Created

    String sResp = _responsePost.getContentAsString();

    // the response is actually a JSON object
    JSONObject oResp = new JSONObject(sResp);
    String filePath = (String) oResp.get(DocController.FILEPATH_VARNAME);

    // file name contains absolute url + CSV service path
    assertEquals(true, filePath.contains(DocController.CSV_URL));

    _requestGet.setRequestURI(DOMAIN_NAME + filePath); // fake URI, Rest style

    _controller.getCSVFile(_requestGet, _responseGet);
    assertEquals(200, _responseGet.getStatus()); // 200 OK
    assertEquals(expectedCSVContent, _responseGet.getContentAsString().trim()); // content sent is
    // back
  }
  @Test
  @SuppressWarnings("unchecked")
  // INT-1362
  public void testURIVariablesAndHeaders() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    String testRequest = "aBc;q1=1;q2=2";
    String requestURI = "/test/" + testRequest;
    request.setRequestURI(requestURI);
    request.setContentType("text/plain");
    final Map<String, String> params = new HashMap<String, String>();
    params.put("foo", "bar");
    request.setParameters(params);
    request.setContent("hello".getBytes());
    final Cookie cookie = new Cookie("foo", "bar");
    request.setCookies(cookie);
    request.addHeader("toLowerCase", true);

    // See org.springframework.web.servlet.FrameworkServlet#initContextHolders
    final RequestAttributes attributes = new ServletRequestAttributes(request);
    RequestContextHolder.setRequestAttributes(attributes);

    this.toLowerCaseChannel.subscribe(
        new MessageHandler() {

          @Override
          public void handleMessage(Message<?> message) throws MessagingException {
            MessageHeaders headers = message.getHeaders();

            assertEquals(attributes, headers.get("requestAttributes"));

            Object requestParams = headers.get("requestParams");
            assertNotNull(requestParams);
            assertEquals(
                params, ((MultiValueMap<String, String>) requestParams).toSingleValueMap());

            Object matrixVariables = headers.get("matrixVariables");
            assertThat(matrixVariables, Matchers.instanceOf(Map.class));
            Object value = ((Map<?, ?>) matrixVariables).get("value");
            assertThat(value, Matchers.instanceOf(MultiValueMap.class));
            assertEquals("1", ((MultiValueMap<String, ?>) value).getFirst("q1"));
            assertEquals("2", ((MultiValueMap<String, ?>) value).getFirst("q2"));

            Object requestHeaders = headers.get("requestHeaders");
            assertNotNull(requestParams);
            assertEquals(MediaType.TEXT_PLAIN, ((HttpHeaders) requestHeaders).getContentType());

            Map<String, Cookie> cookies = (Map<String, Cookie>) headers.get("cookies");
            assertEquals(1, cookies.size());
            Cookie foo = cookies.get("foo");
            assertNotNull(foo);
            assertEquals(cookie, foo);
          }
        });

    MockHttpServletResponse response = new MockHttpServletResponse();

    Object handler = this.handlerMapping.getHandler(request).getHandler();
    this.handlerAdapter.handle(request, response, handler);
    final String testResponse = response.getContentAsString();
    assertEquals(testRequest.split(";")[0].toLowerCase(), testResponse);

    RequestContextHolder.resetRequestAttributes();
  }
예제 #18
0
  public Tuple service(String method, String path, Map<String, String> headers, byte[] data) {

    WebDAVStorage webDAVStorage = new DLWebDAVStorageImpl();

    webDAVStorage.setToken("document_library");

    WebDAVUtil.addStorage(webDAVStorage);

    WebDAVServlet webDAVServlet = new WebDAVServlet();

    String requestURI = _CONTEXT_PATH + _SERVLET_PATH + _PATH_INFO_PREFACE + path;

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(method, requestURI);

    mockHttpServletRequest.setContextPath(_CONTEXT_PATH);
    mockHttpServletRequest.setServletPath(_SERVLET_PATH);
    mockHttpServletRequest.setPathInfo(_PATH_INFO_PREFACE + path);

    try {
      mockHttpServletRequest.setRemoteUser(String.valueOf(TestPropsValues.getUserId()));
    } catch (Exception e) {
      Assert.fail("User ID cannot be initialized");
    }

    if (headers == null) {
      headers = new HashMap<String, String>();
    }

    headers.put(HttpHeaders.USER_AGENT, getUserAgent());

    try {
      throw new Exception();
    } catch (Exception e) {
      StackTraceElement[] stackTraceElements = e.getStackTrace();

      for (StackTraceElement stackTraceElement : stackTraceElements) {
        String methodName = stackTraceElement.getMethodName();

        if (methodName.equals("setUp")
            || methodName.equals("tearDown")
            || methodName.startsWith("test")) {

          String testName =
              StringUtil.extractLast(stackTraceElement.getClassName(), CharPool.PERIOD);

          testName =
              StringUtil.replace(testName, new String[] {"WebDAV", "Test"}, new String[] {"", ""});

          headers.put(
              "X-Litmus",
              testName
                  + ": ("
                  + stackTraceElement.getMethodName()
                  + ":"
                  + stackTraceElement.getLineNumber()
                  + ")");

          break;
        }
      }
    }

    if (data != null) {
      mockHttpServletRequest.setContent(data);

      String contentType = headers.remove(HttpHeaders.CONTENT_TYPE);

      if (contentType != null) {
        mockHttpServletRequest.setContentType(contentType);
      } else {
        mockHttpServletRequest.setContentType(ContentTypes.TEXT_PLAIN);
      }
    }

    for (Map.Entry<String, String> entry : headers.entrySet()) {
      String key = entry.getKey();
      String value = entry.getValue();

      mockHttpServletRequest.addHeader(key, value);
    }

    try {
      MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

      webDAVServlet.service(mockHttpServletRequest, mockHttpServletResponse);

      int statusCode = mockHttpServletResponse.getStatus();
      byte[] responseBody = mockHttpServletResponse.getContentAsByteArray();

      Map<String, String> responseHeaders = new HashMap<String, String>();

      for (String name : mockHttpServletResponse.getHeaderNames()) {
        responseHeaders.put(name, (String) mockHttpServletResponse.getHeader(name));
      }

      return new Tuple(statusCode, responseBody, responseHeaders);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }