/** * Test a complete scenario. User sends .wmc file via POST and gets back the generated file path. * Then user asks via GET to get back the file stored on the server * * @throws Exception */ @Test public void testWMCService() throws Exception { // valid wmc file content String fileContent = "<ViewContext xmlns=\"http://www.opengis.net/context\" version=\"1.1.0\" id=\"OpenLayers_Context_133\" xsi:schemaLocation=\"http://www.opengis.net/context http://schemas.opengis.net/context/1.1.0/context.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><General><Window width=\"1233\" height=\"342\"/><BoundingBox minx=\"-201405.7589\" miny=\"2245252.767\" maxx=\"598866.8058\" maxy=\"2467226.179\" SRS=\"EPSG:2154\"/><Title/><Extension><ol:maxExtent xmlns:ol=\"http://openlayers.org/context\" minx=\"47680.03567\" miny=\"2267644.975\" maxx=\"349781.0112\" maxy=\"2444833.970\"/></Extension></General><LayerList><Layer queryable=\"0\" hidden=\"0\"><Server service=\"OGC:WMS\" version=\"1.1.1\"><OnlineResource xlink:type=\"simple\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"http://drebretagne-geobretagne.int.lsn.camptocamp.com/geoserver/wms\"/></Server><Name>topp:communes_geofla</Name><Title>communes_geofla</Title><FormatList><Format current=\"1\">image/jpeg</Format></FormatList><StyleList><Style current=\"1\"><Name/><Title>Default</Title></Style></StyleList><Extension><ol:maxExtent xmlns:ol=\"http://openlayers.org/context\" minx=\"47680.03567\" miny=\"2267644.975\" maxx=\"349781.0112\" maxy=\"2444833.970\"/><ol:numZoomLevels xmlns:ol=\"http://openlayers.org/context\">16</ol:numZoomLevels><ol:units xmlns:ol=\"http://openlayers.org/context\">m</ol:units><ol:isBaseLayer xmlns:ol=\"http://openlayers.org/context\">true</ol:isBaseLayer><ol:displayInLayerSwitcher xmlns:ol=\"http://openlayers.org/context\">true</ol:displayInLayerSwitcher><ol:singleTile xmlns:ol=\"http://openlayers.org/context\">false</ol:singleTile></Extension></Layer></LayerList></ViewContext>"; // wmc file to be send _requestPost.setRequestURI(DOMAIN_NAME + DocController.WMC_URL); // fake URI, Rest style _requestPost.setContent(fileContent.getBytes()); // fake body containing wmc file _controller.storeWMCFile(_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.WMC_URL)); _requestGet.setRequestURI(DOMAIN_NAME + filePath); // fake URI, Rest style _controller.getWMCFile(_requestGet, _responseGet); assertEquals(200, _responseGet.getStatus()); // 200 OK assertEquals(fileContent, _responseGet.getContentAsString().trim()); // content sent is // back }
/** * 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(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 }
private MockHttpServletRequest prepareEmptyRequest() { final MockHttpServletRequest res = new MockHttpServletRequest(); res.setMethod("POST"); res.setContent(new byte[0]); return res; }
public void testRunWithOnlyFormName() throws Exception { MockHttpServletRequest request = constructMockRequest("POST", "/document/validate", WILDCARD); request.setContent(("document=").getBytes()); // NOTE: need space between periods. MockHttpServletResponse response = invoke(request); assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus()); }
@AdviseWith(adviceClasses = {PropsUtilAdvice.class}) @Test public void testPrepareRequest() throws Exception { PropsUtilAdvice.setProps( PropsKeys.INTRABAND_MAILBOX_REAPER_THREAD_ENABLED, Boolean.FALSE.toString()); PropsUtilAdvice.setProps( PropsKeys.INTRABAND_MAILBOX_STORAGE_LIFE, String.valueOf(Long.MAX_VALUE)); Serializer serializer = new Serializer(); serializer.writeString(_SERVLET_CONTEXT_NAME); serializer.writeObject(new SPIAgentRequest(_mockHttpServletRequest)); Method depositMailMethod = ReflectionUtil.getDeclaredMethod(MailboxUtil.class, "depositMail", ByteBuffer.class); long receipt = (Long) depositMailMethod.invoke(null, serializer.toByteBuffer()); byte[] data = new byte[8]; BigEndianCodec.putLong(data, 0, receipt); HttpClientSPIAgent httpClientSPIAgent = new HttpClientSPIAgent( _spiConfiguration, new MockRegistrationReference(new MockIntraband())); MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); mockHttpServletRequest.setContent(data); HttpServletRequest httpServletRequest = httpClientSPIAgent.prepareRequest(mockHttpServletRequest); Assert.assertNotNull(httpServletRequest.getAttribute(WebKeys.SPI_AGENT_REQUEST)); }
// Can't get this to work... again the annoying "HttpMediaTypeNotSupportedException: Content type // 'application/json' not supported" @Test @Ignore public void updateProposal_UpdatedPackageIsToBeSubmittedWhileExistingIsDraft_ShouldMakeRestCallAndPersistWithStatusSubmitted() throws Exception { final ProposedConceptPackage proposedConcept = new ProposedConceptPackage(); proposedConcept.setStatus(PackageStatus.DRAFT); final ProposedConceptService cpServiceMock = mock(ProposedConceptService.class); when(cpServiceMock.getProposedConceptPackageById(1)).thenReturn(proposedConcept); mockStatic(Context.class); when(Context.getService(ProposedConceptService.class)).thenReturn(cpServiceMock); final RestOperations restOperationsMock = mock(RestOperations.class); ReflectionTestUtils.setField( controller.getSubmitProposal(), "submissionRestTemplate", restOperationsMock); request = new MockHttpServletRequest("PUT", "/cpm/proposals/1"); request.addHeader("Accept", "application/json"); request.addHeader("Content-Type", "application/json"); final String payload = "{\"name\":\"test\",\"description\":\"test\",\"email\":\"[email protected]\",\"concepts\":[]}"; request.setContent(payload.getBytes()); adapter.handle(request, response, controller); verify(restOperationsMock) .postForObject( "http://localhost:8080/openmrs/ws/cpm/dictionarymanager/proposals", new SubmissionDto(), SubmissionResponseDto.class); assertThat(proposedConcept.getStatus(), equalTo(PackageStatus.SUBMITTED)); }
@Test public void body() throws IOException { final MockHttpServletRequest httpRequest = prepareEmptyRequest(); httpRequest.setContent("abcd".getBytes()); final Request req = RequestUtils.convert(httpRequest); assertThat(req.getBodyAsString(), is("abcd")); }
public void testRun() throws Exception { MockHttpServletRequest request = constructMockRequest("POST", "/document/validate", WILDCARD); request.setContent("document=Foobar".getBytes()); MockHttpServletResponse response = invoke(request); assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus()); JSONArray errors = (JSONArray) new JSONObject(response.getContentAsString()).get("errors"); assertEquals(0, errors.length()); }
@Test public void getBody() throws Exception { byte[] content = "Hello World".getBytes("UTF-8"); mockRequest.setContent(content); byte[] result = FileCopyUtils.copyToByteArray(request.getBody()); assertArrayEquals("Invalid content returned", content, result); }
@Test public void wrapPostRequestsWithoutContentType() throws Exception { request.setMethod("POST"); request.setContent(new byte[0]); filter.doFilter(request, response, filterChain); verify(filterChain).doFilter(any(FormEncodedHttpServletRequestWrapper.class), eq(response)); }
@Test public void content() throws IOException { byte[] bytes = "body".getBytes(Charset.defaultCharset()); request.setContent(bytes); assertEquals(bytes.length, request.getContentLength()); assertNotNull(request.getInputStream()); assertEquals( "body", StreamUtils.copyToString(request.getInputStream(), Charset.defaultCharset())); }
public MockHttpServletRequest newPostRequest(String requestURI, String content) { MockHttpServletRequest request = request(RequestMethod.POST, requestURI); try { request.setContent(content.getBytes("UTF-8")); } catch (Exception e) { throw new RuntimeException(e); } return request; }
public MockHttpServletRequest newPostRequest(String requestURI, Object content) { MockHttpServletRequest request = request(RequestMethod.POST, requestURI); try { String json = new ObjectMapper().writeValueAsString(content); request.setContent(json.getBytes("UTF-8")); } catch (Exception e) { throw new RuntimeException(e); } return request; }
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); }
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 mailFeedback_confirmNotification_subscribe_fail() throws Exception { request.addHeader("x-amz-sns-message-type", "SubscriptionConfirmation"); request.setContent( toJsonBytes(ImmutableMap.of("SubscribeURL", "http://httpbin.org/status/500"))); try { controller.mailFeedback(request); fail("IOException expected"); } catch (IOException expected) { } }
@Test public void parametersURLEncoded() throws IOException { final MockHttpServletRequest httpRequest = prepareEmptyRequest(); httpRequest.setQueryString("param1%20name=param1%20value"); httpRequest.setContent("param2%20name=param2%20value".getBytes()); httpRequest.addHeader("content-type", "application/x-www-form-urlencoded"); final Request req = RequestUtils.convert(httpRequest); assertThat(req.getParameterNames(), containsInAnyOrder("param1%20name", "param2%20name")); assertThat(req.getParameterValues("param1%20name"), contains("param1%20value")); assertThat(req.getParameterValues("param2%20name"), contains("param2%20value")); }
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); }
public static Object sendAndReceive( RouterController controller, MockHttpServletRequest request, final String action, String method, boolean namedParameter, Object data, final Object result) { MockHttpServletResponse response = new MockHttpServletResponse(); int tid = (int) (Math.random() * 1000); Map<String, Object> edRequest = createRequestJson(action, method, namedParameter, tid, data); request.setContent(ControllerUtil.writeAsByte(edRequest)); try { controller.router(request, response, Locale.ENGLISH); } catch (IOException e) { fail("call controller.router: " + e.getMessage()); } List<ExtDirectResponse> responses = readDirectResponses(response.getContentAsByteArray()); assertThat(responses).hasSize(1); ExtDirectResponse edResponse = responses.get(0); assertThat(edResponse.getAction()).isEqualTo(action); assertThat(edResponse.getMethod()).isEqualTo(method); assertThat(edResponse.getTid()).isEqualTo(tid); assertThat(edResponse.getWhere()).isNull(); if (result == null) { assertThat(edResponse.getType()).isEqualTo("exception"); assertThat(edResponse.getResult()).isNull(); assertThat(edResponse.getMessage()).isEqualTo("Server Error"); } else { assertThat(edResponse.getType()).isEqualTo("rpc"); assertThat(edResponse.getMessage()).isNull(); if (result == Void.TYPE) { assertThat(edResponse.getResult()).isNull(); } else if (result instanceof Class<?>) { Object r = ControllerUtil.convertValue(edResponse.getResult(), (Class<?>) result); return r; } else if (result instanceof TypeReference) { Object r = ControllerUtil.convertValue(edResponse.getResult(), (TypeReference<?>) result); return r; } else { assertThat(edResponse.getResult()).isEqualTo(result); } } return edResponse.getResult(); }
@Test public void shouldEditAConceptSource() throws Exception { final String newName = "updated name"; SimpleObject conceptSource = new SimpleObject(); conceptSource.add("name", newName); String json = new ObjectMapper().writeValueAsString(conceptSource); MockHttpServletRequest req = request(RequestMethod.POST, getURI() + "/" + getUuid()); req.setContent(json.getBytes()); handle(req); Assert.assertEquals(newName, service.getConceptSourceByUuid(getUuid()).getName()); }
public void testRunWithErrors() throws Exception { MockHttpServletRequest request = constructMockRequest("POST", "/document/validate", WILDCARD); request.setContent(("document=foobar.foobar").getBytes()); // NOTE: need space between periods. MockHttpServletResponse response = invoke(request); assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus()); System.out.println(response.getContentAsString()); JSONArray errors = (JSONArray) new JSONObject(response.getContentAsString()).get("errors"); // the following will change whenever the configuration or validator functionaliy changes // but it doesn't indicate what particular errors are new/missing // assertEquals(3, errors.length()); assertTrue(errors.get(0).toString().length() > 0); }
public void testJSValidatorDoesntRunFromNonHomeDir() throws Exception { System.setProperty("REDPEN_HOME", "."); MockHttpServletRequest request = constructMockRequest("POST", "/document/validate/json", WILDCARD, APPLICATION_JSON); request.setContent( String.format( "{\"document\":\"Test, this is a test.\",\"format\":\"json2\",\"documentParser\":\"PLAIN\",\"config\":{\"lang\":\"en\",\"validators\":{\"JavaScript\":{\"properties\":{\"script-path\":\"%s\"}}}}}", "resources/js") .getBytes()); MockHttpServletResponse response = invoke(request); assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus()); JSONArray errors = new JSONObject(response.getContentAsString()).getJSONArray("errors"); assertEquals(0, errors.length()); }
@Test public void mailFeedback_bounce() throws Exception { request.addHeader("x-amz-sns-message-type", "Notification"); String message = q( "{" + " 'notificationType':'Bounce'," + " 'bounce':{" + " 'bounceSubType':'General'," + " 'bounceType':'Permanent'," + " 'reportingMTA':'dsn; a8-26.smtp-out.amazonses.com'," + " 'bouncedRecipients':[" + " {" + " 'status':'5.1.1'," + " 'action':'failed'," + " 'diagnosticCode':'smtp; 550 5.1.1 user unknown'," + " 'emailAddress':'*****@*****.**'" + " }" + " ]," + " 'timestamp':'2014-10-26T15:10:47.544Z'," + " 'feedbackId':'000001494d02704b-70c6bee9-bd31-4e2b-aeb3-2adcc5104d25-000000'" + " }," + " 'mail':{" + " 'timestamp':'2014-10-26T15:10:45.000Z'," + " 'source':'*****@*****.**'," + " 'messageId':'000001494d026e8c-49338317-a0e9-4b69-b351-cb2e368778ee-000000'," + " 'destination':[" + " '*****@*****.**'" + " ]" + " }" + "}"); request.setContent( toJsonBytes( ImmutableMap.of( "Type", "Notification", "MessageId", "cb0b3e1f-01f0-531c-90f5-72d810c7f6a7", "Message", message))); controller.mailFeedback(request); verify(accountService).muteEmail(asList("*****@*****.**")); }
@Test public void shouldCreateAConceptSource() throws Exception { long originalCount = getAllCount(); SimpleObject conceptSource = new SimpleObject(); conceptSource.add("name", "test name"); conceptSource.add("description", "test description"); String json = new ObjectMapper().writeValueAsString(conceptSource); MockHttpServletRequest req = request(RequestMethod.POST, getURI()); req.setContent(json.getBytes()); SimpleObject newConceptSource = deserialize(handle(req)); Assert.assertNotNull(PropertyUtils.getProperty(newConceptSource, "uuid")); Assert.assertEquals(originalCount + 1, getAllCount()); }
@Test public void canPutFileWithResourceTag() throws ServletException, IOException { String fileName = "test_ALF-18821.txt"; // VtiIfHeaderAction PUT handler expects the file to have already been created (in most cases) FileInfo createdFile = fileFolderService.create(docLib, fileName, ContentModel.TYPE_CONTENT); request = new MockHttpServletRequest( "PUT", "/alfresco/" + shortSiteId + "/documentLibrary/" + fileName); String fileContent = "This is the test file's content."; request.setContent(fileContent.getBytes()); request.addHeader("If", "(<rt:792589C1-2E8F-410E-BC91-4EF42DA88D3C@00862604462>)"); dispatcher.service(request, response); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); String retContent = fileFolderService.getReader(createdFile.getNodeRef()).getContentString(); assertEquals(fileContent, retContent); }
public void testJSValidatorRuns() throws Exception { System.setProperty("REDPEN_HOME", "src/test"); MockHttpServletRequest request = constructMockRequest("POST", "/document/validate/json", WILDCARD, APPLICATION_JSON); request.setContent( String.format( "{\"document\":\"Test, this is a test.\",\"format\":\"json2\",\"documentParser\":\"PLAIN\",\"config\":{\"lang\":\"en\",\"validators\":{\"JavaScript\":{\"properties\":{\"script-path\":\"%s\"}}}}}", "resources/js") .getBytes()); MockHttpServletResponse response = invoke(request); assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus()); JSONArray errors = new JSONObject(response.getContentAsString()).getJSONArray("errors"); assertTrue(errors.length() > 0); for (int i = 0; i < errors.length(); ++i) { JSONObject o = errors.getJSONObject(i).getJSONArray("errors").getJSONObject(0); assertEquals("[pass.js] called", o.getString("message")); } }
/** * 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")); }