List of usage examples for org.apache.commons.httpclient.util DateUtil parseDate
public static Date parseDate(String paramString) throws DateParseException
From source file:org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientRetrieveFileTransfer.java
private long getLastModifiedTimeFromHeader() throws IOException { Header lastModifiedHeader = getMethod.getResponseHeader(LAST_MODIFIED_HEADER); if (lastModifiedHeader == null) throw new IOException(Messages.HttpClientRetrieveFileTransfer_INVALID_LAST_MODIFIED_TIME); String lastModifiedString = lastModifiedHeader.getValue(); long lastModified = 0; if (lastModifiedString != null) { try {/*from ww w. j a va 2 s .c o m*/ lastModified = DateUtil.parseDate(lastModifiedString).getTime(); } catch (Exception e) { throw new IOException( Messages.HttpClientRetrieveFileTransfer_EXCEPITION_INVALID_LAST_MODIFIED_FROM_SERVER); } } return lastModified; }
From source file:org.eclipse.mylyn.internal.bugzilla.core.BugzillaClient.java
public RepositoryConfiguration getRepositoryConfiguration(IProgressMonitor monitor, String eTagValue) throws IOException, CoreException { GzipGetMethod method = null;//from www. j av a 2s . c o m int attempt = 0; while (attempt < 2) { try { method = getConnectGzip(repositoryUrl + IBugzillaConstants.URL_GET_CONFIG_RDF, monitor, eTagValue); // provide a solution for bug 196056 by allowing a (cached) gzipped configuration to be sent // modified to also accept "application/x-gzip" as results from a 302 redirect to a previously gzipped file. if (method == null) { throw new IOException("Could not retrieve configuratoin. HttpClient return null method."); //$NON-NLS-1$ } InputStream stream = getResponseStream(method, monitor); try { if (method.getResponseHeader("Content-Type") != null) { //$NON-NLS-1$ Header responseTypeHeader = method.getResponseHeader("Content-Type"); //$NON-NLS-1$ for (String type : VALID_CONFIG_CONTENT_TYPES) { if (responseTypeHeader.getValue().toLowerCase(Locale.ENGLISH).contains(type)) { RepositoryConfigurationFactory configFactory = new RepositoryConfigurationFactory( stream, getCharacterEncoding()); repositoryConfiguration = configFactory.getConfiguration(); Header eTag = method.getResponseHeader("ETag"); //$NON-NLS-1$ if (eTag != null) { repositoryConfiguration.setETagValue(eTag.getValue()); } else { repositoryConfiguration.setETagValue(null); } Header lastModifiedHeader = method.getResponseHeader("Last-Modified"); //$NON-NLS-1$ if (lastModifiedHeader != null) { try { repositoryConfiguration.setLastModifiedHeader( DateUtil.parseDate(lastModifiedHeader.getValue())); } catch (DateParseException e) { repositoryConfiguration.setLastModifiedHeader((Date) null); } } else { repositoryConfiguration.setLastModifiedHeader((Date) null); } if (repositoryConfiguration != null) { getXmlRpcClient(); if (xmlRpcClient != null) { xmlRpcClient.updateConfiguration(monitor, repositoryConfiguration, configParameters.get(IBugzillaConstants.BUGZILLA_DESCRIPTOR_FILE)); } else { repositoryConfiguration.setValidTransitions(monitor, configParameters.get(IBugzillaConstants.BUGZILLA_DESCRIPTOR_FILE), null); } if (!repositoryConfiguration.getOptionValues(BugzillaAttribute.PRODUCT) .isEmpty()) { repositoryConfiguration.setRepositoryUrl(repositoryUrl.toString()); } if (!repositoryConfiguration.getOptionValues(BugzillaAttribute.PRODUCT) .isEmpty()) { return repositoryConfiguration; } else { if (attempt == 0) { // empty configuration, retry authenticate loggedIn = false; break; } else { throw new CoreException(new Status(IStatus.WARNING, BugzillaCorePlugin.ID_PLUGIN, "No products found in repository configuration. Ensure credentials are valid.")); //$NON-NLS-1$ } } } } } } if (loggedIn) { throw new CoreException(parseHtmlError(stream)); } } finally { stream.close(); } } finally { attempt++; if (method != null) { WebUtil.releaseConnection(method, monitor); } } } return null; }
From source file:org.eclipse.mylyn.internal.discovery.core.util.HttpClientTransportService.java
/** * Verify availability of resources at the given web locations. Normally this would be done using an HTTP HEAD. * /*w w w .j a v a 2 s . c o m*/ * @param locations * the locations of the resource to verify * @param one * indicate if only one of the resources must exist * @param monitor * the monitor * @return true if the resource exists */ public long getLastModified(java.net.URI uri, IProgressMonitor monitor) throws CoreException, IOException { WebLocation location = new WebLocation(uri.toString()); monitor = Policy.monitorFor(monitor); monitor.beginTask(NLS.bind(Messages.WebUtil_task_retrievingUrl, location.getUrl()), IProgressMonitor.UNKNOWN); try { HttpClient client = new HttpClient(); org.eclipse.mylyn.commons.net.WebUtil.configureHttpClient(client, ""); //$NON-NLS-1$ HeadMethod method = new HeadMethod(location.getUrl()); try { HostConfiguration hostConfiguration = org.eclipse.mylyn.commons.net.WebUtil .createHostConfiguration(client, location, monitor); int result = org.eclipse.mylyn.commons.net.WebUtil.execute(client, hostConfiguration, method, monitor); if (result == HttpStatus.SC_OK) { Header lastModified = method.getResponseHeader("Last-Modified"); //$NON-NLS-1$ if (lastModified != null) { try { return DateUtil.parseDate(lastModified.getValue()).getTime(); } catch (DateParseException e) { // fall through } } return 0; } else if (result == HttpStatus.SC_NOT_FOUND) { throw new FileNotFoundException( NLS.bind(Messages.WebUtil_cannotDownload, location.getUrl(), result)); } else { throw new IOException(NLS.bind(Messages.WebUtil_cannotDownload, location.getUrl(), result)); } } finally { method.releaseConnection(); } } finally { monitor.done(); } }
From source file:org.eclipse.virgo.ide.runtime.internal.core.utils.WebDownloadUtils.java
public static Date getLastModifiedDate(String url, IProgressMonitor monitor) { GetMethod method = null;/*from w w w . j ava 2 s . c om*/ BufferedInputStream bis = null; FileOutputStream fos = null; try { if (monitor.isCanceled()) { return null; } HttpClient client = new HttpClient(); method = new GetMethod(url); method.setFollowRedirects(true); HostConfiguration hostConfiguration = new HostConfiguration(); hostConfiguration.setHost(getHost(url), HTTP_PORT, "http"); configureHttpClientProxy(url, client, hostConfiguration); client.getHttpConnectionManager().getParams().setSoTimeout(SOCKET_TIMEOUT); client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNNECT_TIMEOUT); // Execute the GET method int statusCode = client.executeMethod(hostConfiguration, method); if (statusCode == 200) { if (monitor.isCanceled()) { return null; } Header lastModified = method.getResponseHeader("Last-Modified"); if (lastModified != null) { return DateUtil.parseDate(lastModified.getValue()); } } } catch (Exception e) { } finally { try { if (method != null) { method.releaseConnection(); } } catch (Exception e2) { } try { if (bis != null) { bis.close(); } } catch (Exception e2) { } try { if (fos != null) { fos.close(); } } catch (Exception e2) { } } return null; }
From source file:org.geoserver.gwc.GWCIntegrationTest.java
@Test public void testDirectWMSIntegrationIfModifiedSinceSupport() throws Exception { final GWC gwc = GWC.get(); gwc.getConfig().setDirectWMSIntegrationEnabled(true); final String layerName = BASIC_POLYGONS.getPrefix() + ":" + BASIC_POLYGONS.getLocalPart(); final String path = buildGetMap(true, layerName, "EPSG:4326", null) + "&tiled=true"; MockHttpServletResponse response = getAsServletResponse(path); assertEquals(200, response.getStatusCode()); assertEquals("image/png", response.getContentType()); String lastModifiedHeader = response.getHeader("Last-Modified"); assertNotNull(lastModifiedHeader);/*from ww w . j a v a2 s . c om*/ Date lastModified = DateUtil.parseDate(lastModifiedHeader); MockHttpServletRequest httpReq = createRequest(path); httpReq.setMethod("GET"); httpReq.setBodyContent(new byte[] {}); httpReq.setHeader("If-Modified-Since", lastModifiedHeader); response = dispatch(httpReq, "UTF-8"); assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getErrorCode()); // set the If-Modified-Since header to some point in the past of the last modified value Date past = new Date(lastModified.getTime() - 5000); String ifModifiedSince = DateUtil.formatDate(past); httpReq.setHeader("If-Modified-Since", ifModifiedSince); response = dispatch(httpReq, "UTF-8"); assertEquals(HttpServletResponse.SC_OK, response.getErrorCode()); Date future = new Date(lastModified.getTime() + 5000); ifModifiedSince = DateUtil.formatDate(future); httpReq.setHeader("If-Modified-Since", ifModifiedSince); response = dispatch(httpReq, "UTF-8"); assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getErrorCode()); }
From source file:org.geoserver.gwc.wms.CachingWebMapService.java
private void setConditionalGetHeaders(RawMap map, ConveyorTile cachedTile, GetMapRequest request, String etag) { map.setResponseHeader("ETag", etag); final long tileTimeStamp = cachedTile.getTSCreated(); final String ifModSinceHeader = request.getHttpRequestHeader("If-Modified-Since"); // commons-httpclient's DateUtil can encode and decode timestamps formatted as per RFC-1123, // which is one of the three formats allowed for Last-Modified and If-Modified-Since headers // (e.g. 'Sun, 06 Nov 1994 08:49:37 GMT'). See // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 final String lastModified = org.apache.commons.httpclient.util.DateUtil.formatDate(new Date(tileTimeStamp)); map.setResponseHeader("Last-Modified", lastModified); final Date ifModifiedSince; if (ifModSinceHeader != null && ifModSinceHeader.length() > 0) { try {/* w w w . j av a 2s.c o m*/ ifModifiedSince = DateUtil.parseDate(ifModSinceHeader); // the HTTP header has second precision long ifModSinceSeconds = 1000 * (ifModifiedSince.getTime() / 1000); long tileTimeStampSeconds = 1000 * (tileTimeStamp / 1000); if (ifModSinceSeconds >= tileTimeStampSeconds) { throw new HttpErrorCodeException(HttpServletResponse.SC_NOT_MODIFIED); } } catch (DateParseException e) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("Can't parse client's If-Modified-Since header: '" + ifModSinceHeader + "'"); } } } }
From source file:org.geowebcache.GeoWebCacheDispatcher.java
/** * Happy ending, sets the headers and writes the response back to the client. *//*w ww .j ava2 s.com*/ private void writeData(ConveyorTile tile) throws IOException { HttpServletResponse servletResp = tile.servletResp; final HttpServletRequest servletReq = tile.servletReq; final CacheResult cacheResult = tile.getCacheResult(); int httpCode = HttpServletResponse.SC_OK; String mimeType = tile.getMimeType().getMimeType(); Resource blob = tile.getBlob(); servletResp.setHeader("geowebcache-cache-result", String.valueOf(cacheResult)); servletResp.setHeader("geowebcache-tile-index", Arrays.toString(tile.getTileIndex())); long[] tileIndex = tile.getTileIndex(); TileLayer layer = tile.getLayer(); GridSubset gridSubset = layer.getGridSubset(tile.getGridSetId()); BoundingBox tileBounds = gridSubset.boundsFromIndex(tileIndex); servletResp.setHeader("geowebcache-tile-bounds", tileBounds.toString()); servletResp.setHeader("geowebcache-gridset", gridSubset.getName()); servletResp.setHeader("geowebcache-crs", gridSubset.getSRS().toString()); final long tileTimeStamp = tile.getTSCreated(); final String ifModSinceHeader = servletReq.getHeader("If-Modified-Since"); // commons-httpclient's DateUtil can encode and decode timestamps formatted as per RFC-1123, // which is one of the three formats allowed for Last-Modified and If-Modified-Since headers // (e.g. 'Sun, 06 Nov 1994 08:49:37 GMT'). See // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 final String lastModified = org.apache.commons.httpclient.util.DateUtil.formatDate(new Date(tileTimeStamp)); servletResp.setHeader("Last-Modified", lastModified); final Date ifModifiedSince; if (ifModSinceHeader != null && ifModSinceHeader.length() > 0) { try { ifModifiedSince = DateUtil.parseDate(ifModSinceHeader); // the HTTP header has second precision long ifModSinceSeconds = 1000 * (ifModifiedSince.getTime() / 1000); long tileTimeStampSeconds = 1000 * (tileTimeStamp / 1000); if (ifModSinceSeconds >= tileTimeStampSeconds) { httpCode = HttpServletResponse.SC_NOT_MODIFIED; blob = null; } } catch (DateParseException e) { if (log.isDebugEnabled()) { log.debug("Can't parse client's If-Modified-Since header: '" + ifModSinceHeader + "'"); } } } if (httpCode == HttpServletResponse.SC_OK && tile.getLayer().useETags()) { String ifNoneMatch = servletReq.getHeader("If-None-Match"); String hexTag = Long.toHexString(tileTimeStamp); if (ifNoneMatch != null) { if (ifNoneMatch.equals(hexTag)) { httpCode = HttpServletResponse.SC_NOT_MODIFIED; blob = null; } } // If we get here, we want ETags but the client did not have the tile. servletResp.setHeader("ETag", hexTag); } int contentLength = (int) (blob == null ? -1 : blob.getSize()); writeFixedResponse(servletResp, httpCode, mimeType, blob, cacheResult, contentLength); }
From source file:org.geowebcache.util.ResponseUtils.java
/** * Happy ending, sets the headers and writes the response back to the client. *//*from w w w.j a va 2 s .c o m*/ private static void writeData(ConveyorTile tile, RuntimeStats runtimeStats) throws IOException { HttpServletResponse servletResp = tile.servletResp; final HttpServletRequest servletReq = tile.servletReq; final CacheResult cacheResult = tile.getCacheResult(); int httpCode = HttpServletResponse.SC_OK; Resource blob = tile.getBlob(); String mimeType = tile.getMimeType().getMimeType(blob); servletResp.setHeader("geowebcache-cache-result", String.valueOf(cacheResult)); servletResp.setHeader("geowebcache-tile-index", Arrays.toString(tile.getTileIndex())); long[] tileIndex = tile.getTileIndex(); TileLayer layer = tile.getLayer(); GridSubset gridSubset = layer.getGridSubset(tile.getGridSetId()); BoundingBox tileBounds = gridSubset.boundsFromIndex(tileIndex); servletResp.setHeader("geowebcache-tile-bounds", tileBounds.toString()); servletResp.setHeader("geowebcache-gridset", gridSubset.getName()); servletResp.setHeader("geowebcache-crs", gridSubset.getSRS().toString()); final long tileTimeStamp = tile.getTSCreated(); final String ifModSinceHeader = servletReq.getHeader("If-Modified-Since"); // commons-httpclient's DateUtil can encode and decode timestamps formatted as per RFC-1123, // which is one of the three formats allowed for Last-Modified and If-Modified-Since headers // (e.g. 'Sun, 06 Nov 1994 08:49:37 GMT'). See // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 final String lastModified = org.apache.commons.httpclient.util.DateUtil.formatDate(new Date(tileTimeStamp)); servletResp.setHeader("Last-Modified", lastModified); final Date ifModifiedSince; if (ifModSinceHeader != null && ifModSinceHeader.length() > 0) { try { ifModifiedSince = DateUtil.parseDate(ifModSinceHeader); // the HTTP header has second precision long ifModSinceSeconds = 1000 * (ifModifiedSince.getTime() / 1000); long tileTimeStampSeconds = 1000 * (tileTimeStamp / 1000); if (ifModSinceSeconds >= tileTimeStampSeconds) { httpCode = HttpServletResponse.SC_NOT_MODIFIED; blob = null; } } catch (DateParseException e) { if (log.isDebugEnabled()) { log.debug("Can't parse client's If-Modified-Since header: '" + ifModSinceHeader + "'"); } } } if (httpCode == HttpServletResponse.SC_OK && tile.getLayer().useETags()) { String ifNoneMatch = servletReq.getHeader("If-None-Match"); String hexTag = Long.toHexString(tileTimeStamp); if (ifNoneMatch != null) { if (ifNoneMatch.equals(hexTag)) { httpCode = HttpServletResponse.SC_NOT_MODIFIED; blob = null; } } // If we get here, we want ETags but the client did not have the tile. servletResp.setHeader("ETag", hexTag); } int contentLength = (int) (blob == null ? -1 : blob.getSize()); writeFixedResponse(servletResp, httpCode, mimeType, blob, cacheResult, contentLength, runtimeStats); }
From source file:org.gss_project.gss.server.rest.FilesHandler.java
/** * Serve the specified resource, optionally including the data content. *//from w w w .ja va 2 s .co m * @param req The servlet request we are processing * @param resp The servlet response we are creating * @param content Should the content be included? * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs * @throws RpcException * @throws InsufficientPermissionsException * @throws ObjectNotFoundException */ @Override protected void serveResource(HttpServletRequest req, HttpServletResponse resp, boolean content) throws IOException, ServletException { boolean authDeferred = getAuthDeferred(req); String path = getInnerPath(req, PATH_FILES); if (path.equals("")) path = "/"; try { path = URLDecoder.decode(path, "UTF-8"); } catch (IllegalArgumentException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } String progress = req.getParameter(PROGRESS_PARAMETER); if (logger.isDebugEnabled()) if (content) logger.debug("Serving resource '" + path + "' headers and data"); else logger.debug("Serving resource '" + path + "' headers only"); User user = getUser(req); User owner = getOwner(req); boolean exists = true; Object resource = null; FileHeader file = null; Folder folder = null; try { resource = getService().getResourceAtPath(owner.getId(), path, false); } catch (ObjectNotFoundException e) { exists = false; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (!exists && authDeferred) { // We do not want to leak information if the request // was not authenticated. resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } if (resource instanceof Folder) folder = (Folder) resource; else file = (FileHeader) resource; // Note that file will be null, if (!exists). // Now it's time to perform the deferred authentication check. // Since regular signature checking was already performed, // we need to check the read-all flag or the signature-in-parameters. if (authDeferred) { if (file != null && !file.isReadForAll() && content) { // Check for GET with the signature in the request parameters. String auth = req.getParameter(AUTHORIZATION_PARAMETER); String dateParam = req.getParameter(DATE_PARAMETER); if (auth == null || dateParam == null) { // Check for a valid authentication cookie. if (req.getCookies() != null) { boolean found = false; for (Cookie cookie : req.getCookies()) if (Login.AUTH_COOKIE.equals(cookie.getName())) { String cookieauth = cookie.getValue(); int sepIndex = cookieauth.indexOf(Login.COOKIE_SEPARATOR); if (sepIndex == -1) { handleAuthFailure(req, resp); return; } String username = URLDecoder.decode(cookieauth.substring(0, sepIndex), "US-ASCII"); user = null; try { user = getService().findUser(username); } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (user == null) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } req.setAttribute(USER_ATTRIBUTE, user); String token = cookieauth.substring(sepIndex + 1); if (user.getAuthToken() == null) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } if (!Arrays.equals(user.getAuthToken(), Base64.decodeBase64(token))) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } found = true; break; } if (!found) { handleAuthFailure(req, resp); return; } } else { handleAuthFailure(req, resp); return; } } else { long timestamp; try { timestamp = DateUtil.parseDate(dateParam).getTime(); } catch (DateParseException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; } // Fetch the Authorization parameter and find the user specified in it. String[] authParts = auth.split(" "); if (authParts.length != 2) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String username = authParts[0]; String signature = authParts[1]; user = null; try { user = getService().findUser(username); } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (user == null) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } req.setAttribute(USER_ATTRIBUTE, user); // Remove the servlet path from the request URI. String p = req.getRequestURI(); String servletPath = req.getContextPath() + req.getServletPath(); p = p.substring(servletPath.length()); // Validate the signature in the Authorization parameter. String data = req.getMethod() + dateParam + p; if (!isSignatureValid(signature, user, data)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } } else if (folder != null && folder.isReadForAll() || file != null && file.isReadForAll()) { //This case refers to a folder or file with public privileges //For a read-for-all folder request, pretend the owner is making it. user = owner; req.setAttribute(USER_ATTRIBUTE, user); } else if (folder != null && !folder.isReadForAll()) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } else { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } // If the resource is not a collection, and the resource path // ends with "/" or "\", return NOT FOUND. if (folder == null) if (path.endsWith("/") || path.endsWith("\\")) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getRequestURI()); return; } // Workaround for IE's broken caching behavior. if (folder != null) resp.setHeader("Expires", "-1"); // A request for upload progress. if (progress != null && content) { serveProgress(req, resp, progress, user, file); return; } // Fetch the version to retrieve, if specified. String verStr = req.getParameter(VERSION_PARAM); int version = 0; FileBody oldBody = null; if (verStr != null && file != null) try { version = Integer.valueOf(verStr); } catch (NumberFormatException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, req.getRequestURI()); return; } if (version > 0) try { oldBody = getService().getFileVersion(user.getId(), file.getId(), version); } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (ObjectNotFoundException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (InsufficientPermissionsException e) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } // Check if the conditions specified in the optional If headers are // satisfied. Doing this for folders would require recursive checking // for all of their children, which in turn would defy the purpose of // the optimization. if (folder == null) { // Checking If headers. if (!checkIfHeaders(req, resp, file, oldBody)) return; } else if (!checkIfModifiedSince(req, resp, folder)) return; // Find content type. String contentType = null; boolean isContentHtml = false; boolean expectJSON = false; if (file != null) { contentType = version > 0 ? oldBody.getMimeType() : file.getCurrentBody().getMimeType(); if (contentType == null) { contentType = context.getMimeType(file.getName()); file.getCurrentBody().setMimeType(contentType); } } else { // folder != null String accept = req.getHeader("Accept"); // The order in this conditional pessimizes the common API case, // but is important for backwards compatibility with existing // clients who send no accept header and expect a JSON response. if (accept != null && accept.contains("text/html")) { contentType = "text/html;charset=UTF-8"; isContentHtml = true; //this is the case when clients send the appropriate headers, the contentType is "text/html" //and expect a JSON response. The above check applies to FireGSS client expectJSON = !authDeferred ? true : false; } else if (authDeferred && req.getMethod().equals(METHOD_GET)) { contentType = "text/html;charset=UTF-8"; isContentHtml = true; expectJSON = false; } else { contentType = "application/json;charset=UTF-8"; expectJSON = true; } } ArrayList ranges = null; long contentLength = -1L; if (file != null) { // Parse range specifier. ranges = parseRange(req, resp, file, oldBody); // ETag header resp.setHeader("ETag", getETag(file, oldBody)); // Last-Modified header. String lastModified = oldBody == null ? getLastModifiedHttp(file.getAuditInfo()) : getLastModifiedHttp(oldBody.getAuditInfo()); resp.setHeader("Last-Modified", lastModified); // X-GSS-Metadata header. try { resp.setHeader("X-GSS-Metadata", renderJson(user, file, oldBody)); } catch (InsufficientPermissionsException e) { resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } // Get content length. contentLength = version > 0 ? oldBody.getFileSize() : file.getCurrentBody().getFileSize(); // Special case for zero length files, which would cause a // (silent) ISE when setting the output buffer size. if (contentLength == 0L) content = false; } else // Set the folder X-GSS-Metadata header. try { resp.setHeader("X-GSS-Metadata", renderJsonMetadata(user, folder)); } catch (InsufficientPermissionsException e) { resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } ServletOutputStream ostream = null; PrintWriter writer = null; if (content) try { ostream = resp.getOutputStream(); } catch (IllegalStateException e) { // If it fails, we try to get a Writer instead if we're // trying to serve a text file if (contentType == null || contentType.startsWith("text") || contentType.endsWith("xml")) writer = resp.getWriter(); else throw e; } if (folder != null || (ranges == null || ranges.isEmpty()) && req.getHeader("Range") == null || ranges == FULL) { // Set the appropriate output headers if (contentType != null) { if (logger.isDebugEnabled()) logger.debug("contentType='" + contentType + "'"); resp.setContentType(contentType); } if (file != null && contentLength >= 0) { if (logger.isDebugEnabled()) logger.debug("contentLength=" + contentLength); if (contentLength < Integer.MAX_VALUE) resp.setContentLength((int) contentLength); else // Set the content-length as String to be able to use a long resp.setHeader("content-length", "" + contentLength); } InputStream renderResult = null; String relativePath = getRelativePath(req); String contextPath = req.getContextPath(); String servletPath = req.getServletPath(); String contextServletPath = contextPath + servletPath; if (folder != null && content) // Serve the directory browser for a public folder if (isContentHtml && !expectJSON) { try { folder = getService().expandFolder(folder); } catch (ObjectNotFoundException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (RpcException e) { //We send 500 instead of 404 because this folder has been loaded before in this method and it is //impossible to not be found now resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } renderResult = renderHtml(contextServletPath, relativePath, folder, user); } // Serve the directory for an ordinary folder or for fireGSS client else try { renderResult = renderJson(user, folder); } catch (InsufficientPermissionsException e) { resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } // Copy the input stream to our output stream (if requested) if (content) { try { resp.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } try { if (file != null) if (needsContentDisposition(req)) resp.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + getDispositionFilename(file)); else resp.setHeader("Content-Disposition", "inline; filename*=UTF-8''" + getDispositionFilename(file)); if (ostream != null) copy(file, renderResult, ostream, req, oldBody); else copy(file, renderResult, writer, req, oldBody); if (file != null) updateAccounting(owner, new Date(), contentLength); } catch (ObjectNotFoundException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (InsufficientPermissionsException e) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } } else { if (ranges == null || ranges.isEmpty()) return; // Partial content response. resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { Range range = (Range) ranges.get(0); resp.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) resp.setContentLength((int) length); else // Set the content-length as String to be able to use a long resp.setHeader("content-length", "" + length); if (contentType != null) { if (logger.isDebugEnabled()) logger.debug("contentType='" + contentType + "'"); resp.setContentType(contentType); } if (content) { try { resp.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } try { if (ostream != null) copy(file, ostream, range, req, oldBody); else copy(file, writer, range, req, oldBody); updateAccounting(owner, new Date(), contentLength); } catch (ObjectNotFoundException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (InsufficientPermissionsException e) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } } else { resp.setContentType("multipart/byteranges; boundary=" + mimeSeparation); if (content) { try { resp.setBufferSize(output); } catch (IllegalStateException e) { // Silent catch } try { if (ostream != null) copy(file, ostream, ranges.iterator(), contentType, req, oldBody); else copy(file, writer, ranges.iterator(), contentType, req, oldBody); updateAccounting(owner, new Date(), contentLength); } catch (ObjectNotFoundException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (InsufficientPermissionsException e) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } } } }
From source file:org.gss_project.gss.server.rest.FilesHandler.java
/** * A method for handling multipart POST requests for uploading * files from browser-based JavaScript clients. * * @param request the HTTP request/*from ww w . j ava2 s .c om*/ * @param response the HTTP response * @param path the resource path * @throws IOException in case an error occurs writing to the * response stream */ private void handleMultipart(HttpServletRequest request, HttpServletResponse response, String path) throws IOException { if (logger.isDebugEnabled()) logger.debug("Multipart POST for resource: " + path); User owner = getOwner(request); boolean exists = true; Object resource = null; FileHeader file = null; try { resource = getService().getResourceAtPath(owner.getId(), path, false); } catch (ObjectNotFoundException e) { exists = false; } catch (RpcException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (exists) if (resource instanceof FileHeader) { file = (FileHeader) resource; if (file.isDeleted()) { response.sendError(HttpServletResponse.SC_CONFLICT, file.getName() + " is in the trash"); return; } } else { response.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder"); return; } Object parent; String parentPath = null; try { parentPath = getParentPath(path); parent = getService().getResourceAtPath(owner.getId(), parentPath, true); } catch (ObjectNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND, parentPath); return; } catch (RpcException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (!(parent instanceof Folder)) { response.sendError(HttpServletResponse.SC_CONFLICT); return; } final Folder folderLocal = (Folder) parent; final String fileName = getLastElement(path); if (!isValidResourceName(fileName)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } FileItemIterator iter; File uploadedFile = null; try { // Create a new file upload handler. ServletFileUpload upload = new ServletFileUpload(); StatusProgressListener progressListener = new StatusProgressListener(getService()); upload.setProgressListener(progressListener); iter = upload.getItemIterator(request); String dateParam = null; String auth = null; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { final String value = Streams.asString(stream); if (name.equals(DATE_PARAMETER)) dateParam = value; else if (name.equals(AUTHORIZATION_PARAMETER)) auth = value; if (logger.isDebugEnabled()) logger.debug(name + ":" + value); } else { // Fetch the timestamp used to guard against replay attacks. if (dateParam == null) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Date parameter"); return; } long timestamp; try { timestamp = DateUtil.parseDate(dateParam).getTime(); } catch (DateParseException e) { response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; } // Fetch the Authorization parameter and find the user specified in it. if (auth == null) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Authorization parameter"); return; } String[] authParts = auth.split(" "); if (authParts.length != 2) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String username = authParts[0]; String signature = authParts[1]; User user = null; try { user = getService().findUser(username); } catch (RpcException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (user == null) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } request.setAttribute(USER_ATTRIBUTE, user); // Remove the servlet path from the request URI. String p = request.getRequestURI(); String servletPath = request.getContextPath() + request.getServletPath(); p = p.substring(servletPath.length()); // Validate the signature in the Authorization parameter. String data = request.getMethod() + dateParam + p; if (!isSignatureValid(signature, user, data)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } progressListener.setUserId(user.getId()); progressListener.setFilename(fileName); final String contentType = item.getContentType(); try { uploadedFile = getService().uploadFile(stream, user.getId()); } catch (IOException ex) { throw new GSSIOException(ex, false); } FileHeader fileLocal = null; final File upf = uploadedFile; final FileHeader f = file; final User u = user; if (file == null) fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().createFile(u.getId(), folderLocal.getId(), fileName, contentType, upf.getCanonicalFile().length(), upf.getAbsolutePath()); } }); else fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().updateFileContents(u.getId(), f.getId(), contentType, upf.getCanonicalFile().length(), upf.getAbsolutePath()); } }); updateAccounting(owner, new Date(), fileLocal.getCurrentBody().getFileSize()); getService().removeFileUploadProgress(user.getId(), fileName); } } // We can't return 204 here since GWT's onSubmitComplete won't fire. response.setContentType("text/html"); response.getWriter().print("<pre></pre>"); } catch (FileUploadException e) { String error = "Error while uploading file"; logger.error(error, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); } catch (GSSIOException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "Error while uploading file"; if (e.logAsError()) logger.error(error, e); else logger.debug(error, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); } catch (DuplicateNameException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "The specified file name already exists in this folder"; logger.error(error, e); response.sendError(HttpServletResponse.SC_CONFLICT, error); } catch (InsufficientPermissionsException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "You don't have the necessary permissions"; logger.error(error, e); response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, error); } catch (QuotaExceededException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "Not enough free space available"; if (logger.isDebugEnabled()) logger.debug(error, e); response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, error); } catch (ObjectNotFoundException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "A specified object was not found"; logger.error(error, e); response.sendError(HttpServletResponse.SC_NOT_FOUND, error); } catch (RpcException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "An error occurred while communicating with the service"; logger.error(error, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); } catch (Exception e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "An internal server error occurred"; logger.error(error, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); } }