List of usage examples for java.net HttpURLConnection HTTP_NOT_MODIFIED
int HTTP_NOT_MODIFIED
To view the source code for java.net HttpURLConnection HTTP_NOT_MODIFIED.
Click Source Link
From source file:org.eclipse.mylyn.internal.bugzilla.core.BugzillaClient.java
private GzipGetMethod connectInternal(String requestURL, boolean gzip, IProgressMonitor monitor, String eTagValue) throws IOException, CoreException { monitor = Policy.monitorFor(monitor); hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); for (int attempt = 0; attempt < 2; attempt++) { // force authentication authenticate(monitor);//from w w w . j a v a 2 s . c o m GzipGetMethod getMethod = new GzipGetMethod(WebUtil.getRequestPath(requestURL), gzip); if (requestURL.contains(QUERY_DELIMITER)) { getMethod.setQueryString(requestURL.substring(requestURL.indexOf(QUERY_DELIMITER))); } getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" //$NON-NLS-1$ //$NON-NLS-2$ + getCharacterEncoding()); if (eTagValue != null && eTagValue.compareTo("") != 0) { //$NON-NLS-1$ getMethod.setRequestHeader("If-None-Match", eTagValue); //$NON-NLS-1$ } // Resolves bug#195113 httpClient.getParams().setParameter("http.protocol.single-cookie-header", true); //$NON-NLS-1$ // WARNING!! Setting browser compatibility breaks Bugzilla // authentication // getMethod.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // getMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109); getMethod.setDoAuthentication(true); int code; try { code = WebUtil.execute(httpClient, hostConfiguration, getMethod, monitor); } catch (IOException e) { WebUtil.releaseConnection(getMethod, monitor); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_IO, repositoryUrl.toString(), e)); } switch (code) { case HttpURLConnection.HTTP_OK: return getMethod; case HttpURLConnection.HTTP_NOT_MODIFIED: WebUtil.releaseConnection(getMethod, monitor); throw new CoreException(new Status(IStatus.WARNING, BugzillaCorePlugin.ID_PLUGIN, "Not changed")); //$NON-NLS-1$ case HttpURLConnection.HTTP_UNAUTHORIZED: case HttpURLConnection.HTTP_FORBIDDEN: // login or reauthenticate due to an expired session loggedIn = false; WebUtil.releaseConnection(getMethod, monitor); authenticate(monitor); break; case HttpURLConnection.HTTP_PROXY_AUTH: loggedIn = false; WebUtil.releaseConnection(getMethod, monitor); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(), "Proxy authentication required")); //$NON-NLS-1$ case HttpURLConnection.HTTP_INTERNAL_ERROR: loggedIn = false; InputStream stream = getResponseStream(getMethod, monitor); ByteArrayOutputStream ou = new ByteArrayOutputStream(1024); transferData(stream, ou); WebUtil.releaseConnection(getMethod, monitor); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_NETWORK, repositoryUrl.toString(), "Error = 500")); //$NON-NLS-1$ default: WebUtil.releaseConnection(getMethod, monitor); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); //$NON-NLS-1$ } } throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_REPOSITORY_LOGIN, "All connection attempts to " + repositoryUrl.toString() //$NON-NLS-1$ + " failed. Please verify connection and authentication information.")); //$NON-NLS-1$ }
From source file:edu.harvard.hmdc.dvnplugin.DVNOAIUrlCacher.java
protected InputStream getUncachedInputStreamOnly(String lastModified) throws IOException { InputStream input = null;//from w w w.j a v a 2 s .c om try { openConnection(lastModified); if (conn.isHttp()) { // http connection; check response code int code = conn.getResponseCode(); if (code == HttpURLConnection.HTTP_NOT_MODIFIED) { logger.debug2("Unmodified content not cached for url '" + origUrl + "'"); return null; } } input = conn.getResponseInputStream(); if (input == null) { logger.warning("Got null input stream back from conn.getResponseInputStream"); } } finally { if (conn != null && input == null) { logger.debug3("Releasing connection"); conn.release(); } } return input; }
From source file:net.sf.ehcache.constructs.web.filter.CachingFilterTest.java
/** * A 0 length body should give a 0 length nongzipped body and content length * Manual Test: wget -d --server-response --timestamping --header='If-modified-Since: Fri, 13 May 3006 23:54:18 GMT' --header='Accept-Encoding: gzip' http://localhost:9080/empty_caching_filter/empty.html *//*from ww w .j a v a2s . c o m*/ public void testIfModifiedZeroLengthHTML() throws Exception { String url = "http://localhost:9080/empty_caching_filter/empty.html"; HttpClient httpClient = new HttpClient(); HttpMethod httpMethod = new GetMethod(url); httpMethod.addRequestHeader("If-modified-Since", "Fri, 13 May 3006 23:54:18 GMT"); httpMethod.addRequestHeader("Accept-Encoding", "gzip"); int responseCode = httpClient.executeMethod(httpMethod); assertTrue( HttpURLConnection.HTTP_OK == responseCode || HttpURLConnection.HTTP_NOT_MODIFIED == responseCode); String responseBody = httpMethod.getResponseBodyAsString(); assertTrue("".equals(responseBody) || null == responseBody); checkNullOrZeroContentLength(httpMethod); }
From source file:net.sf.ehcache.constructs.web.filter.CachingFilterTest.java
/** * Servlets and JSPs can send content even when the response is set to no content. * In this case there should not be a body but there is. Orion seems to kill the body * after is has left the Servlet filter chain. To avoid wget going into an inifinite * retry loop, and presumably some other web clients, the content length should be 0 * and the body 0.//from w w w . j a va 2 s.c om * <p/> * wget -d --server-response --timestamping --header='If-modified-Since: Fri, 13 May 3006 23:54:18 GMT' --header='Accept-Encoding: gzip' http://localhost:9080/empty_caching_filter/SC_NOT_MODIFIED.jsp */ public void testNotModifiedJSPGzipFilter() throws Exception { String url = "http://localhost:9080/empty_caching_filter/SC_NOT_MODIFIED.jsp"; HttpClient httpClient = new HttpClient(); HttpMethod httpMethod = new GetMethod(url); httpMethod.addRequestHeader("If-modified-Since", "Fri, 13 May 3006 23:54:18 GMT"); httpMethod.addRequestHeader("Accept-Encoding", "gzip"); int responseCode = httpClient.executeMethod(httpMethod); assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, responseCode); String responseBody = httpMethod.getResponseBodyAsString(); assertEquals(null, responseBody); assertNull(httpMethod.getResponseHeader("Content-Encoding")); assertNotNull(httpMethod.getResponseHeader("Last-Modified").getValue()); checkNullOrZeroContentLength(httpMethod); }
From source file:edu.harvard.iq.dvn.lockss.plugin.DVNOAIUrlCacher.java
protected InputStream getUncachedInputStreamOnly(String lastModified) throws IOException { InputStream input = null;/*www .ja v a2 s . co m*/ try { openConnection(lastModified); if (conn.isHttp()) { // http connection; check response code int code = conn.getResponseCode(); if (code == HttpURLConnection.HTTP_NOT_MODIFIED) { logger.debug2("Unmodified content not cached for url '" + origUrl + "'"); return null; } } input = conn.getResponseInputStream(); if (input == null) { logger.warning("Got null input stream back from conn.getResponseInputStream"); } } finally { if (conn != null && input == null) { logger.debug3("Releasing connection"); //conn.release(); IOUtil.safeRelease(conn); } } return input; }
From source file:org.wso2.carbon.registry.app.RegistryResolver.java
/** * Method to identify the response target for the request. * * @param request the request.//from www.j ava2 s . c om * * @return the response target. */ public Target resolve(Request request) { RequestContext context = (RequestContext) request; final ServletRequestContext requestContext; if (context instanceof ServletRequestContext) { requestContext = (ServletRequestContext) request; } else { requestContext = null; } if (embeddedRegistryService == null) { if (requestContext != null) { embeddedRegistryService = (EmbeddedRegistryService) requestContext.getRequest().getSession() .getServletContext().getAttribute("registry"); } if (embeddedRegistryService == null) { String msg = "Error in retrieving the embedded registry service."; log.error(msg); } } //TODO (reg-sep) UserRegistry registry = null; String uri = context.getUri().toString(); String loggedIn = null; if (requestContext != null) { loggedIn = ((ServletRequestContext) request).getRequest().getParameter("loggedIn"); } if (loggedIn != null) { String loggedUser = (String) requestContext.getRequest().getSession().getServletContext() .getAttribute("logged-user"); try { registry = embeddedRegistryService.getRegistry(loggedUser); uri = uri.substring(0, uri.lastIndexOf('?')); } catch (RegistryException e) { final StringResponseContext response = new StringResponseContext("Unauthorized", HttpURLConnection.HTTP_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\""); return new ResponseTarget(context, response); } } if (registry == null) { // Set up secure registry instance String authorizationString = request.getAuthorization(); if (authorizationString != null) { // splitting the Authorization string "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" String values[] = authorizationString.split("\\ "); if (values == null || values.length == 0) { final StringResponseContext response = new StringResponseContext("Unauthorized", HttpURLConnection.HTTP_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\""); return new ResponseTarget(context, response); } else if ("Basic".equals(values[0])) { try { // Decode username/password authorizationString = new String(Base64.decode(values[1])); values = authorizationString.split("\\:"); String userName = values[0]; String password = values[1]; String tenantDomain = (String) ((ServletRequestContext) request).getRequest() .getAttribute(MultitenantConstants.TENANT_DOMAIN); int tenantId; String userNameAlong; if (tenantDomain == null || MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { tenantId = getTenantId(userName); userNameAlong = getUserName(userName); } else { tenantId = getTenantIdFromDomain(tenantDomain); userNameAlong = userName; } registry = embeddedRegistryService.getRegistry(userNameAlong, password, tenantId); } catch (Exception e) { final StringResponseContext response = new StringResponseContext("Unauthorized", HttpURLConnection.HTTP_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\""); return new ResponseTarget(context, response); } } else { // TODO - return an ExceptionTarget which contains the authentication problem // return new ExceptionTarget(400, "Only basic authentication is supported!"); return null; } } else { String tenantDomain = (String) requestContext.getRequest() .getAttribute(MultitenantConstants.TENANT_DOMAIN); int calledTenantId = MultitenantConstants.SUPER_TENANT_ID; if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { if (RegistryContext.getBaseInstance().getRealmService() == null) { String msg = "Error in getting the tenant manager. " + "The realm service is not available."; log.error(msg); return new ResponseTarget(context, new EmptyResponseContext(400, msg)); } TenantManager tenantManager = RegistryContext.getBaseInstance().getRealmService() .getTenantManager(); try { calledTenantId = tenantManager.getTenantId(tenantDomain); } catch (org.wso2.carbon.user.api.UserStoreException e) { String msg = "Error in converting tenant domain to the id for tenant domain: " + tenantDomain + "."; log.error(msg, e); return new ResponseTarget(context, new EmptyResponseContext(400, msg)); } try { if (!tenantManager.isTenantActive(calledTenantId)) { // the tenant is not active. String msg = "The tenant is not active. tenant domain: " + tenantDomain + "."; log.error(msg); return new ResponseTarget(context, new EmptyResponseContext(400, msg)); } } catch (org.wso2.carbon.user.api.UserStoreException e) { String msg = "Error in converting tenant domain to the id for tenant domain: " + tenantDomain + "."; log.error(msg, e); return new ResponseTarget(context, new EmptyResponseContext(400, msg)); } RegistryContext.getBaseInstance().getRealmService().getBootstrapRealmConfiguration(); } String anonUser = CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME; try { registry = embeddedRegistryService.getRegistry(anonUser, calledTenantId); } catch (RegistryException e) { String msg = "Error in creating the registry."; log.error(msg, e); return new ResponseTarget(context, new EmptyResponseContext(400, msg)); } } } // Squirrel this away so the adapter can get it later (after all that work we just did!) context.setAttribute("userRegistry", registry); final String method = context.getMethod(); /* Following code moved further down try { uri = URLDecoder.decode(uri, "utf-8"); } catch (UnsupportedEncodingException e) { log.error(e); return null; } */ if (uri.startsWith(RegistryConstants.PATH_SEPARATOR + RegistryConstants.REGISTRY_INSTANCE + RegistryConstants.PATH_SEPARATOR + RegistryConstants.REGISTRY_INSTANCE)) { //if ROOT war is renamed to 'registry', uri will look like following, //'/registry/registry/foo/bar' //Hence,we need to remove the first 'registry' uri = uri.replaceFirst(RegistryConstants.PATH_SEPARATOR + RegistryConstants.REGISTRY_INSTANCE, ""); } // URI will start with the baseURI, which we need to strip off. String[] excludeStartArr = { basePath + APPConstants.ATOM, basePath + APPConstants.RESOURCE, basePath + "/tags" }; if (basePath == null) { log.error("Base path is null. Aborting the operation."); final StringResponseContext response = new StringResponseContext("Internal Server Error", HttpURLConnection.HTTP_INTERNAL_ERROR); return new ResponseTarget(context, response); } else if (!basePath.equals("")) { for (String excludeStartStr : excludeStartArr) { // URI will start with the baseURI, which we need to strip off. if (uri.indexOf(excludeStartStr) > -1 && uri.length() > uri.indexOf(excludeStartStr) + basePath.length()) { uri = uri.substring(uri.indexOf(excludeStartStr) + basePath.length()); break; } } } if (!uri.startsWith(RegistryConstants.PATH_SEPARATOR + RegistryConstants.REGISTRY_INSTANCE)) { uri = uri.substring(uri.indexOf(RegistryConstants.PATH_SEPARATOR)); } context.setAttribute("pathInfo", uri); String[] parts = splitPath(uri); // splits with "\;" boolean hasColon = false; TargetType type = null; // Let's just see if this is an import first - in which case we can just send it // on through. if (parts.length > 1) { String discriminator = parts[1]; // If this is a version request, don't do anything special. Otherwise process. if (discriminator.startsWith("version:")) { if (parts.length > 2) { // Make sure this is a restore. if (parts[2].equals("restore")) { type = RESTORE_TYPE; uri = parts[0] + RegistryConstants.URL_SEPARATOR + parts[1]; } else if (parts[2].equals(APPConstants.ASSOCIATIONS)) { type = ASSOCIATIONS_TYPE; uri = parts[0] + RegistryConstants.URL_SEPARATOR + parts[1]; } else { // There's an extra semicolon here somewhere. return null; } } } else { // Store the split URL for later context.setAttribute(APPConstants.PARAMETER_SPLIT_PATH, parts); int idx = discriminator.indexOf('?'); if (idx > -1) { discriminator = discriminator.substring(0, idx); } String suffix = null; idx = discriminator.indexOf(':'); if (idx > -1) { suffix = discriminator.substring(idx + 1, discriminator.length()); discriminator = discriminator.substring(0, idx); hasColon = true; } if (discriminator.startsWith("aspect")) { type = ASPECT_TYPE; } else { type = types.get(discriminator); } if (discriminator.equals("tag") && method.equals("DELETE") && hasColon) { context.setAttribute("tagName", suffix); type = DELETE_TYPE; } else if (discriminator.equals("comment") && method.equals("DELETE") && hasColon) { context.setAttribute("commentId", suffix); type = DELETE_TYPE; } else if (discriminator.equals("ratings") && hasColon) { context.setAttribute("ratingUser", suffix); type = RATINGS_TYPE; } // If we have a discriminator that we don't understand, return a 404 if (type == null) { return null; } // For the rest of this code, we'll want the "raw" resource URI if (!hasColon || !(type.equals(COMMENTS_TYPE) || type.equals(RATINGS_TYPE) || type.equals(TAGS_TYPE))) { uri = parts[0]; } if (hasColon && type.equals(TAGS_TYPE)) { type = null; } } } int idx = uri.indexOf('?'); if (idx > -1) { String queryString = uri.substring(idx + 1, uri.length()); context.setAttribute("queryString", queryString); uri = uri.substring(0, idx); } try { uri = URLDecoder.decode(uri, RegistryConstants.DEFAULT_CHARSET_ENCODING); } catch (UnsupportedEncodingException e) { log.error(e); return null; } boolean isMedia = false; if (uri.startsWith(APPConstants.RESOURCE)) { uri = uri.substring(APPConstants.RESOURCE.length()); isMedia = true; } else if (uri.startsWith(APPConstants.ATOM)) { uri = uri.substring(APPConstants.ATOM.length()); } else if (uri.startsWith("/tags") && (uri.length() == 5 || uri.charAt(5) == '/')) { return new SimpleTarget(TAG_URL_TYPE, context); } else { return null; } if (uri.length() == 0) { uri = "/"; } // See if we're asking for a paginated collection String startParam = context.getParameter("start"); String pageLenParam = context.getParameter("pageLen"); int start = (startParam == null) ? -1 : Integer.parseInt(startParam); int pageLen = (pageLenParam == null) ? -1 : Integer.parseInt(pageLenParam); Resource resource = null; if (type != null && type.equals(DUMP_TYPE) && method != null && method.equals("POST")) { // for restoring a dump we don't need to have available resource // here we will create a fake resource to store the path resource = new ResourceImpl(); ((ResourceImpl) resource).setPath(uri); } else { // in a restore, path don't need to exist. CurrentSession.setUserRealm(registry.getUserRealm()); CurrentSession.setUser(registry.getUserName()); try { if (!AuthorizationUtils.authorize(RegistryUtils.getAbsolutePath(registry.getRegistryContext(), uri), ActionConstants.GET)) { final StringResponseContext response = new StringResponseContext("Unauthorized", HttpURLConnection.HTTP_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\""); return new ResponseTarget(context, response); } else if (start > -1 || pageLen > -1) { resource = registry.get(uri, start, pageLen); } else { resource = registry.get(uri); } } catch (AuthorizationFailedException e) { final StringResponseContext response = new StringResponseContext("Unauthorized", HttpURLConnection.HTTP_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\""); return new ResponseTarget(context, response); } catch (ResourceNotFoundException e) { // If this is a straight-ahead POST to a non-existent directory, create it? if (method.equals("POST") && parts.length == 1) { // Need to create it. try { Collection c = registry.newCollection(); registry.put(uri, c); resource = registry.get(uri); } catch (RegistryException e1) { log.error(e1); return null; } } if (resource == null) { return null; } } catch (RegistryException e) { return null; // return 404 } finally { CurrentSession.removeUser(); CurrentSession.removeUserRealm(); } if (method.equals("GET")) { // eTag based conditional get String ifNonMatchValue = context.getHeader("if-none-match"); if (ifNonMatchValue != null) { String currentETag = Utils.calculateEntityTag(resource); if (ifNonMatchValue.equals(currentETag)) { /* the version is not modified */ ResponseContext response = new StringResponseContext("Not Modified", HttpURLConnection.HTTP_NOT_MODIFIED); return new ResponseTarget(context, response); } } // date based conditional get long ifModifiedSinceValue = 0; Date ifModifiedSince = context.getDateHeader("If-Modified-Since"); if (ifModifiedSince != null) { ifModifiedSinceValue = ifModifiedSince.getTime(); } if (ifModifiedSinceValue > 0) { long lastModifiedValue = resource.getLastModified().getTime(); // convert the time values from milliseconds to seconds ifModifiedSinceValue /= 1000; lastModifiedValue /= 1000; /* condition to check we have latest updates in terms of dates */ if (ifModifiedSinceValue >= lastModifiedValue) { /* no need to response with data */ ResponseContext response = new StringResponseContext("Not Modified", HttpURLConnection.HTTP_NOT_MODIFIED); return new ResponseTarget(context, response); } } } } context.setAttribute("MyResolver", this); if (type == null) { if (method.equals("DELETE")) { // Unfortunately, deletions aren't quite handled the way we want them // in AbstractEntityCollectionProvider, so for now we're using an // extensionRequest to get it done. type = DELETE_TYPE; } else { if (resource instanceof Collection) { if (method.equals("HEAD") || method.equals("PUT")) { // Abdera doesn't handle HEAD or PUT on collections yet. this should // go away once that's fixed! type = COLLECTION_CUSTOM_TYPE; } else { type = TargetType.TYPE_COLLECTION; } } else { type = isMedia ? TargetType.TYPE_MEDIA : TargetType.TYPE_ENTRY; } } } return new ResourceTarget(type, context, resource); }
From source file:net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilterTest.java
/** * A 0 length body should give a 0 length nongzipped body and content length * Manual Test: wget -d --server-response --timestamping --header='If-modified-Since: Fri, 13 May 3006 23:54:18 GMT' --header='Accept-Encoding: gzip' http://localhost:9090/empty_caching_filter/empty.html *//*from w ww . j av a2 s .com*/ @Test public void testIfModifiedZeroLengthHTML() throws Exception { String url = buildUrl("/empty_caching_filter/empty.html"); HttpClient httpClient = new HttpClient(); HttpMethod httpMethod = new GetMethod(url); httpMethod.addRequestHeader("If-modified-Since", "Fri, 13 May 3006 23:54:18 GMT"); httpMethod.addRequestHeader("Accept-Encoding", "gzip"); int responseCode = httpClient.executeMethod(httpMethod); assertTrue( HttpURLConnection.HTTP_OK == responseCode || HttpURLConnection.HTTP_NOT_MODIFIED == responseCode); String responseBody = httpMethod.getResponseBodyAsString(); assertTrue("".equals(responseBody) || null == responseBody); checkNullOrZeroContentLength(httpMethod); }
From source file:hudson.FilePathTest.java
@Issue("JENKINS-16215") @Test/*from w w w.j a v a 2 s.c o m*/ public void installIfNecessaryAvoidsExcessiveDownloadsByUsingIfModifiedSince() throws Exception { File tmp = temp.getRoot(); final FilePath d = new FilePath(tmp); d.child(".timestamp").touch(123000); final HttpURLConnection con = mock(HttpURLConnection.class); final URL url = someUrlToZipFile(con); when(con.getResponseCode()).thenReturn(HttpURLConnection.HTTP_NOT_MODIFIED); assertFalse(d.installIfNecessaryFrom(url, null, null)); verify(con).setIfModifiedSince(123000); }
From source file:net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilterTest.java
/** * Servlets and JSPs can send content even when the response is set to no content. * In this case there should not be a body but there is. Orion seems to kill the body * after is has left the Servlet filter chain. To avoid wget going into an inifinite * retry loop, and presumably some other web clients, the content length should be 0 * and the body 0./*from w ww . j av a 2 s.com*/ * <p/> * wget -d --server-response --timestamping --header='If-modified-Since: Fri, 13 May 3006 23:54:18 GMT' --header='Accept-Encoding: gzip' http://localhost:9090/empty_caching_filter/SC_NOT_MODIFIED.jsp */ @Test public void testNotModifiedJSPGzipFilter() throws Exception { String url = buildUrl("/empty_caching_filter/SC_NOT_MODIFIED.jsp"); HttpClient httpClient = new HttpClient(); HttpMethod httpMethod = new GetMethod(url); httpMethod.addRequestHeader("If-modified-Since", "Fri, 13 May 3006 23:54:18 GMT"); httpMethod.addRequestHeader("Accept-Encoding", "gzip"); int responseCode = httpClient.executeMethod(httpMethod); assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, responseCode); String responseBody = httpMethod.getResponseBodyAsString(); assertEquals(null, responseBody); assertNull(httpMethod.getResponseHeader("Content-Encoding")); assertNotNull(httpMethod.getResponseHeader("Last-Modified").getValue()); checkNullOrZeroContentLength(httpMethod); }
From source file:com.remobile.filetransfer.FileTransfer.java
/** * Downloads a file form a given URL and saves it to the specified directory. * * @param source URL of the server to receive the file * @param target Full path of the file on the file system *//*from w w w .j av a2 s .c om*/ private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.d(LOG_TAG, "download " + source + " to " + target); final CordovaResourceApi resourceApi = new CordovaResourceApi(getReactApplicationContext()); final boolean trustEveryone = args.optBoolean(2); final String objectId = args.getString(3); final JSONObject headers = args.optJSONObject(4); final Uri sourceUri = resourceApi.remapUri(Uri.parse(source)); // Accept a path or a URI for the source. Uri tmpTarget = Uri.parse(target); final Uri targetUri = resourceApi .remapUri(tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target))); int uriType = CordovaResourceApi.getUriType(sourceUri); final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP; if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null); Log.e(LOG_TAG, "Unsupported URI: " + sourceUri); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } final RequestContext context = new RequestContext(source, target, callbackContext); synchronized (activeRequests) { activeRequests.put(objectId, context); } this.cordova.getThreadPool().execute(new Runnable() { public void run() { if (context.aborted) { return; } HttpURLConnection connection = null; HostnameVerifier oldHostnameVerifier = null; SSLSocketFactory oldSocketFactory = null; File file = null; PluginResult result = null; TrackingInputStream inputStream = null; boolean cached = false; OutputStream outputStream = null; try { CordovaResourceApi.OpenForReadResult readResult = null; file = resourceApi.mapUriToFile(targetUri); context.targetFile = file; Log.d(LOG_TAG, "Download file:" + sourceUri); FileProgressResult progress = new FileProgressResult(); if (isLocalTransfer) { readResult = resourceApi.openForRead(sourceUri); if (readResult.length != -1) { progress.setLengthComputable(true); progress.setTotal(readResult.length); } inputStream = new SimpleTrackingInputStream(readResult.inputStream); } else { // connect to server // Open a HTTP connection to the URL based on protocol connection = resourceApi.createHttpConnection(sourceUri); if (useHttps && trustEveryone) { // Setup the HTTPS connection class to trust everyone HttpsURLConnection https = (HttpsURLConnection) connection; oldSocketFactory = trustAllHosts(https); // Save the current hostnameVerifier oldHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); } connection.setRequestMethod("GET"); // This must be explicitly set for gzip progress tracking to work. connection.setRequestProperty("Accept-Encoding", "gzip"); // Handle the other headers if (headers != null) { addHeadersToRequest(connection, headers); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { cached = true; connection.disconnect(); Log.d(LOG_TAG, "Resource not modified: " + source); JSONObject error = createFileTransferError(NOT_MODIFIED_ERR, source, target, connection, null); result = new PluginResult(PluginResult.Status.ERROR, error); } else { if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) { // Only trust content-length header if we understand // the encoding -- identity or gzip if (connection.getContentLength() != -1) { progress.setLengthComputable(true); progress.setTotal(connection.getContentLength()); } } inputStream = getInputStream(connection); } } if (!cached) { try { synchronized (context) { if (context.aborted) { return; } context.connection = connection; } // write bytes to file byte[] buffer = new byte[MAX_BUFFER_SIZE]; int bytesRead = 0; outputStream = resourceApi.openOutputStream(targetUri); while ((bytesRead = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, bytesRead); // Send a progress event. progress.setLoaded(inputStream.getTotalRawBytesRead()); FileTransfer.this.sendJSEvent("DownloadProgress-" + objectId, JsonConvert.jsonToReact(progress.toJSONObject())); } } finally { synchronized (context) { context.connection = null; } safeClose(inputStream); safeClose(outputStream); } Log.d(LOG_TAG, "Saved file: " + target); file = resourceApi.mapUriToFile(targetUri); context.targetFile = file; result = new PluginResult(PluginResult.Status.OK, targetUri.getPath()); } } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection, e); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); result = new PluginResult(PluginResult.Status.JSON_EXCEPTION); } catch (Throwable e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } finally { synchronized (activeRequests) { activeRequests.remove(objectId); } if (connection != null) { // Revert back to the proper verifier and socket factories if (trustEveryone && useHttps) { HttpsURLConnection https = (HttpsURLConnection) connection; https.setHostnameVerifier(oldHostnameVerifier); https.setSSLSocketFactory(oldSocketFactory); } } if (result == null) { result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection, null)); } // Remove incomplete download. if (!cached && result.status.ordinal() != PluginResult.Status.OK.ordinal() && file != null) { file.delete(); } context.sendPluginResult(result); } } }); }