/** * Test that calling session.isNew() works for the initial as well as subsequent requests. */ @Test public void testIsNew() throws Exception { Callback c = new Callback() { @Override public void call(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpSession session = request.getSession(); response.getWriter().write(Boolean.toString(session.isNew())); } }; servlet.getServletContext().setAttribute("callback", c); WebConversation wc = new WebConversation(); WebRequest req = new GetMethodWebRequest(String.format("http://localhost:%d/test", port)); req.setParameter("cmd", QueryCommand.CALLBACK.name()); req.setParameter("param", "callback"); WebResponse response = wc.getResponse(req); assertEquals("true", response.getText()); response = wc.getResponse(req); assertEquals("false", response.getText()); }
/** * Check that our session persists. The values we pass in as query params are used to set * attributes on the session. */ @Test public void testSessionPersists1() throws Exception { String key = "value_testSessionPersists1"; String value = "Foo"; WebConversation wc = new WebConversation(); WebRequest req = new GetMethodWebRequest(String.format("http://localhost:%d/test", port)); req.setParameter("cmd", QueryCommand.SET.name()); req.setParameter("param", key); req.setParameter("value", value); WebResponse response = wc.getResponse(req); String sessionId = response.getNewCookieValue("JSESSIONID"); assertNotNull("No apparent session cookie", sessionId); // The request retains the cookie from the prior response... req.setParameter("cmd", QueryCommand.GET.name()); req.setParameter("param", key); req.removeParameter("value"); response = wc.getResponse(req); assertEquals(value, response.getText()); }
protected void loadResponseText() throws IOException { if (_responseText != null) throw new IllegalStateException( "May only invoke loadResponseText once" ); _responseText = ""; InputStream inputStream = getInputStream(); try { final int contentLength = this.encodedUsingGZIP() ? -1 : getContentLength(); int bytesRemaining = contentLength < 0 ? Integer.MAX_VALUE : contentLength; byte[] bytes = readFromStream( inputStream, bytesRemaining ); readTags( bytes ); _responseText = new String( bytes, getCharacterSet() ); _inputStream = new ByteArrayInputStream( bytes ); if (HttpUnitOptions.isCheckContentLength() && contentLength >= 0 && bytes.length != contentLength) { throw new IOException("Truncated message. Expected length: " + contentLength + ", Actual length: " + bytes.length); } } finally { inputStream.close(); } }
/** * get the received Page * @return the received page * @throws SAXException */ HTMLPage getReceivedPage() throws SAXException { if (_page == null) { try { _parsingPage = true; if (!isHTML()) throw new NotHTMLException( getContentType() ); _page = new HTMLPage( this, _frame, _baseURL, _baseTarget, getCharacterSet() ); _page.parse( getText(), _pageURL ); if (_page == null) throw new IllegalStateException( "replaceText called in the middle of getReceivedPage()" ); ((HTMLDocumentImpl) _page.getRootNode()).getWindow().setProxy( this ); } catch (IOException e) { HttpUnitUtils.handleException(e); throw new RuntimeException( e.toString() ); } finally { _parsingPage = false; } } return _page; }
public void invokingEndpoint(WebRequest req) throws Exception { WebResponse response = newClient().getResponse(req); assertEquals("text/xml", response.getContentType()); assertTrue("utf-8".equalsIgnoreCase(response.getCharacterSet())); Document doc = StaxUtils.read(response.getInputStream()); assertNotNull(doc); addNamespace("h", "http://apache.org/hello_world_soap_http/types"); assertValid("/s:Envelope/s:Body", doc); assertValid("//h:sayHiResponse", doc); }
@Test public void testGetWSDLWithIncludes() throws Exception { ServletUnitClient client = newClient(); client.setExceptionsThrownOnErrorStatus(true); WebRequest req = new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter3?wsdl"); WebResponse res = client.getResponse(req); assertEquals(200, res.getResponseCode()); assertEquals("text/xml", res.getContentType()); Document doc = StaxUtils.read(res.getInputStream()); assertNotNull(doc); assertXPathEquals("//xsd:include/@schemaLocation", "http://localhost/mycontext/services/greeter3?xsd=hello_world_includes2.xsd", doc.getDocumentElement()); req = new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter3?xsd=hello_world_includes2.xsd"); res = client.getResponse(req); assertEquals(200, res.getResponseCode()); assertEquals("text/xml", res.getContentType()); doc = StaxUtils.read(res.getInputStream()); assertNotNull(doc); assertValid("//xsd:complexType[@name='ErrorCode']", doc); }
RedirectWebRequest( WebResponse response ) { super( response.getURL(), response.getHeaderField( "Location" ), response.getFrame(), response.getFrameName() ); if (response.getReferer() != null) setHeaderField( "Referer", response.getReferer() ); }
/** * check whether redirect is configured * @param response * @return */ private boolean redirectConfigured( WebResponse response ) { boolean isAutoredirect=getClient().getClientProperties().isAutoRedirect(); boolean hasLocation=response.getHeaderField( "Location" ) != null; int responseCode=response.getResponseCode(); boolean result=isAutoredirect && responseCode >= HttpURLConnection.HTTP_MOVED_PERM && responseCode <= HttpURLConnection.HTTP_MOVED_TEMP && hasLocation; return result; }
public void testDynamicReport() throws Exception { ServletRunner sr = new ServletRunner( getClass().getResourceAsStream("/webwork/web.xml") ); // (1) use the web.xml file to define mappings ServletUnitClient client = sr.newClient(); // (2) create a client to invoke the application WebResponse r = client.getResponse( "http://localhost/generateReport.action" ); // (3) invoke the servlet w/o authorization String fname=r.getHeaderField("CONTENT-DISPOSITION"); fname = fname.substring(fname.indexOf("=")+1); FileOutputStream fos = new FileOutputStream( new File(System.getProperty("user.dir")+ "/target/" + fname)); InputStream is = r.getInputStream(); StreamUtils.copy(is, fos); is.close(); fos.close(); }
/** * Examines the headers in the response and throws an exception if appropriate. * @parm response - the response to validate **/ private void validateHeaders( WebResponse response ) throws HttpException { if (!getExceptionsThrownOnErrorStatus()) return; // see feature request [ 914314 ] Add HttpException.getResponse for better reporting // for possible improvements here if (response.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) { throw new HttpInternalErrorException( response.getURL() ); } else if (response.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { throw new HttpNotFoundException( response.getResponseMessage(), response.getURL() ); } else if (response.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST) { throw new HttpException( response.getResponseCode(), response.getResponseMessage(), response.getURL() ); } }
@Test public void testGetImportedXSD() throws Exception { ServletUnitClient client = newClient(); client.setExceptionsThrownOnErrorStatus(true); WebRequest req = new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter?wsdl"); WebResponse res = client.getResponse(req); assertEquals(200, res.getResponseCode()); String text = res.getText(); assertEquals("text/xml", res.getContentType()); assertTrue(text.contains(CONTEXT_URL + "/services/greeter?wsdl=test_import.xsd")); req = new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter?wsdl=test_import.xsd"); res = client.getResponse(req); assertEquals(200, res.getResponseCode()); text = res.getText(); assertEquals("text/xml", res.getContentType()); assertTrue("the xsd should contain the completType SimpleStruct", text.contains("<complexType name=\"SimpleStruct\">")); }
/** * Returns the character set used in this response. **/ public String getCharacterSet() { if (_characterSet == null) { readContentTypeHeader(); if (_characterSet == null) setCharacterSet( getHeaderField( "Charset" ) ); if (_characterSet == null) setCharacterSet( HttpUnitOptions.getDefaultCharacterSet() ); } return _characterSet; }
/** * Constructs a web request using a base URL, a relative URL string, and a target. **/ protected WebRequest( WebResponse referer, Element sourceElement, URL urlBase, String urlString, String target ) { this( urlBase, urlString, referer.getFrame(), target != null ? target : referer.getBaseTarget() ); _sourceElement = sourceElement; _referringPage = referer; setHeaderField( REFERER_HEADER_NAME, referer.getURL().toExternalForm() ); }
private void verifyPhase(WebConversation conversation, String jobId, String expectedPhase) throws Throwable { // GET request to the phase resource. String resourceUrl = serviceUrl + "/" + jobId + "/phase"; WebResponse response = get(conversation, resourceUrl, "text/plain"); log.debug(Util.getResponseHeaders(response)); log.debug("Response.getText():\r\n" + response.getText()); assertEquals("GET response Content-Type header to " + resourceUrl + " is incorrect", "text/plain", response.getContentType()); assertEquals("response should return only a string of the phase.", expectedPhase, response.getText()); }
/** * Returns the contents of an included script, given its src attribute. * @param srcAttribute the location of the script. * @return the contents of the script. * @throws java.io.IOException if there is a problem retrieving the script */ String getIncludedScript( String srcAttribute ) throws IOException { WebRequest req = new GetMethodWebRequest( getBaseURL(), srcAttribute ); WebWindow window = getResponse().getWindow(); if (window == null) throw new IllegalStateException( "Unable to retrieve script included by this response, since it was loaded by getResource(). Use getResponse() instead."); return window.getResource( req ).getText(); }
public void produceHTML(WebResponse r, PrintStream out) throws IOException, SAXException { out.println(); Document tree = Util.getDom4j(r); find(tree, r,"//IMG|//SCRIPT", "src"); find(tree, r,"//LINK", "href"); // replpace @import in CSS for( Element style : (List<Element>)tree.selectNodes("//STYLE") ) { String text = style.getText(); findInCSS(text, r.getURL()); } out.print(r.getText()); out.println(); }
/** * infer the refresh Header * @param refreshHeader */ private void inferRefreshHeader( String refreshHeader ) { String originalHeader = getHeaderField( "Refresh" ); // System.err.println("original='"+originalHeader+"'\nrefreshHeader='"+refreshHeader+"'"); if (originalHeader == null) { _refreshHeader = refreshHeader; } }
private void inferContentType( String contentTypeHeader ) { String originalHeader = getHeaderField( "Content-type" ); if (originalHeader == null || originalHeader.indexOf( "charset" ) < 0) { setContentTypeHeader( contentTypeHeader ); } }
/** * Returns the URL of the codebase used to find the applet classes */ public URL getCodeBaseURL() throws MalformedURLException { return new URL( _response.getURL(), getCodeBase() ); }
/** * Constructs a response object from a servlet response. * @param frame the target frame on which the response will be displayed * @param url the url from which the response was received * @param response the response populated by the servlet **/ ServletUnitWebResponse( ServletUnitClient client, FrameSelector frame, URL url, HttpServletResponse response, boolean throwExceptionOnError ) throws IOException { super( client, frame, url ); _response = (ServletUnitHttpResponse) response; /** make sure that any IO exception for HTML received page happens here, not later. **/ if (getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST || !throwExceptionOnError) { defineRawInputStream( new ByteArrayInputStream( _response.getContents() ) ); if (getContentType().startsWith( "text" )) loadResponseText(); } }