List of usage examples for org.springframework.mock.web MockHttpServletResponse getStatus
@Override public int getStatus()
From source file:org.geoserver.catalog.rest.StyleTest.java
@Test public void testPostSLDPackage() throws Exception { Catalog cat = getCatalog();//w ww . ja va 2s . co m assertNull(cat.getStyleByName("foo")); URL zip = getClass().getResource("test-data/foo.zip"); byte[] bytes = FileUtils.readFileToByteArray(DataUtilities.urlToFile(zip)); MockHttpServletResponse response = postAsServletResponse("/rest/styles", bytes, "application/zip"); assertEquals(201, response.getStatus()); assertNotNull(cat.getStyleByName("foo")); Document d = getAsDOM("/rest/styles/foo.sld"); assertEquals("StyledLayerDescriptor", d.getDocumentElement().getNodeName()); XpathEngine engine = XMLUnit.newXpathEngine(); NodeList list = engine.getMatchingNodes( "//sld:StyledLayerDescriptor/sld:NamedLayer/sld:UserStyle/sld:FeatureTypeStyle/sld:Rule/sld:PointSymbolizer/sld:Graphic/sld:ExternalGraphic/sld:OnlineResource", d); assertEquals(1, list.getLength()); Element onlineResource = (Element) list.item(0); assertEquals("gear.png", onlineResource.getAttribute("xlink:href")); assertNotNull(getCatalog().getResourceLoader().find("styles/gear.png")); assertNotNull(getCatalog().getResourceLoader().find("styles/foo.sld")); }
From source file:org.geoserver.catalog.rest.StyleTest.java
@Test public void testPutSLDPackage() throws Exception { testPostAsSLD();/*from ww w.j av a 2 s .c o m*/ Catalog cat = getCatalog(); assertNotNull(cat.getStyleByName("foo")); URL zip = getClass().getResource("test-data/foo.zip"); byte[] bytes = FileUtils.readFileToByteArray(DataUtilities.urlToFile(zip)); MockHttpServletResponse response = putAsServletResponse("/rest/styles/foo.zip", bytes, "application/zip"); assertEquals(200, response.getStatus()); assertNotNull(cat.getStyleByName("foo")); Document d = getAsDOM("/rest/styles/foo.sld"); assertEquals("StyledLayerDescriptor", d.getDocumentElement().getNodeName()); XpathEngine engine = XMLUnit.newXpathEngine(); NodeList list = engine.getMatchingNodes( "//sld:StyledLayerDescriptor/sld:NamedLayer/sld:UserStyle/sld:FeatureTypeStyle/sld:Rule/sld:PointSymbolizer/sld:Graphic/sld:ExternalGraphic/sld:OnlineResource", d); assertEquals(1, list.getLength()); Element onlineResource = (Element) list.item(0); assertEquals("gear.png", onlineResource.getAttribute("xlink:href")); assertNotNull(getCatalog().getResourceLoader().find("styles/gear.png")); assertNotNull(getCatalog().getResourceLoader().find("styles/foo.sld")); }
From source file:org.geoserver.h2.RestTest.java
public void genericCreateDataStoreUsingRestTest(String dataStoreName, String mimeType, byte[] content) throws Exception { // perform a PUT request, a new H2 data store should be created // we also require that all available feature types should be created String path = String.format("/rest/workspaces/%s/datastores/%s/file.h2?configure=all", WORKSPACE_NAME, dataStoreName);//from ww w. j a v a2s .c om MockHttpServletResponse response = putAsServletResponse(path, content, mimeType); // we should get a HTTP 201 status code meaning that the data store was created assertThat(response.getStatus(), is(201)); // let's see if the data store was correctly created DataStoreInfo storeInfo = getCatalog().getDataStoreByName(dataStoreName); assertThat(storeInfo, notNullValue()); DataAccess store = storeInfo.getDataStore(null); assertThat(store, notNullValue()); List<Name> names = store.getNames(); assertThat(store, notNullValue()); // check that at least the table points is available Name found = names.stream().filter(name -> name != null && name.getLocalPart().equals("points")).findFirst() .orElse(null); assertThat(found, notNullValue()); // check that the points layer was correctly created LayerInfo layerInfo = getCatalog().getLayerByName(new NameImpl(WORKSPACE_URI, "points")); assertThat(layerInfo, notNullValue()); assertThat(layerInfo.getResource(), notNullValue()); assertThat(layerInfo.getResource(), instanceOf(FeatureTypeInfo.class)); // check that we have the expected features FeatureTypeInfo featureTypeInfo = (FeatureTypeInfo) layerInfo.getResource(); int count = featureTypeInfo.getFeatureSource(null, null).getCount(Query.ALL); assertThat(count, is(4)); }
From source file:org.geoserver.importer.ImporterTestSupport.java
protected void assertErrorResponse(MockHttpServletResponse resp, String... errs) throws UnsupportedEncodingException { assertEquals(400, resp.getStatus()); //TODO: Implement JSON error response /*// w w w . ja va 2 s. c o m JSONObject json = JSONObject.fromObject(resp.getContentAsString()); JSONArray errors = json.getJSONArray("errors"); assertNotNull("Expected error array", errors); assertEquals(errs.length, errors.size()); for (int i = 0; i < errs.length; i++) { assertEquals(errors.get(i), errs[i]); } */ }
From source file:org.geoserver.importer.rest.ImporterIntegrationTest.java
void testDirectExecuteInternal(boolean async) throws Exception { // set a callback to check that the request spring context is passed to the job thread RequestContextListener listener = applicationContext.getBean(RequestContextListener.class); SecurityContextHolder.getContext().setAuthentication(createAuthentication()); final boolean[] invoked = { false }; listener.setCallBack((request, user, resource) -> { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); assertThat(request, notNullValue()); assertThat(resource, notNullValue()); assertThat(auth, notNullValue()); invoked[0] = true;/*from w w w . ja v a 2 s. com*/ }); File gmlFile = file("gml/poi.gml2.gml"); String wsName = getCatalog().getDefaultWorkspace().getName(); // @formatter:off String contextDefinition = "{\n" + " \"import\": {\n" + " \"targetWorkspace\": {\n" + " \"workspace\": {\n" + " \"name\": \"" + wsName + "\"\n" + " }\n" + " },\n" + " \"data\": {\n" + " \"type\": \"file\",\n" + " \"file\": \"" + jsonSafePath(gmlFile) + "\"\n" + " }," + " targetStore: {\n" + " dataStore: {\n" + " name: \"h2\",\n" + " }\n" + " }\n" + " }\n" + "}"; // @formatter:on JSONObject json = (JSONObject) json(postAsServletResponse( "/rest/imports?exec=true" + (async ? "&async=true" : ""), contextDefinition, "application/json")); // print(json); String state = null; int importId; if (async) { importId = json.getJSONObject("import").getInt("id"); for (int i = 0; i < 60 * 2 * 2; i++) { json = (JSONObject) getAsJSON("/rest/imports/" + importId); // print(json); state = json.getJSONObject("import").getString("state"); if ("INIT".equals(state) || "RUNNING".equals(state) || "PENDING".equals(state)) { Thread.sleep(500); } } } else { state = json.getJSONObject("import").getString("state"); importId = json.getJSONObject("import").getInt("id"); } Thread.sleep(500); assertEquals("COMPLETE", state); assertThat(invoked[0], is(true)); checkPoiImport(); //Test delete MockHttpServletResponse resp = deleteAsServletResponse("/rest/imports/" + importId); assertEquals(204, resp.getStatus()); }
From source file:org.geoserver.importer.rest.ImportTaskControllerTest.java
private Integer putZip(String path) throws Exception { File file = new File(path); InputStream stream;//from w w w . ja va 2s. c o m if (file.exists()) { stream = new FileInputStream(file); } else { stream = ImporterTestSupport.class.getResourceAsStream("../test-data/" + path); } MockHttpServletResponse resp = postAsServletResponse(RestBaseController.ROOT_PATH + "/imports", ""); assertEquals(201, resp.getStatus()); assertNotNull(resp.getHeader("Location")); String[] split = resp.getHeader("Location").split("/"); Integer id = Integer.parseInt(split[split.length - 1]); ImportContext context = importer.getContext(id); MockHttpServletRequest req = createRequest( RestBaseController.ROOT_PATH + "/imports/" + id + "/tasks/" + file.getName()); req.setContentType("application/zip"); req.addHeader("Content-Type", "application/zip"); req.setMethod("PUT"); req.setContent(org.apache.commons.io.IOUtils.toByteArray(stream)); resp = dispatch(req); assertEquals(201, resp.getStatus()); context = importer.getContext(context.getId()); assertNull(context.getData()); assertEquals(1, context.getTasks().size()); ImportTask task = context.getTasks().get(0); assertTrue(task.getData() instanceof SpatialFile); return id; }
From source file:org.geoserver.importer.rest.ImportTaskControllerTest.java
private Integer putZipAsURL(String zip) throws Exception { MockHttpServletResponse resp = postAsServletResponse(RestBaseController.ROOT_PATH + "/imports", ""); assertEquals(201, resp.getStatus()); assertNotNull(resp.getHeader("Location")); String[] split = resp.getHeader("Location").split("/"); Integer id = Integer.parseInt(split[split.length - 1]); ImportContext context = importer.getContext(id); MockHttpServletRequest req = createRequest(RestBaseController.ROOT_PATH + "/imports/" + id + "/tasks/"); MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>(1); form.add("url", new File(zip).getAbsoluteFile().toURI().toString()); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); final HttpHeaders headers = new HttpHeaders(); new FormHttpMessageConverter().write(form, MediaType.APPLICATION_FORM_URLENCODED, new HttpOutputMessage() { @Override//from w w w . ja v a 2s . c om public OutputStream getBody() throws IOException { return stream; } @Override public HttpHeaders getHeaders() { return headers; } }); req.setContent(stream.toByteArray()); req.setMethod("POST"); req.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE); req.addHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE); resp = dispatch(req); assertEquals(201, resp.getStatus()); context = importer.getContext(context.getId()); assertNull(context.getData()); assertEquals(1, context.getTasks().size()); ImportTask task = context.getTasks().get(0); assertTrue(task.getData() instanceof SpatialFile); return id; }
From source file:org.geoserver.importer.rest.ImportTaskControllerTest.java
@Test public void testDeleteTask() throws Exception { MockHttpServletResponse resp = postAsServletResponse(RestBaseController.ROOT_PATH + "/imports", ""); assertEquals(201, resp.getStatus()); assertNotNull(resp.getHeader("Location")); String[] split = resp.getHeader("Location").split("/"); Integer id = Integer.parseInt(split[split.length - 1]); ImportContext context = importer.getContext(id); File dir = unpack("shape/archsites_epsg_prj.zip"); unpack("shape/bugsites_esri_prj.tar.gz", dir); new File(dir, "extra.file").createNewFile(); File[] files = dir.listFiles(); Part[] parts = new Part[files.length]; for (int i = 0; i < files.length; i++) { parts[i] = new FilePart(files[i].getName(), files[i]); }//w w w . ja va 2s . c o m MultipartRequestEntity multipart = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); multipart.writeRequest(bout); MockHttpServletRequest req = createRequest(RestBaseController.ROOT_PATH + "/imports/" + id + "/tasks"); req.setContentType(multipart.getContentType()); req.addHeader("Content-Type", multipart.getContentType()); req.setMethod("POST"); req.setContent(bout.toByteArray()); resp = dispatch(req); context = importer.getContext(context.getId()); assertEquals(2, context.getTasks().size()); req = createRequest(RestBaseController.ROOT_PATH + "/imports/" + id + "/tasks/1"); req.setMethod("DELETE"); resp = dispatch(req); assertEquals(204, resp.getStatus()); context = importer.getContext(context.getId()); assertEquals(1, context.getTasks().size()); }
From source file:org.geoserver.importer.rest.ImportTaskControllerTest.java
@Test public void testPostMultiPartFormData() throws Exception { MockHttpServletResponse resp = postAsServletResponse(RestBaseController.ROOT_PATH + "/imports", ""); assertEquals(201, resp.getStatus()); assertNotNull(resp.getHeader("Location")); String[] split = resp.getHeader("Location").split("/"); Integer id = Integer.parseInt(split[split.length - 1]); ImportContext context = importer.getContext(id); assertNull(context.getData());/*from ww w.j a va 2 s . c o m*/ assertTrue(context.getTasks().isEmpty()); File dir = unpack("shape/archsites_epsg_prj.zip"); Part[] parts = new Part[] { new FilePart("archsites.shp", new File(dir, "archsites.shp")), new FilePart("archsites.dbf", new File(dir, "archsites.dbf")), new FilePart("archsites.shx", new File(dir, "archsites.shx")), new FilePart("archsites.prj", new File(dir, "archsites.prj")) }; MultipartRequestEntity multipart = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); multipart.writeRequest(bout); MockHttpServletRequest req = createRequest(RestBaseController.ROOT_PATH + "/imports/" + id + "/tasks"); req.setContentType(multipart.getContentType()); req.addHeader("Content-Type", multipart.getContentType()); req.setMethod("POST"); req.setContent(bout.toByteArray()); resp = dispatch(req); context = importer.getContext(context.getId()); assertNull(context.getData()); assertEquals(1, context.getTasks().size()); ImportTask task = context.getTasks().get(0); assertTrue(task.getData() instanceof SpatialFile); assertEquals(ImportTask.State.READY, task.getState()); }
From source file:org.geoserver.importer.rest.ImportTaskControllerTest.java
private ImportContext uploadGeotiffAndVerify(String taskName, InputStream geotiffResourceStream, String contentType, String createImportBody, String creationContentType) throws Exception { // upload tif or zip file containing a tif and verify the results MockHttpServletResponse resp = postAsServletResponse(RestBaseController.ROOT_PATH + "/imports", createImportBody, creationContentType); assertEquals(201, resp.getStatus()); assertNotNull(resp.getHeader("Location")); String[] split = resp.getHeader("Location").split("/"); Integer id = Integer.parseInt(split[split.length - 1]); ImportContext context = importer.getContext(id); MockHttpServletRequest req = createRequest( RestBaseController.ROOT_PATH + "/imports/" + id + "/tasks/" + taskName); req.setContentType(contentType);/* www. ja v a2s. c o m*/ req.addHeader("Content-Type", contentType); req.setMethod("PUT"); req.setContent(org.apache.commons.io.IOUtils.toByteArray(geotiffResourceStream)); resp = dispatch(req); assertEquals(201, resp.getStatus()); context = importer.getContext(context.getId()); assertNull(context.getData()); assertEquals(1, context.getTasks().size()); ImportTask task = context.getTasks().get(0); assertEquals(ImportTask.State.READY, task.getState()); ImportData importData = task.getData(); assertTrue(importData instanceof SpatialFile); DataFormat format = importData.getFormat(); assertTrue(format instanceof GridFormat); return context; }