예제 #1
0
  public void testReadOpContext() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContextPath("/geoserver");
    request.setRequestURI("/geoserver/hello");
    request.setMethod("get");

    Dispatcher dispatcher = new Dispatcher();

    Request req = new Request();
    req.httpRequest = request;
    dispatcher.init(req);

    Map map = dispatcher.readOpContext(req);

    assertEquals("hello", map.get("service"));

    request = new MockHttpServletRequest();
    request.setContextPath("/geoserver");
    request.setRequestURI("/geoserver/foobar/hello");
    request.setMethod("get");
    map = dispatcher.readOpContext(req);
    assertEquals("hello", map.get("service"));

    request = new MockHttpServletRequest();
    request.setContextPath("/geoserver");
    request.setRequestURI("/geoserver/foobar/hello/");
    request.setMethod("get");
    map = dispatcher.readOpContext(req);

    assertEquals("hello", map.get("service"));
  }
예제 #2
0
  int postNewTaskAsMultiPartForm(int imp, String data) throws Exception {
    File dir = unpack(data);

    List<Part> parts = new ArrayList<Part>();
    for (File f : dir.listFiles()) {
      parts.add(new FilePart(f.getName(), f));
    }
    MultipartRequestEntity multipart =
        new MultipartRequestEntity(
            parts.toArray(new Part[parts.size()]), new PostMethod().getParams());

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

    MockHttpServletRequest req = createRequest("/rest/imports/" + imp + "/tasks");
    req.setContentType(multipart.getContentType());
    req.addHeader("Content-Type", multipart.getContentType());
    req.setMethod("POST");
    req.setBodyContent(bout.toByteArray());

    MockHttpServletResponse resp = dispatch(req);
    assertEquals(201, resp.getStatusCode());
    assertNotNull(resp.getHeader("Location"));

    assertTrue(resp.getHeader("Location").matches(".*/imports/" + imp + "/tasks/\\d"));
    assertEquals("application/json", resp.getContentType());

    JSONObject json = (JSONObject) json(resp);

    JSONObject task = json.getJSONObject("task");
    return task.getInt("id");
  }
예제 #3
0
  int putNewTask(int imp, String data) throws Exception {
    File zip = getTestDataFile(data);
    byte[] payload = new byte[(int) zip.length()];
    FileInputStream fis = new FileInputStream(zip);
    fis.read(payload);
    fis.close();

    MockHttpServletRequest req =
        createRequest("/rest/imports/" + imp + "/tasks/" + new File(data).getName());
    req.setHeader("Content-Type", MediaType.APPLICATION_ZIP.toString());
    req.setMethod("PUT");
    req.setBodyContent(payload);

    MockHttpServletResponse resp = dispatch(req);
    assertEquals(201, resp.getStatusCode());
    assertNotNull(resp.getHeader("Location"));

    assertTrue(resp.getHeader("Location").matches(".*/imports/" + imp + "/tasks/\\d"));
    assertEquals("application/json", resp.getContentType());

    JSONObject json = (JSONObject) json(resp);

    JSONObject task = json.getJSONObject("task");
    return task.getInt("id");
  }
예제 #4
0
  @SuppressWarnings("unchecked")
  @Test
  public void testDoFilterRedirectLogin() throws IOException, ServletException {
    req.setRequestURI("/admin/bla.jsp");
    me.doFilter(req, resp, chain);

    assertNull(chain.getLastRequest());
    assertNull(chain.getLastResponse());

    assertFalse(resp.wasRedirectSent());
    Map<String, MockRequestDispatcher> m = req.getRequestDispatcherMap();
    assertEquals("/login.jsp", m.get(m.keySet().iterator().next()).getPath());
  }
예제 #5
0
  /**
   * Tests mixed get/post situations for cases in which there is no kvp parser
   *
   * @throws Exception
   */
  public void testHelloOperationMixed() throws Exception {
    URL url = getClass().getResource("applicationContextOnlyXml.xml");

    FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(url.toString());

    Dispatcher dispatcher = (Dispatcher) context.getBean("dispatcher");

    final String body = "<Hello service=\"hello\" message=\"Hello world!\" version=\"1.0.0\" />";

    MockHttpServletRequest request =
        new MockHttpServletRequest() {
          String encoding;

          public int getServerPort() {
            return 8080;
          }

          public String getCharacterEncoding() {
            return encoding;
          }

          public void setCharacterEncoding(String encoding) {
            this.encoding = encoding;
          }

          public ServletInputStream getInputStream() throws IOException {
            final ServletInputStream stream = super.getInputStream();
            return new ServletInputStream() {
              public int read() throws IOException {
                return stream.read();
              }

              public int available() {
                return body.length();
              }
            };
          }
        };

    request.setScheme("http");
    request.setServerName("localhost");
    request.setContextPath("/geoserver");
    request.setMethod("POST");
    request.setRequestURI("http://localhost/geoserver/ows");
    request.setContentType("application/xml");
    request.setBodyContent(body);

    MockHttpServletResponse response = new MockHttpServletResponse();

    request.setupAddParameter("strict", "true");

    dispatcher.handleRequest(request, response);
    assertEquals("Hello world!", response.getOutputStreamContent());
  }
예제 #6
0
  @Test
  public void testDoFilterOk() throws IOException, ServletException {
    req.setRequestURI("/img/blub.jpg");
    me.doFilter(req, resp, chain);

    assertEquals(req, chain.getLastRequest());
    assertEquals(resp, chain.getLastResponse());
  }
예제 #7
0
  public void testHttpErrorCodeException() throws Exception {
    URL url = getClass().getResource("applicationContext.xml");

    FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(url.toString());

    Dispatcher dispatcher = (Dispatcher) context.getBean("dispatcher");

    MockHttpServletRequest request =
        new MockHttpServletRequest() {
          String encoding;

          public int getServerPort() {
            return 8080;
          }

          public String getCharacterEncoding() {
            return encoding;
          }

          public void setCharacterEncoding(String encoding) {
            this.encoding = encoding;
          }
        };

    request.setScheme("http");
    request.setServerName("localhost");

    request.setContextPath("/geoserver");
    request.setMethod("GET");

    CodeExpectingHttpServletResponse response =
        new CodeExpectingHttpServletResponse(new MockHttpServletResponse());

    request.setupAddParameter("service", "hello");
    request.setupAddParameter("request", "httpErrorCodeException");
    request.setupAddParameter("version", "1.0.0");

    request.setRequestURI(
        "http://localhost/geoserver/ows?service=hello&request=hello&message=HelloWorld");
    request.setQueryString("service=hello&request=hello&message=HelloWorld");

    dispatcher.handleRequest(request, response);
    assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatusCode());
  }
예제 #8
0
  @SuppressWarnings("unchecked")
  @Test
  public void testDoFilterRedirectDeny() throws IOException, ServletException {
    req.setRequestURI("/admin/bla.jsp");

    // getSession() returns null otherwise - violation of the spec
    req.setSession(new MockHttpSession());

    SessionToken tok = new SessionToken("login", 1234, false);
    SecManager.getInstance(ctx).setSessionToken(req, tok);

    me.doFilter(req, resp, chain);

    assertNull(chain.getLastRequest());
    assertNull(chain.getLastResponse());

    assertFalse(resp.wasRedirectSent());
    Map<String, MockRequestDispatcher> m = req.getRequestDispatcherMap();
    assertEquals("/deny.do", m.get(m.keySet().iterator().next()).getPath());
  }
예제 #9
0
  public void testErrorSavedOnRequestOnNon304ErrorCodeException() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContextPath("/geoserver");
    request.setRequestURI("/geoserver/hello");
    request.setMethod("get");

    Dispatcher dispatcher = new Dispatcher();

    Request req = new Request();
    req.httpRequest = request;
    dispatcher.init(req);

    MockHttpServletResponse response = new MockHttpServletResponse();
    req.setHttpResponse(response);

    RuntimeException genericError = new HttpErrorCodeException(500, "Internal Server Error");
    dispatcher.exception(genericError, null, req);

    assertEquals("Exception did not get saved", genericError, req.error);
  }
예제 #10
0
  public void testNoErrorOn304ErrorCodeException() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContextPath("/geoserver");
    request.setRequestURI("/geoserver/hello");
    request.setMethod("get");

    Dispatcher dispatcher = new Dispatcher();

    Request req = new Request();
    req.httpRequest = request;
    dispatcher.init(req);

    MockHttpServletResponse response = new MockHttpServletResponse();
    req.setHttpResponse(response);

    RuntimeException error = new HttpErrorCodeException(304, "Not Modified");
    dispatcher.exception(error, null, req);

    assertNull("Exception erroneously saved", req.error);
  }
예제 #11
0
  public void testReadOpPost() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContextPath("/geoserver");
    request.setRequestURI("/geoserver/hello");
    request.setMethod("post");

    String body = "<Hello service=\"hello\"/>";

    MockServletInputStream input = new MockServletInputStream(body.getBytes());

    Dispatcher dispatcher = new Dispatcher();

    BufferedReader buffered = new BufferedReader(new InputStreamReader(input));
    buffered.mark(2048);

    Map map = dispatcher.readOpPost(buffered);

    assertNotNull(map);
    assertEquals("Hello", map.get("request"));
    assertEquals("hello", map.get("service"));
  }
예제 #12
0
  public void testDispatchWithNamespace() throws Exception {
    URL url = getClass().getResource("applicationContextNamespace.xml");
    FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(url.toString());

    Dispatcher dispatcher = (Dispatcher) context.getBean("dispatcher");
    MockHttpServletRequest request =
        new MockHttpServletRequest() {
          String encoding;

          public int getServerPort() {
            return 8080;
          }

          public String getCharacterEncoding() {
            return encoding;
          }

          public void setCharacterEncoding(String encoding) {
            this.encoding = encoding;
          }
        };

    request.setScheme("http");
    request.setServerName("localhost");

    request.setContextPath("/geoserver");
    request.setMethod("POST");

    MockHttpServletResponse response = new MockHttpServletResponse();

    request.setContentType("application/xml");
    request.setBodyContent(
        "<h:Hello service='hello' message='Hello world!' xmlns:h='http://hello.org' />");
    request.setRequestURI("http://localhost/geoserver/hello");

    dispatcher.handleRequest(request, response);
    assertEquals("Hello world!", response.getOutputStreamContent());

    request.setBodyContent(
        "<h:Hello service='hello' message='Hello world!' xmlns:h='http://hello.org/v2' />");

    response = new MockHttpServletResponse();
    dispatcher.handleRequest(request, response);
    assertEquals("Hello world!:V2", response.getOutputStreamContent());
  }
예제 #13
0
  public void testReadContextAndPath() throws Exception {
    Dispatcher dispatcher = new Dispatcher();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContextPath("/geoserver");
    request.setRequestURI("/geoserver/hello");
    request.setMethod("get");

    Request req = new Request();
    req.httpRequest = request;

    dispatcher.init(req);
    assertNull(req.context);
    assertEquals("hello", req.path);

    request.setRequestURI("/geoserver/foo/hello");
    dispatcher.init(req);
    assertEquals("foo", req.context);
    assertEquals("hello", req.path);

    request.setRequestURI("/geoserver/foo/baz/hello/");
    dispatcher.init(req);
    assertEquals("foo/baz", req.context);
    assertEquals("hello", req.path);
  }
예제 #14
0
  public void testParseKVP() throws Exception {
    URL url = getClass().getResource("applicationContext.xml");

    FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(url.toString());

    Dispatcher dispatcher = (Dispatcher) context.getBean("dispatcher");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContextPath("/geoserver");

    request.setupAddParameter("service", "hello");
    request.setupAddParameter("request", "Hello");
    request.setupAddParameter("message", "Hello world!");

    request.setQueryString("service=hello&request=hello&message=Hello World!");

    Request req = new Request();
    req.setHttpRequest(request);

    dispatcher.parseKVP(req);

    Message message = (Message) dispatcher.parseRequestKVP(Message.class, req);
    assertEquals(new Message("Hello world!"), message);
  }
예제 #15
0
  @Before
  public void setUp() throws Exception {
    ctx = new MockServletContext();
    ctx.setInitParameter("security-config", "/WEB-INF/security-config.xml");
    ctx.setResourceAsStream(
        "/WEB-INF/security-config.xml", SecConfigTest.getSecurityConfigInputStream());

    MockFilterConfig conf = new MockFilterConfig();
    conf.setupServletContext(ctx);

    req = new MockHttpServletRequest();
    req.setContextPath("contextPath/");

    resp = new MockHttpServletResponse();
    chain = new MockFilterChain();

    me = new SecFilter();
    me.init(conf);
  }
  @Test
  public void testHarvestImageMosaic() throws Exception {
    // Upload of the Mosaic via REST
    URL zip = MockData.class.getResource("watertemp.zip");
    InputStream is = null;
    byte[] bytes;
    try {
      is = zip.openStream();
      bytes = IOUtils.toByteArray(is);
    } finally {
      IOUtils.closeQuietly(is);
    }

    MockHttpServletResponse response =
        putAsServletResponse(
            "/rest/workspaces/gs/coveragestores/watertemp2/file.imagemosaic",
            bytes,
            "application/zip");
    assertEquals(201, response.getStatusCode());

    // check the response contents
    String content = response.getOutputStreamContent();
    Document d = dom(new ByteArrayInputStream(content.getBytes()));

    XMLAssert.assertXpathEvaluatesTo("watertemp2", "//coverageStore/name", d);
    XMLAssert.assertXpathEvaluatesTo("ImageMosaic", "//coverageStore/type", d);

    // check the coverage is actually there
    CoverageStoreInfo storeInfo = getCatalog().getCoverageStoreByName("watertemp2");
    assertNotNull(storeInfo);
    CoverageInfo ci = getCatalog().getCoverageByName("watertemp2");
    assertNotNull(ci);
    assertEquals(storeInfo, ci.getStore());

    // Harvesting of the Mosaic
    URL zipHarvest = getClass().getResource("test-data/harvesting.zip");
    // Extract a Byte array from the zip file
    is = null;
    try {
      is = zipHarvest.openStream();
      bytes = IOUtils.toByteArray(is);
    } finally {
      IOUtils.closeQuietly(is);
    }
    // Create the POST request
    MockHttpServletRequest request =
        createRequest("/rest/workspaces/gs/coveragestores/watertemp2/file.imagemosaic");
    request.setMethod("POST");
    request.setContentType("application/zip");
    request.setBodyContent(bytes);
    request.setHeader("Content-type", "application/zip");
    // Get The response
    response = dispatch(request);
    // Get the Mosaic Reader
    GridCoverageReader reader = storeInfo.getGridCoverageReader(null, GeoTools.getDefaultHints());
    // Test if all the TIME DOMAINS are present
    String[] metadataNames = reader.getMetadataNames();
    assertNotNull(metadataNames);
    assertEquals("true", reader.getMetadataValue("HAS_TIME_DOMAIN"));
    assertEquals(
        "2008-10-31T00:00:00.000Z,2008-11-01T00:00:00.000Z,2008-11-02T00:00:00.000Z",
        reader.getMetadataValue(metadataNames[0]));
  }
  @Test
  public void testHarvestImageMosaicWithDirectory() throws Exception {
    // Upload of the Mosaic via REST
    URL zip = MockData.class.getResource("watertemp.zip");
    InputStream is = null;
    byte[] bytes;
    try {
      is = zip.openStream();
      bytes = IOUtils.toByteArray(is);
    } finally {
      IOUtils.closeQuietly(is);
    }

    MockHttpServletResponse response =
        putAsServletResponse(
            "/rest/workspaces/gs/coveragestores/watertemp3/file.imagemosaic",
            bytes,
            "application/zip");
    assertEquals(201, response.getStatusCode());

    // check the response contents
    String content = response.getOutputStreamContent();
    Document d = dom(new ByteArrayInputStream(content.getBytes()));

    XMLAssert.assertXpathEvaluatesTo("watertemp3", "//coverageStore/name", d);
    XMLAssert.assertXpathEvaluatesTo("ImageMosaic", "//coverageStore/type", d);

    // check the coverage is actually there
    CoverageStoreInfo storeInfo = getCatalog().getCoverageStoreByName("watertemp3");
    assertNotNull(storeInfo);
    CoverageInfo ci = getCatalog().getCoverageByName("watertemp3");
    assertNotNull(ci);
    assertEquals(storeInfo, ci.getStore());

    // Harvesting of the Mosaic
    URL zipHarvest = getClass().getResource("test-data/harvesting.zip");
    File zipFile = DataUtilities.urlToFile(zipHarvest);
    // Creation of another zip file which is a copy of the one before
    File newZip = new File(zipFile.getParentFile(), "harvesting2.zip");
    // Copy the content of the first zip to the second
    FileUtils.copyFile(zipFile, newZip);
    File outputDirectory = new File(zipFile.getParentFile(), "harvesting");
    outputDirectory.mkdir();
    RESTUtils.unzipFile(newZip, outputDirectory);
    // Create the POST request
    MockHttpServletRequest request =
        createRequest("/rest/workspaces/gs/coveragestores/watertemp3/external.imagemosaic");
    request.setMethod("POST");
    request.setContentType("text/plain");
    request.setBodyContent("file:///" + outputDirectory.getAbsolutePath());
    request.setHeader("Content-type", "text/plain");
    // Get The response
    response = dispatch(request);
    // Get the Mosaic Reader
    GridCoverageReader reader = storeInfo.getGridCoverageReader(null, GeoTools.getDefaultHints());
    // Test if all the TIME DOMAINS are present
    String[] metadataNames = reader.getMetadataNames();
    assertNotNull(metadataNames);
    assertEquals("true", reader.getMetadataValue("HAS_TIME_DOMAIN"));
    assertEquals(
        "2008-10-31T00:00:00.000Z,2008-11-01T00:00:00.000Z,2008-11-02T00:00:00.000Z",
        reader.getMetadataValue(metadataNames[0]));
    // Removal of the temporary directory
    FileUtils.deleteDirectory(outputDirectory);
  }
  @Test
  public void testHarvestExternalImageMosaic() throws Exception {
    // Check if an already existing directory called "mosaic" is present
    URL resource = getClass().getResource("test-data/mosaic");
    if (resource != null) {
      File oldDir = DataUtilities.urlToFile(resource);
      if (oldDir.exists()) {
        FileUtils.deleteDirectory(oldDir);
      }
    }
    // reading of the mosaic directory
    File mosaic = readMosaic();
    // Creation of the builder for building a new CoverageStore
    CatalogBuilder builder = new CatalogBuilder(getCatalog());
    // Definition of the workspace associated to the coverage
    WorkspaceInfo ws = getCatalog().getWorkspaceByName("gs");
    // Creation of a CoverageStore
    CoverageStoreInfo store = builder.buildCoverageStore("watertemp4");
    store.setURL(DataUtilities.fileToURL(mosaic).toExternalForm());
    store.setWorkspace(ws);
    ImageMosaicFormat imageMosaicFormat = new ImageMosaicFormat();
    store.setType((imageMosaicFormat.getName()));
    // Addition to the catalog
    getCatalog().add(store);
    builder.setStore(store);
    // Input reader used for reading the mosaic folder
    GridCoverage2DReader reader = null;
    // Reader used for checking if the mosaic has been configured correctly
    StructuredGridCoverage2DReader reader2 = null;

    try {
      // Selection of the reader to use for the mosaic
      reader = (GridCoverage2DReader) imageMosaicFormat.getReader(DataUtilities.fileToURL(mosaic));

      // configure the coverage
      configureCoverageInfo(builder, store, reader);

      // check the coverage is actually there
      CoverageStoreInfo storeInfo = getCatalog().getCoverageStoreByName("watertemp4");
      assertNotNull(storeInfo);
      CoverageInfo ci = getCatalog().getCoverageByName("mosaic");
      assertNotNull(ci);
      assertEquals(storeInfo, ci.getStore());

      // Harvesting of the Mosaic
      URL zipHarvest = getClass().getResource("test-data/harvesting.zip");
      // Extract a Byte array from the zip file
      InputStream is = null;
      byte[] bytes;
      try {
        is = zipHarvest.openStream();
        bytes = IOUtils.toByteArray(is);
      } finally {
        IOUtils.closeQuietly(is);
      }
      // Create the POST request
      MockHttpServletRequest request =
          createRequest("/rest/workspaces/gs/coveragestores/watertemp4/file.imagemosaic");
      request.setMethod("POST");
      request.setContentType("application/zip");
      request.setBodyContent(bytes);
      request.setHeader("Content-type", "application/zip");
      // Get The response
      MockHttpServletResponse response = dispatch(request);
      // Get the Mosaic Reader
      reader2 =
          (StructuredGridCoverage2DReader)
              storeInfo.getGridCoverageReader(null, GeoTools.getDefaultHints());
      // Test if all the TIME DOMAINS are present
      String[] metadataNames = reader2.getMetadataNames();
      assertNotNull(metadataNames);
      assertEquals("true", reader2.getMetadataValue("HAS_TIME_DOMAIN"));
      assertEquals(
          "2008-10-31T00:00:00.000Z,2008-11-01T00:00:00.000Z,2008-11-02T00:00:00.000Z",
          reader2.getMetadataValue(metadataNames[0]));
      // Removal of all the data associated to the mosaic
      reader2.delete(true);
    } finally {
      // Reader disposal
      if (reader != null) {
        try {
          reader.dispose();
        } catch (Throwable t) {
          // Does nothing
        }
      }
      if (reader2 != null) {
        try {
          reader2.dispose();
        } catch (Throwable t) {
          // Does nothing
        }
      }
    }
  }