List of usage examples for java.net HttpURLConnection getContentType
public String getContentType()
From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading * page resources as appropriate./*from w ww . jav a 2 s . com*/ * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ @Override protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { HttpURLConnection conn = null; String urlStr = url.toString(); if (log.isDebugEnabled()) { log.debug("Start : sample " + urlStr); log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth); } HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); res.setSampleLabel(urlStr); res.setURL(url); res.setHTTPMethod(method); res.sampleStart(); // Count the retries as well in the time // Check cache for an entry with an Expires header in the future final CacheManager cacheManager = getCacheManager(); if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) { if (cacheManager.inCache(url)) { return updateSampleResultForResourceInCache(res); } } try { // Sampling proper - establish the connection and read the response: // Repeatedly try to connect: int retry = -1; // Start with -1 so tries at least once, and retries at most MAX_CONN_RETRIES times for (; retry < MAX_CONN_RETRIES; retry++) { try { conn = setupConnection(url, method, res); // Attempt the connection: savedConn = conn; conn.connect(); break; } catch (BindException e) { if (retry >= MAX_CONN_RETRIES) { log.error("Can't connect after " + retry + " retries, " + e); throw e; } log.debug("Bind exception, try again"); if (conn != null) { savedConn = null; // we don't want interrupt to try disconnection again conn.disconnect(); } setUseKeepAlive(false); } catch (IOException e) { log.debug("Connection failed, giving up"); throw e; } } if (retry > MAX_CONN_RETRIES) { // This should never happen, but... throw new BindException(); } // Nice, we've got a connection. Finish sending the request: if (method.equals(HTTPConstants.POST)) { String postBody = sendPostData(conn); res.setQueryString(postBody); } else if (method.equals(HTTPConstants.PUT)) { String putBody = sendPutData(conn); res.setQueryString(putBody); } // Request sent. Now get the response: byte[] responseData = readResponse(conn, res); res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setResponseData(responseData); int errorLevel = conn.getResponseCode(); String respMsg = conn.getResponseMessage(); String hdr = conn.getHeaderField(0); if (hdr == null) { hdr = "(null)"; // $NON-NLS-1$ } if (errorLevel == -1) {// Bug 38902 - sometimes -1 seems to be returned unnecessarily if (respMsg != null) {// Bug 41902 - NPE try { errorLevel = Integer.parseInt(respMsg.substring(0, 3)); log.warn("ResponseCode==-1; parsed " + respMsg + " as " + errorLevel); } catch (NumberFormatException e) { log.warn("ResponseCode==-1; could not parse " + respMsg + " hdr: " + hdr); } } else { respMsg = hdr; // for result log.warn("ResponseCode==-1 & null ResponseMessage. Header(0)= " + hdr); } } if (errorLevel == -1) { res.setResponseCode("(null)"); // $NON-NLS-1$ } else { res.setResponseCode(Integer.toString(errorLevel)); } res.setSuccessful(isSuccessCode(errorLevel)); if (respMsg == null) {// has been seen in a redirect respMsg = hdr; // use header (if possible) if no message found } res.setResponseMessage(respMsg); String ct = conn.getContentType(); if (ct != null) { res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } String responseHeaders = getResponseHeaders(conn); res.setResponseHeaders(responseHeaders); if (res.isRedirect()) { res.setRedirectLocation(conn.getHeaderField(HTTPConstants.HEADER_LOCATION)); } // record headers size to allow HTTPSampleResult.getBytes() with different options res.setHeadersSize(responseHeaders.replaceAll("\n", "\r\n") // $NON-NLS-1$ $NON-NLS-2$ .length() + 2); // add 2 for a '\r\n' at end of headers (before data) if (log.isDebugEnabled()) { log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(conn.getURL()); } // Store any cookies received in the cookie manager: saveConnectionCookies(conn, url, getCookieManager()); // Save cache information if (cacheManager != null) { cacheManager.saveDetails(conn, res); } res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); return res; } catch (IOException e) { res.sampleEnd(); savedConn = null; // we don't want interrupt to try disconnection again // We don't want to continue using this connection, even if KeepAlive is set if (conn != null) { // May not exist conn.disconnect(); } conn = null; // Don't process again return errorResult(e, res); } finally { // calling disconnect doesn't close the connection immediately, // but indicates we're through with it. The JVM should close // it when necessary. savedConn = null; // we don't want interrupt to try disconnection again disconnect(conn); // Disconnect unless using KeepAlive } }
From source file:i5.las2peer.services.mobsos.SurveyService.java
/** * Parses incoming content to a survey JSON representation including checks for completeness, illegal fields and values. *///from www. ja va2 s . co m private JSONObject parseSurvey(String content) throws IllegalArgumentException { JSONObject o; try { o = (JSONObject) JSONValue.parseWithException(content); } catch (ParseException e1) { throw new IllegalArgumentException("Survey data *" + content + "* is not valid JSON!"); } // check result for unknown illegal fields. If so, parsing fails. String[] fields = { "id", "owner", "organization", "logo", "name", "description", "resource", "start", "end", "lang", "qid" }; for (Object key : o.keySet()) { if (!Arrays.asList(fields).contains(key)) { throw new IllegalArgumentException("Illegal survey field '" + key + "' detected!"); } else { if (key.equals("name") && !(o.get(key) instanceof String)) { throw new IllegalArgumentException( "Illegal value for survey field 'name'. Should be a string."); } else if (key.equals("description") && !(o.get(key) instanceof String)) { throw new IllegalArgumentException( "Illegal value for survey field 'description'. Should be a string."); } else if (key.equals("organization") && !(o.get(key) instanceof String)) { throw new IllegalArgumentException( "Illegal value for survey field 'organization'. Should be a string."); } else if (key.equals("logo")) { try { URL u = new URL((String) o.get(key)); HttpURLConnection con = (HttpURLConnection) u.openConnection(); if (404 == con.getResponseCode()) { throw new IllegalArgumentException( "Illegal value for survey field logo. Should be a valid URL to an image resource."); } if (!con.getContentType().matches("image/.*")) { throw new IllegalArgumentException( "Illegal value for survey field logo. Should be a valid URL to an image resource."); } } catch (MalformedURLException e) { throw new IllegalArgumentException( "Illegal value for survey field 'logo'. Should be a valid URL to an image resource."); } catch (IOException e) { throw new IllegalArgumentException( "Illegal value for survey field 'logo'. Should be a valid URL to an image resource."); } } else if (key.equals("resource")) { HttpResponse h = getClientMetadata((String) o.get(key)); if (h.getStatus() == 404) { throw new IllegalArgumentException( "Illegal value for survey field 'resource'. Should be an existing OpenID Client ID."); } /*try { URL u = new URL((String) o.get(key)); HttpURLConnection con = (HttpURLConnection) u.openConnection(); if(404 == con.getResponseCode()){ throw new IllegalArgumentException("Illegal value for survey field 'resource'. Should be a valid URL."); } } catch (MalformedURLException e) { throw new IllegalArgumentException("Illegal value for survey field 'resource'. Should be a valid URL."); } catch (IOException e) { throw new IllegalArgumentException("Illegal value for survey field 'resource'. Should be a valid URL."); }*/ } else if (key.equals("start")) { try { DatatypeConverter.parseDateTime((String) o.get("start")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( "Illegal value for survey field 'start'. Should be an ISO-8601 formatted time string."); } } else if (key.equals("end")) { try { DatatypeConverter.parseDateTime((String) o.get("end")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( "Illegal value for survey field 'end'. Should be an ISO-8601 formatted time string."); } } else if (key.equals("lang")) { String lang = (String) o.get(key); Pattern p = Pattern.compile("[a-z]+-[A-Z]+"); Matcher m = p.matcher(lang); // do not iterate over all locales found, but only use first option with highest preference. Locale l = null; if (m.find()) { String[] tokens = m.group().split("-"); l = new Locale(tokens[0], tokens[1]); } else { throw new IllegalArgumentException( "Illegal value for survey field 'lang'. Should be a valid locale such as 'en-US' or 'de-DE'."); } } } } // check if all necessary fields are specified. if (o.get("name") == null || o.get("organization") == null || o.get("logo") == null || o.get("description") == null || o.get("resource") == null || o.get("start") == null || o.get("end") == null || o.get("lang") == null) { throw new IllegalArgumentException( "Survey data incomplete! All fields name, organization, logo, description, resource, start, end, and lang must be defined!"); } // finally check time integrity constraint: start must be before end (possibly not enforced by database; mySQL does not support this check) long d_start = DatatypeConverter.parseDateTime((String) o.get("start")).getTimeInMillis(); long d_end = DatatypeConverter.parseDateTime((String) o.get("end")).getTimeInMillis(); if (d_start >= d_end) { throw new IllegalArgumentException("Survey data invalid! Start time must be before end time!"); } return o; }
From source file:org.openqa.selenium.server.ProxyHandler.java
protected long proxyPlainTextRequest(URL url, String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws IOException { CaptureNetworkTrafficCommand.Entry entry = new CaptureNetworkTrafficCommand.Entry(request.getMethod(), url.toString());/* w ww . j a v a 2s. co m*/ entry.addRequestHeaders(request); if (log.isDebugEnabled()) log.debug("PROXY URL=" + url); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); if (proxyInjectionMode) { adjustRequestForProxyInjection(request, connection); } // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); if (trustAllSSLCertificates && connection instanceof HttpsURLConnection) { TrustEverythingSSLTrustManager.trustAllSSLCertificates((HttpsURLConnection) connection); } } // check connection header String connectionHdr = request.getField(HttpFields.__Connection); if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close))) connectionHdr = null; // copy headers boolean xForwardedFor = false; boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; Enumeration enm = request.getFieldNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0) continue; if (!isGet && HttpFields.__ContentType.equals(hdr)) hasContent = true; Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { // don't proxy Referer headers if the referer is Selenium! if ("Referer".equals(hdr) && (-1 != val.indexOf("/selenium-server/"))) { continue; } if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } connection.addRequestProperty(hdr, val); xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr); } } } // add any custom request headers that the user asked for Map<String, String> customRequestHeaders = AddCustomRequestHeaderCommand.getHeaders(); for (Map.Entry<String, String> e : customRequestHeaders.entrySet()) { connection.addRequestProperty(e.getKey(), e.getValue()); entry.addRequestHeader(e.getKey(), e.getValue()); } // Proxy headers if (!_anonymous) connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getField(HttpFields.__CacheControl); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection customizeConnection(pathInContext, pathParams, request, connection); try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { LogSupport.ignore(log, e); } InputStream proxy_in = null; // handler status codes etc. int code = -1; if (http != null) { proxy_in = http.getErrorStream(); try { code = http.getResponseCode(); } catch (SSLHandshakeException e) { throw new RuntimeException("Couldn't establish SSL handshake. Try using trustAllSSLCertificates.\n" + e.getLocalizedMessage(), e); } response.setStatus(code); response.setReason(http.getResponseMessage()); String contentType = http.getContentType(); if (log.isDebugEnabled()) { log.debug("Content-Type is: " + contentType); } } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { LogSupport.ignore(log, e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.removeField(HttpFields.__Date); response.removeField(HttpFields.__Server); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr) && (_chained || !_ProxyAuthHeaders.containsKey(hdr))) response.addField(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } if (!_anonymous) response.setField("Via", "1.1 (jetty)"); response.removeField(HttpFields.__ETag); // possible cksum? Stop caching... response.removeField(HttpFields.__LastModified); // Stop caching... // Handled long bytesCopied = -1; request.setHandled(true); if (proxy_in != null) { boolean injectableResponse = http.getResponseCode() == HttpURLConnection.HTTP_OK || (http.getResponseCode() >= 400 && http.getResponseCode() < 600); if (proxyInjectionMode && injectableResponse) { // check if we should proxy this path based on the dontProxyRegex that can be user-specified if (shouldInject(request.getPath())) { bytesCopied = InjectionHelper.injectJavaScript(request, response, proxy_in, response.getOutputStream(), debugURL); } else { bytesCopied = ModifiedIO.copy(proxy_in, response.getOutputStream()); } } else { bytesCopied = ModifiedIO.copy(proxy_in, response.getOutputStream()); } } entry.finish(code, bytesCopied); entry.addResponseHeader(response); CaptureNetworkTrafficCommand.capture(entry); return bytesCopied; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImplClassifier.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading page * resources as appropriate./*from ww w.ja v a 2 s . c om*/ * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { HttpURLConnection conn = null; String urlStr = url.toString(); log.debug("Start : sample " + urlStr); HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); res.setSampleLabel(urlStr); res.setURL(url); res.setHTTPMethod(method); res.sampleStart(); // Count the retries as well in the time // Check cache for an entry with an Expires header in the future final CacheManager cacheManager = getCacheManager(); if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) { if (cacheManager.inCache(url)) { res.sampleEnd(); res.setResponseNoContent(); res.setSuccessful(true); return res; } } try { // Sampling proper - establish the connection and read the response: // Repeatedly try to connect: int retry; // Start with 0 so tries at least once, and retries at most // MAX_CONN_RETRIES times for (retry = 0; retry <= MAX_CONN_RETRIES; retry++) { try { conn = setupConnection(url, method, res); // Attempt the connection: savedConn = conn; conn.connect(); break; } catch (BindException e) { if (retry >= MAX_CONN_RETRIES) { log.error("Can't connect after " + retry + " retries, " + e); throw e; } log.debug("Bind exception, try again"); if (conn != null) { savedConn = null; // we don't want interrupt to try // disconnection again conn.disconnect(); } setUseKeepAlive(false); continue; // try again } catch (IOException e) { log.debug("Connection failed, giving up"); throw e; } } if (retry > MAX_CONN_RETRIES) { // This should never happen, but... throw new BindException(); } // Nice, we've got a connection. Finish sending the request: if (method.equals(HTTPConstants.POST)) { String postBody = sendPostData(conn); res.setQueryString(postBody); } else if (method.equals(HTTPConstants.PUT)) { String putBody = sendPutData(conn); res.setQueryString(putBody); } // Request sent. Now get the response: byte[] responseData = readResponse(conn, res); res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setResponseData(responseData); @SuppressWarnings("null") // Cannot be null here int errorLevel = conn.getResponseCode(); String respMsg = conn.getResponseMessage(); String hdr = conn.getHeaderField(0); if (hdr == null) { hdr = "(null)"; // $NON-NLS-1$ } if (errorLevel == -1) {// Bug 38902 - sometimes -1 seems to be // returned unnecessarily if (respMsg != null) {// Bug 41902 - NPE try { errorLevel = Integer.parseInt(respMsg.substring(0, 3)); log.warn("ResponseCode==-1; parsed " + respMsg + " as " + errorLevel); } catch (NumberFormatException e) { log.warn("ResponseCode==-1; could not parse " + respMsg + " hdr: " + hdr); } } else { respMsg = hdr; // for result log.warn("ResponseCode==-1 & null ResponseMessage. Header(0)= " + hdr); } } if (errorLevel == -1) { res.setResponseCode("(null)"); // $NON-NLS-1$ } else { res.setResponseCode(Integer.toString(errorLevel)); } res.setSuccessful(isSuccessCode(errorLevel)); if (respMsg == null) {// has been seen in a redirect respMsg = hdr; // use header (if possible) if no message found } res.setResponseMessage(respMsg); String ct = conn.getContentType(); if (ct != null) { res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } String responseHeaders = getResponseHeaders(conn); res.setResponseHeaders(responseHeaders); if (res.isRedirect()) { res.setRedirectLocation(conn.getHeaderField(HTTPConstants.HEADER_LOCATION)); } // record headers size to allow HTTPSampleResult.getBytes() with // different options res.setHeadersSize(responseHeaders.replaceAll("\n", "\r\n") // $NON-NLS-1$ // $NON-NLS-2$ .length() + 2); // add 2 for a '\r\n' at end of headers // (before data) if (log.isDebugEnabled()) { log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(conn.getURL()); } // Store any cookies received in the cookie manager: saveConnectionCookies(conn, url, getCookieManager()); // Save cache information if (cacheManager != null) { cacheManager.saveDetails(conn, res); } res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); return res; } catch (IOException e) { res.sampleEnd(); savedConn = null; // we don't want interrupt to try disconnection // again // We don't want to continue using this connection, even if // KeepAlive is set if (conn != null) { // May not exist conn.disconnect(); } conn = null; // Don't process again return errorResult(e, res); } finally { // calling disconnect doesn't close the connection immediately, // but indicates we're through with it. The JVM should close // it when necessary. savedConn = null; // we don't want interrupt to try disconnection // again disconnect(conn); // Disconnect unless using KeepAlive } }
From source file:org.drools.guvnor.server.jaxrs.BasicPackageResourceIntegrationTest.java
@Test @RunAsClient// w w w .ja v a 2 s. c o m public void testGetHistoricalAssetBinary(@ArquillianResource URL baseURL) throws Exception { //Query if the asset exist URL url = new URL(baseURL, "rest/packages/restPackage1/assets/testGetHistoricalAssetBinary"); 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); byte[] authEncBytes = Base64.encodeBase64("admin:admin".getBytes()); connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes)); connection.connect(); //The asset should not exist assertEquals(404, 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", "testGetHistoricalAssetBinary.gif"); connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes)); 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()); //Update asset binary url = new URL(baseURL, "rest/packages/restPackage1/assets/testGetHistoricalAssetBinary/binary"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setDoOutput(true); connection.setRequestMethod("PUT"); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes)); ByteArrayOutputStream out2 = new ByteArrayOutputStream(); byte[] data2 = new byte[1000]; int count2 = 0; InputStream is2 = this.getClass().getResourceAsStream("Error-image-new.gif"); while ((count2 = is2.read(data2, 0, 1000)) != -1) { out2.write(data2, 0, count2); } connection.getOutputStream().write(out2.toByteArray()); out2.close(); assertEquals(204, connection.getResponseCode()); //Get the asset binary version 1 and verify url = new URL(baseURL, "rest/packages/restPackage1/assets/testGetHistoricalAssetBinary/versions/1/binary"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes)); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_OCTET_STREAM, connection.getContentType()); InputStream in = connection.getInputStream(); assertNotNull(in); //Get the asset binary version 2 and verify url = new URL(baseURL, "rest/packages/restPackage1/assets/testGetHistoricalAssetBinary/versions/2/binary"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes)); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_OCTET_STREAM, connection.getContentType()); in = connection.getInputStream(); assertNotNull(in); //Roll back changes. url = new URL(baseURL, "rest/packages/restPackage1/assets/testGetHistoricalAssetBinary"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("DELETE"); connection.setRequestProperty("Authorization", "Basic " + new String(authEncBytes)); connection.connect(); assertEquals(204, connection.getResponseCode()); //Verify the package is indeed deleted url = new URL(baseURL, "rest/packages/restPackage1/assets/testGetHistoricalAssetBinary"); 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.setRequestProperty("Authorization", "Basic " + new String(authEncBytes)); connection.connect(); assertEquals(404, connection.getResponseCode()); }
From source file:org.opendaylight.vtn.manager.it.northbound.VtnNorthboundIT.java
/** * Send request and get result/*w w w .j ava2 s. c om*/ * * @param restUrl A request URL. * @param method A request method. * @param body A request body send with request. * @param contentType A contentType of request. * @param auth if {@code true} authorization succeed, * else if {@code false} authorization fails. * @return A returned result for request. */ private String getJsonResult(String restUrl, String method, String body, String contentType, boolean auth) { // Initialize response code to indicate error httpResponseCode = HTTP_BAD_REQUEST; httpLocation = null; LOG.debug("HTTP method: {}, uri: {}", method, restUrl); LOG.debug("Body: {}", body); try { URL url = new URL(restUrl); this.userManager.getAuthorizationList(); String authString = null; if (auth) { this.userManager.authenticate("admin", "admin"); authString = "admin:admin"; } else { this.userManager.authenticate("admin", "bad"); authString = "admin:bad"; } byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setRequestProperty("Authorization", "Basic " + authStringEnc); connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("Accept", "application/json"); if (body != null) { connection.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(body); wr.flush(); } connection.connect(); connection.getContentType(); // Response code for success should be 2xx httpResponseCode = connection.getResponseCode(); LOG.debug("HTTP response code: {}", httpResponseCode); LOG.debug("HTTP response message: {}", connection.getResponseMessage()); if (httpResponseCode == HTTP_CREATED) { // Determine location. for (int i = 0; true; i++) { String field = connection.getHeaderFieldKey(i); if (field == null) { if (i == 0) { continue; } break; } if (field.equalsIgnoreCase("location")) { httpLocation = connection.getHeaderField(i); break; } } } boolean error = (httpResponseCode > 299); InputStream is = (error) ? connection.getErrorStream() : connection.getInputStream(); StringBuilder sb = new StringBuilder(); if (is != null) { InputStreamReader in = new InputStreamReader(is, Charset.forName("UTF-8")); BufferedReader rd = new BufferedReader(in); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } is.close(); } connection.disconnect(); if (httpResponseCode > 299) { String msg = sb.toString(); if (msg.length() != 0) { LOG.debug("HTTP error response body: {}", msg); return msg; } return httpResponseCode.toString(); } if (httpResponseCode == HTTP_NO_CONTENT) { assertEquals(0, sb.length()); } return sb.toString(); } catch (Exception e) { LOG.error("Caught exception.", e); return null; } }