List of usage examples for java.net HttpURLConnection getContentType
public String getContentType()
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceIntegrationTest.java
@Test @RunAsClient/*from w w w . j av a 2s.c o m*/ public void testCreatePackageFromDRLAsEntry(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/packages"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.setDoOutput(true); //Send request InputStream in = null; OutputStream out = null; try { in = getClass().getResourceAsStream("simple_rules.drl"); out = connection.getOutputStream(); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType()); //logger.log(LogLevel, IOUtils.toString(connection.getInputStream())); }
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceIntegrationTest.java
@Test @RunAsClient// www . ja v a 2s . co m public void testUpdatePackageFromJAXB(@ArquillianResource URL baseURL) throws Exception { //create a package for fixtures Package p = createTestPackage("testUpdatePackageFromJAXB"); p.setDescription("desc for testUpdatePackageFromJAXB"); p.getMetadata().setCheckinComment("checkincomment for testUpdatePackageFromJAXB"); JAXBContext context = JAXBContext.newInstance(p.getClass()); Marshaller marshaller = context.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.marshal(p, sw); String xml = sw.toString(); URL url = new URL(baseURL, "rest/packages"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_XML); connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length)); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(xml); wr.flush(); wr.close(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection.getContentType()); //System.out.println(IOUtils.toString(connection.getInputStream())); Package result = unmarshalPackageXML(connection.getInputStream()); assertEquals("testUpdatePackageFromJAXB", result.getTitle()); assertEquals("desc for testUpdatePackageFromJAXB", result.getDescription()); assertNotNull(result.getPublished()); assertEquals(new URL(baseURL, "rest/packages/testUpdatePackageFromJAXB/source").toExternalForm(), result.getSourceLink().toString()); assertEquals(new URL(baseURL, "rest/packages/testUpdatePackageFromJAXB/binary").toExternalForm(), result.getBinaryLink().toString()); PackageMetadata pm = result.getMetadata(); assertFalse(pm.isArchived()); assertNotNull(pm.getCreated()); assertNotNull(pm.getUuid()); assertEquals("checkincomment for testUpdatePackageFromJAXB", pm.getCheckinComment()); //Test update package Package p2 = createTestPackage("testUpdatePackageFromJAXB"); p2.setDescription("update package testUpdatePackageFromJAXB"); PackageMetadata meta = new PackageMetadata(); meta.setCheckinComment("checkInComment: update package testUpdatePackageFromJAXB"); p2.setMetadata(meta); JAXBContext context2 = JAXBContext.newInstance(p2.getClass()); Marshaller marshaller2 = context2.createMarshaller(); StringWriter sw2 = new StringWriter(); marshaller2.marshal(p2, sw2); String xml2 = sw2.toString(); URL url2 = new URL(baseURL, "rest/packages/testUpdatePackageFromJAXB"); HttpURLConnection connection2 = (HttpURLConnection) url2.openConnection(); connection2.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection2.setRequestMethod("PUT"); connection2.setRequestProperty("Content-Type", MediaType.APPLICATION_XML); connection2.setRequestProperty("Content-Length", Integer.toString(xml2.getBytes().length)); connection2.setUseCaches(false); //connection2.setDoInput(true); connection2.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection2.getOutputStream()); out.write(xml2); out.close(); connection2.getInputStream(); //Verify URL url3 = new URL(baseURL, "rest/packages/testUpdatePackageFromJAXB"); HttpURLConnection connection3 = (HttpURLConnection) url3.openConnection(); connection3.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection3.setRequestMethod("GET"); connection3.setRequestProperty("Accept", MediaType.APPLICATION_XML); connection3.connect(); assertEquals(200, connection3.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection3.getContentType()); //System.out.println("------------------------"); //System.out.println(IOUtils.toString(connection.getInputStream())); Package p3 = unmarshalPackageXML(connection3.getInputStream()); assertEquals("testUpdatePackageFromJAXB", p3.getTitle()); assertEquals("update package testUpdatePackageFromJAXB", p3.getDescription()); assertNotNull(p3.getPublished()); assertEquals(new URL(baseURL, "rest/packages/testUpdatePackageFromJAXB/source").toExternalForm(), p3.getSourceLink().toString()); assertEquals(new URL(baseURL, "rest/packages/testUpdatePackageFromJAXB/binary").toExternalForm(), p3.getBinaryLink().toString()); PackageMetadata pm3 = p3.getMetadata(); assertFalse(pm3.isArchived()); assertNotNull(pm3.getCreated()); assertNotNull(pm3.getUuid()); assertEquals("checkInComment: update package testUpdatePackageFromJAXB", pm3.getCheckinComment()); }
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceIntegrationTest.java
@Test @RunAsClient//from w w w. j a v a 2 s . com public void testRenamePackageFromXML(@ArquillianResource URL baseURL) throws Exception { //create a package for testing Package p = createTestPackage("testRenamePackageFromXML"); p.setDescription("desc for testRenamePackageFromXML"); JAXBContext context = JAXBContext.newInstance(p.getClass()); Marshaller marshaller = context.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.marshal(p, sw); String xml = sw.toString(); URL url = new URL(baseURL, "rest/packages"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_XML); connection.setRequestProperty("Content-Length", Integer.toString(xml.getBytes().length)); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(xml); wr.flush(); wr.close(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection.getContentType()); //System.out.println(IOUtils.toString(connection.getInputStream())); Package result = unmarshalPackageXML(connection.getInputStream()); assertEquals("testRenamePackageFromXML", result.getTitle()); assertEquals("desc for testRenamePackageFromXML", result.getDescription()); assertNotNull(result.getPublished()); assertEquals(new URL(baseURL, "rest/packages/testRenamePackageFromXML/source").toExternalForm(), result.getSourceLink().toString()); assertEquals(new URL(baseURL, "rest/packages/testRenamePackageFromXML/binary").toExternalForm(), result.getBinaryLink().toString()); PackageMetadata pm = result.getMetadata(); assertFalse(pm.isArchived()); assertNotNull(pm.getCreated()); assertNotNull(pm.getUuid()); //Test rename package p.setDescription("renamed package testRenamePackageFromXML"); p.setTitle("testRenamePackageFromXMLNew"); JAXBContext context2 = JAXBContext.newInstance(p.getClass()); Marshaller marshaller2 = context2.createMarshaller(); StringWriter sw2 = new StringWriter(); marshaller2.marshal(p, sw2); String xml2 = sw2.toString(); URL url2 = new URL(baseURL, "rest/packages/testRenamePackageFromXML"); HttpURLConnection connection2 = (HttpURLConnection) url2.openConnection(); connection2.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection2.setRequestMethod("PUT"); connection2.setRequestProperty("Content-Type", MediaType.APPLICATION_XML); connection2.setRequestProperty("Content-Length", Integer.toString(xml2.getBytes().length)); connection2.setUseCaches(false); //connection2.setDoInput(true); connection2.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection2.getOutputStream()); out.write(xml2); out.close(); connection2.getInputStream(); //assertEquals (200, connection2.getResponseCode()); //Verify the new package is available after renaming URL url3 = new URL(baseURL, "rest/packages/testRenamePackageFromXMLNew"); HttpURLConnection conn3 = (HttpURLConnection) url3.openConnection(); conn3.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); conn3.setRequestMethod("GET"); conn3.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); conn3.connect(); //System.out.println(GetContent(conn)); assertEquals(200, conn3.getResponseCode()); assertEquals(MediaType.APPLICATION_ATOM_XML, conn3.getContentType()); InputStream in = conn3.getInputStream(); assertNotNull(in); Document<Entry> doc = abdera.getParser().parse(in); Entry entry = doc.getRoot(); assertEquals(baseURL.getPath() + "rest/packages/testRenamePackageFromXMLNew", entry.getBaseUri().getPath()); assertEquals("testRenamePackageFromXMLNew", entry.getTitle()); assertTrue(entry.getPublished() != null); assertEquals("renamed package testRenamePackageFromXML", entry.getSummary()); //Verify the old package does not exist after renaming URL url4 = new URL(baseURL, "rest/packages/testRenamePackageFromXML"); HttpURLConnection conn4 = (HttpURLConnection) url4.openConnection(); conn4.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); conn4.setRequestMethod("GET"); conn4.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); conn4.connect(); //System.out.println(IOUtils.toString(connection.getInputStream())); assertEquals(404, conn4.getResponseCode()); //Roll back changes. Abdera abdera = new Abdera(); AbderaClient client = new AbderaClient(abdera); client.addCredentials(baseURL.toExternalForm(), null, null, new org.apache.commons.httpclient.UsernamePasswordCredentials("admin", "admin")); ClientResponse resp = client .delete(new URL(baseURL, "rest/packages/testRenamePackageFromXMLNew").toExternalForm()); assertEquals(ResponseType.SUCCESS, resp.getType()); //Verify the package is indeed deleted URL url5 = new URL(baseURL, "rest/packages/testRenamePackageFromXMLNew"); HttpURLConnection conn5 = (HttpURLConnection) url5.openConnection(); conn5.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); conn5.setRequestMethod("GET"); conn5.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); conn5.connect(); //System.out.println(IOUtils.toString(connection.getInputStream())); assertEquals(404, conn5.getResponseCode()); }
From source file:org.apache.hadoop.crypto.key.kms.KMSClientProvider.java
private <T> T call(HttpURLConnection conn, Map jsonOutput, int expectedResponse, Class<T> klass, int authRetryCount) throws IOException { T ret = null;//ww w .j av a2 s.c o m try { if (jsonOutput != null) { writeJson(jsonOutput, conn.getOutputStream()); } } catch (IOException ex) { IOUtils.closeStream(conn.getInputStream()); throw ex; } if ((conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN && (conn.getResponseMessage().equals(ANONYMOUS_REQUESTS_DISALLOWED) || conn.getResponseMessage().contains(INVALID_SIGNATURE))) || conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { // Ideally, this should happen only when there is an Authentication // failure. Unfortunately, the AuthenticationFilter returns 403 when it // cannot authenticate (Since a 401 requires Server to send // WWW-Authenticate header as well).. KMSClientProvider.this.authToken = new DelegationTokenAuthenticatedURL.Token(); if (authRetryCount > 0) { String contentType = conn.getRequestProperty(CONTENT_TYPE); String requestMethod = conn.getRequestMethod(); URL url = conn.getURL(); conn = createConnection(url, requestMethod); conn.setRequestProperty(CONTENT_TYPE, contentType); return call(conn, jsonOutput, expectedResponse, klass, authRetryCount - 1); } } try { AuthenticatedURL.extractToken(conn, authToken); } catch (AuthenticationException e) { // Ignore the AuthExceptions.. since we are just using the method to // extract and set the authToken.. (Workaround till we actually fix // AuthenticatedURL properly to set authToken post initialization) } HttpExceptionUtils.validateResponse(conn, expectedResponse); if (conn.getContentType() != null && conn.getContentType().trim().toLowerCase().startsWith(APPLICATION_JSON_MIME) && klass != null) { ObjectMapper mapper = new ObjectMapper(); InputStream is = null; try { is = conn.getInputStream(); ret = mapper.readValue(is, klass); } finally { IOUtils.closeStream(is); } } return ret; }
From source file:fr.xebia.servlet.filter.ExpiresFilterTest.java
protected void validate(HttpServlet servlet, Integer expectedMaxAgeInSeconds, int expectedResponseStatusCode) throws Exception { // SETUP/*from ww w .ja va 2 s . c o m*/ int port = 6666; Server server = new Server(port); Context context = new Context(server, "/", Context.SESSIONS); MockFilterConfig filterConfig = new MockFilterConfig(); filterConfig.addInitParameter("ExpiresDefault", "access plus 1 minute"); filterConfig.addInitParameter("ExpiresByType text/xml; charset=utf-8", "access plus 3 minutes"); filterConfig.addInitParameter("ExpiresByType text/xml", "access plus 5 minutes"); filterConfig.addInitParameter("ExpiresByType text", "access plus 7 minutes"); filterConfig.addInitParameter("ExpiresExcludedResponseStatusCodes", "304, 503"); ExpiresFilter expiresFilter = new ExpiresFilter(); expiresFilter.init(filterConfig); context.addFilter(new FilterHolder(expiresFilter), "/*", Handler.REQUEST); context.addServlet(new ServletHolder(servlet), "/test"); server.start(); try { Calendar.getInstance(TimeZone.getTimeZone("GMT")); long timeBeforeInMillis = System.currentTimeMillis(); // TEST HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test") .openConnection(); // VALIDATE Assert.assertEquals(expectedResponseStatusCode, httpURLConnection.getResponseCode()); for (Entry<String, List<String>> field : httpURLConnection.getHeaderFields().entrySet()) { System.out.println(field.getKey() + ": " + StringUtils.arrayToDelimitedString(field.getValue().toArray(), ", ")); } Integer actualMaxAgeInSeconds; String cacheControlHeader = httpURLConnection.getHeaderField("Cache-Control"); if (cacheControlHeader == null) { actualMaxAgeInSeconds = null; } else { actualMaxAgeInSeconds = null; // System.out.println("Evaluate Cache-Control:" + // cacheControlHeader); StringTokenizer cacheControlTokenizer = new StringTokenizer(cacheControlHeader, ","); while (cacheControlTokenizer.hasMoreTokens() && actualMaxAgeInSeconds == null) { String cacheDirective = cacheControlTokenizer.nextToken(); // System.out.println("\tEvaluate directive: " + // cacheDirective); StringTokenizer cacheDirectiveTokenizer = new StringTokenizer(cacheDirective, "="); // System.out.println("countTokens=" + // cacheDirectiveTokenizer.countTokens()); if (cacheDirectiveTokenizer.countTokens() == 2) { String key = cacheDirectiveTokenizer.nextToken().trim(); String value = cacheDirectiveTokenizer.nextToken().trim(); if (key.equalsIgnoreCase("max-age")) { actualMaxAgeInSeconds = Integer.parseInt(value); } } } } if (expectedMaxAgeInSeconds == null) { Assert.assertNull("actualMaxAgeInSeconds '" + actualMaxAgeInSeconds + "' should be null", actualMaxAgeInSeconds); return; } Assert.assertNotNull(actualMaxAgeInSeconds); int deltaInSeconds = Math.abs(actualMaxAgeInSeconds - expectedMaxAgeInSeconds); Assert.assertTrue("actualMaxAgeInSeconds: " + actualMaxAgeInSeconds + ", expectedMaxAgeInSeconds: " + expectedMaxAgeInSeconds + ", request time: " + timeBeforeInMillis + " for content type " + httpURLConnection.getContentType(), deltaInSeconds < 2000); } finally { server.stop(); } }
From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java
/** * * @param httpParam/*from w ww . j a v a 2s . c o m*/ * @return */ public static SimpleHttpResult httpRequest(SimpleHttpParam httpParam) { String url = httpParam.getUrl(); Map<String, Object> parameters = httpParam.getParameters(); String sMethod = httpParam.getMethod(); String charSet = httpParam.getCharSet(); boolean sslVerify = httpParam.isSslVerify(); int maxResultSize = httpParam.getMaxResultSize(); Map<String, Object> headers = httpParam.getHeaders(); int readTimeout = httpParam.getReadTimeout(); int connectTimeout = httpParam.getConnectTimeout(); boolean ignoreContentIfUnsuccess = httpParam.isIgnoreContentIfUnsuccess(); boolean hostnameVerify = httpParam.isHostnameVerify(); TrustKeyStore trustKeyStore = httpParam.getTrustKeyStore(); ClientKeyStore clientKeyStore = httpParam.getClientKeyStore(); if (url == null || url.trim().length() == 0) { throw new IllegalArgumentException("invalid url : " + url); } if (maxResultSize <= 0) { throw new IllegalArgumentException("maxResultSize must be positive : " + maxResultSize); } Charset.forName(charSet); HttpURLConnection urlConn = null; URL destURL = null; String baseUrl = url.trim(); if (!baseUrl.toLowerCase().startsWith(HTTPS_PREFIX) && !baseUrl.toLowerCase().startsWith(HTTP_PREFIX)) { baseUrl = HTTP_PREFIX + baseUrl; } String method = null; if (sMethod != null) { method = sMethod.toUpperCase(); } if (method == null || !(method.equals(HTTP_METHOD_POST) || method.equals(HTTP_METHOD_GET))) { throw new IllegalArgumentException("invalid http method : " + method); } int index = baseUrl.indexOf("?"); if (index > 0) { baseUrl = urlEncode(baseUrl, charSet); } else if (index == 0) { throw new IllegalArgumentException("invalid url : " + url); } String queryString = mapToQueryString(parameters, charSet); String targetUrl = ""; if (method.equals(HTTP_METHOD_POST)) { targetUrl = baseUrl; } else { if (index > 0) { targetUrl = baseUrl + "&" + queryString; } else { targetUrl = baseUrl + "?" + queryString; } } try { destURL = new URL(targetUrl); urlConn = (HttpURLConnection) destURL.openConnection(); setSSLSocketFactory(urlConn, sslVerify, hostnameVerify, trustKeyStore, clientKeyStore); boolean hasContentType = false; boolean hasUserAgent = false; for (String key : headers.keySet()) { if ("Content-Type".equalsIgnoreCase(key)) { hasContentType = true; } if ("user-agent".equalsIgnoreCase(key)) { hasUserAgent = true; } } if (!hasContentType) { headers.put("Content-Type", "application/x-www-form-urlencoded; charset=" + charSet); } if (!hasUserAgent) { headers.put("user-agent", "PlatSystem"); } if (headers != null && !headers.isEmpty()) { for (Entry<String, Object> entry : headers.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); List<String> values = makeStringList(value); for (String v : values) { urlConn.addRequestProperty(key, v); } } } urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setAllowUserInteraction(false); urlConn.setUseCaches(false); urlConn.setRequestMethod(method); urlConn.setConnectTimeout(connectTimeout); urlConn.setReadTimeout(readTimeout); if (method.equals(HTTP_METHOD_POST)) { String postData = queryString.length() == 0 ? httpParam.getPostData() : queryString; if (postData != null && postData.trim().length() > 0) { OutputStream os = urlConn.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, charSet); osw.write(postData); osw.flush(); osw.close(); } } int responseCode = urlConn.getResponseCode(); Map<String, List<String>> responseHeaders = urlConn.getHeaderFields(); String contentType = urlConn.getContentType(); SimpleHttpResult result = new SimpleHttpResult(responseCode); result.setHeaders(responseHeaders); result.setContentType(contentType); if (responseCode != 200 && ignoreContentIfUnsuccess) { return result; } InputStream is = urlConn.getInputStream(); byte[] temp = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int readBytes = is.read(temp); while (readBytes > 0) { baos.write(temp, 0, readBytes); readBytes = is.read(temp); } String resultString = new String(baos.toByteArray(), charSet); //new String(buffer.array(), charSet); baos.close(); result.setContent(resultString); return result; } catch (Exception e) { logger.warn("connection error : " + e.getMessage()); return new SimpleHttpResult(e); } finally { if (urlConn != null) { urlConn.disconnect(); } } }
From source file:org.vfny.geoserver.wfs.servlets.TestWfsPost.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*w w w.j av a2 s . c om*/ * * @param request servlet request * @param response servlet response * * @throws ServletException DOCUMENT ME! * @throws IOException DOCUMENT ME! */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestString = request.getParameter("body"); String urlString = request.getParameter("url"); boolean doGet = (requestString == null) || requestString.trim().equals(""); if ((urlString == null)) { PrintWriter out = response.getWriter(); StringBuffer urlInfo = request.getRequestURL(); if (urlInfo.indexOf("?") != -1) { urlInfo.delete(urlInfo.indexOf("?"), urlInfo.length()); } String geoserverUrl = urlInfo.substring(0, urlInfo.indexOf("/", 8)) + request.getContextPath(); response.setContentType("text/html"); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); out.println("<html>"); out.println("<head>"); out.println("<title>TestWfsPost</title>"); out.println("</head>"); out.println("<script language=\"JavaScript\">"); out.println("function doNothing() {"); out.println("}"); out.println("function sendRequest() {"); out.println(" if (checkURL()==true) {"); out.print(" document.frm.action = \""); out.print(urlInfo.toString()); out.print("\";\n"); out.println(" document.frm.target = \"_blank\";"); out.println(" document.frm.submit();"); out.println(" }"); out.println("}"); out.println("function checkURL() {"); out.println(" if (document.frm.url.value==\"\") {"); out.println(" alert(\"Please give URL before you sumbit this form!\");"); out.println(" return false;"); out.println(" } else {"); out.println(" return true;"); out.println(" }"); out.println("}"); out.println("function clearRequest() {"); out.println("document.frm.body.value = \"\";"); out.println("}"); out.println("</script>"); out.println("<body>"); out.println("<form name=\"frm\" action=\"JavaScript:doNothing()\" method=\"POST\">"); out.println("<table align=\"center\" cellspacing=\"2\" cellpadding=\"2\" border=\"0\">"); out.println("<tr>"); out.println("<td><b>URL:</b></td>"); out.print("<td><input name=\"url\" value=\""); out.print(geoserverUrl); out.print("/wfs/GetFeature\" size=\"70\" MAXLENGTH=\"100\"/></td>\n"); out.println("</tr>"); out.println("<tr>"); out.println("<td><b>Request:</b></td>"); out.println("<td><textarea cols=\"60\" rows=\"24\" name=\"body\"></textarea></td>"); out.println("</tr>"); out.println("</table>"); out.println("<table align=\"center\">"); out.println("<tr>"); out.println("<td><input type=\"button\" value=\"Clear\" onclick=\"clearRequest()\"></td>"); out.println("<td><input type=\"button\" value=\"Submit\" onclick=\"sendRequest()\"></td>"); out.println("<td></td>"); out.println("</tr>"); out.println("</table>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); out.close(); } else { response.setContentType("application/xml"); BufferedReader xmlIn = null; PrintWriter xmlOut = null; StringBuffer sbf = new StringBuffer(); String resp = null; try { URL u = new URL(urlString); java.net.HttpURLConnection acon = (java.net.HttpURLConnection) u.openConnection(); acon.setAllowUserInteraction(false); if (!doGet) { //System.out.println("set to post"); acon.setRequestMethod("POST"); acon.setRequestProperty("Content-Type", "application/xml"); } else { //System.out.println("set to get"); acon.setRequestMethod("GET"); } acon.setDoOutput(true); acon.setDoInput(true); acon.setUseCaches(false); //SISfixed - if there was authentication info in the request, // Pass it along the way to the target URL //DJB: applied patch in GEOS-335 String authHeader = request.getHeader("Authorization"); String username = request.getParameter("username"); if ((username != null) && !username.trim().equals("")) { String password = request.getParameter("password"); String up = username + ":" + password; byte[] encoded = Base64.encodeBase64(up.getBytes()); authHeader = "Basic " + new String(encoded); } if (authHeader != null) { acon.setRequestProperty("Authorization", authHeader); } if (!doGet) { xmlOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(acon.getOutputStream()))); xmlOut = new java.io.PrintWriter(acon.getOutputStream()); xmlOut.write(requestString); xmlOut.flush(); } // Above 400 they're all error codes, see: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html if (acon.getResponseCode() >= 400) { PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<servlet-exception>"); out.println("HTTP response: " + acon.getResponseCode() + "\n" + URLDecoder.decode(acon.getResponseMessage(), "UTF-8")); out.println("</servlet-exception>"); out.close(); } else { // xmlIn = new BufferedReader(new InputStreamReader( // acon.getInputStream())); // String line; // System.out.println("got encoding from acon: " // + acon.getContentType()); response.setContentType(acon.getContentType()); response.setHeader("Content-disposition", acon.getHeaderField("Content-disposition")); OutputStream output = response.getOutputStream(); int c; InputStream in = acon.getInputStream(); while ((c = in.read()) != -1) output.write(c); in.close(); output.close(); } //while ((line = xmlIn.readLine()) != null) { // out.print(line); //} } catch (Exception e) { PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<servlet-exception>"); out.println(e.toString()); out.println("</servlet-exception>"); out.close(); } finally { try { if (xmlIn != null) { xmlIn.close(); } } catch (Exception e1) { PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<servlet-exception>"); out.println(e1.toString()); out.println("</servlet-exception>"); out.close(); } try { if (xmlOut != null) { xmlOut.close(); } } catch (Exception e2) { PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<servlet-exception>"); out.println(e2.toString()); out.println("</servlet-exception>"); out.close(); } } } }
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceTest.java
@Test @RunAsClient//from w w w.java2 s .c o m @Ignore public void testCreatePackageFromDRLAsEntry(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/packages"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.setDoOutput(true); //Send request BufferedReader br = new BufferedReader( new InputStreamReader(getClass().getResourceAsStream("simple_rules.drl"))); DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); while (br.ready()) dos.writeBytes(br.readLine()); dos.flush(); dos.close(); /* Retry with a -1 from the connection */ if (connection.getResponseCode() == -1) { url = new URL(baseURL, "rest/packages"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.setDoOutput(true); //Send request br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("simple_rules.drl"))); dos = new DataOutputStream(connection.getOutputStream()); while (br.ready()) dos.writeBytes(br.readLine()); dos.flush(); dos.close(); } assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType()); //logger.log(LogLevel, IOUtils.toString(connection.getInputStream())); }
From source file:com.wadpam.guja.oauth2.social.NetworkTemplate.java
public <J> NetworkResponse<J> exchangeForResponse(String method, String url, Map<String, String> requestHeaders, Object requestBody, Class<J> responseClass, boolean followRedirects) { // so that we can read in case of Exception InputStream in = null;// ww w.j a v a 2 s . co m try { // expand url? if (null != requestBody && !CONTENT_METHODS.contains(method)) { Map<String, Object> paramMap = requestBody instanceof Map ? (Map) requestBody : MAPPER.convertValue(requestBody, Map.class); url = expandUrl(url, paramMap); } // create the connection URL u = new URL(url); HttpURLConnection con = (HttpURLConnection) u.openConnection(); con.setInstanceFollowRedirects(followRedirects); // override default method if (null != method) { con.setRequestMethod(method); } LOG.info("{} {}", method, url); // Accept if (null != accept) { con.addRequestProperty(ACCEPT, accept); LOG.trace("{}: {}", ACCEPT, accept); } // Authorization if (null != authorization) { con.addRequestProperty(AUTHORIZATION, authorization); LOG.trace("{}: {}", AUTHORIZATION, authorization); } // other request headers: String contentType = null; if (null != requestHeaders) { for (Entry<String, String> entry : requestHeaders.entrySet()) { con.addRequestProperty(entry.getKey(), entry.getValue()); LOG.info("{}: {}", entry.getKey(), entry.getValue()); if (CONTENT_TYPE.equalsIgnoreCase(entry.getKey())) { contentType = entry.getValue(); } } } if (null != requestBody) { if (CONTENT_METHODS.contains(method)) { // content-type not specified in request headers? if (null == contentType) { contentType = MIME_JSON; con.addRequestProperty(CONTENT_TYPE, MIME_JSON); } con.setDoOutput(true); OutputStream out = con.getOutputStream(); if (MIME_JSON.equals(contentType)) { MAPPER.writeValue(out, requestBody); final String json = MAPPER.writeValueAsString(requestBody); LOG.debug("json Content: {}", json); } else { // application/www-form-urlencoded PrintWriter writer = new PrintWriter(out); if (requestBody instanceof String) { writer.print(requestBody); LOG.debug("Content: {}", requestBody); } else { Map<String, Object> params = MAPPER.convertValue(requestBody, Map.class); String content = expandUrl("", params); writer.print(content.substring(1)); LOG.debug("Content: {}", content.substring(1)); } writer.flush(); } out.close(); } } NetworkResponse<J> response = new NetworkResponse<J>(con.getResponseCode(), con.getHeaderFields(), con.getResponseMessage()); LOG.info("HTTP {} {}", response.getCode(), response.getMessage()); // response content to read and parse? if (null != con.getContentType()) { final String responseType = con.getContentType(); LOG.debug("Content-Type: {}", responseType); in = con.getInputStream(); if (con.getContentType().startsWith(MIME_JSON)) { response.setBody(MAPPER.readValue(in, responseClass)); LOG.debug("Response JSON: {}", response.getBody()); } else if (String.class.equals(responseClass)) { String s = readResponseAsString(in, responseType); LOG.info("Read {} bytes from {}", s.length(), con.getContentType()); response.setBody((J) s); } else if (400 <= response.getCode()) { String s = readResponseAsString(in, responseType); LOG.warn(s); } in.close(); } return response; } catch (IOException ioe) { if (null != in) { try { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s; while (null != (s = br.readLine())) { LOG.warn(s); } } catch (IOException ignore) { } } throw new RuntimeException(String.format("NetworkTemplate.exchange: %s", ioe.getMessage()), ioe); } }
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceTest.java
@Test @RunAsClient/*from ww w. j av a 2 s . c o m*/ public void testGetSourceContentFromBinaryAsset(@ArquillianResource URL baseURL) throws Exception { //Query if the asset exist URL url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image-new"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.connect(); //The asset should not exist assertEquals(500, connection.getResponseCode()); //Create the asset from binary url = new URL(baseURL, "rest/packages/restPackage1/assets"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.setRequestProperty("Slug", "Error-image-new"); connection.setDoOutput(true); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] data = new byte[1000]; int count = 0; InputStream is = this.getClass().getResourceAsStream("Error-image.gif"); while ((count = is.read(data, 0, 1000)) != -1) { out.write(data, 0, count); } connection.getOutputStream().write(out.toByteArray()); out.close(); assertEquals(200, connection.getResponseCode()); //Get the asset source. this will return the binary data as a byte array. url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image-new/source"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.TEXT_PLAIN); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.TEXT_PLAIN, connection.getContentType()); String result = IOUtils.toString(connection.getInputStream()); assertNotNull(result); //Roll back changes. url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image-new"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("DELETE"); connection.connect(); System.out.println(IOUtils.toString(connection.getInputStream())); assertEquals(204, connection.getResponseCode()); //Verify the package is indeed deleted url = new URL(baseURL, "rest/packages/restPackage1/assets/Error-image-new"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.connect(); assertEquals(500, connection.getResponseCode()); }