List of usage examples for javax.servlet.http HttpServletResponse getContentType
public String getContentType();
From source file:au.gov.aims.atlasmapperserver.servlet.Proxy.java
private void performTask(HttpServletRequest request, HttpServletResponse response) throws IOException { String clientId = request.getParameter("client"); String urlStr = request.getParameter(URL_PARAM); if (urlStr != null && !urlStr.isEmpty()) { LOGGER.log(Level.INFO, "Proxy URL: {0}", urlStr); try {//from www . j a v a 2s . co m String decodedUrl = URLDecoder.decode(urlStr, "UTF-8"); if (decodedUrl != null) { decodedUrl = decodedUrl.trim(); } URL url = Utils.toURL(decodedUrl); if (url != null) { String protocol = url.getProtocol(); String host = url.getHost(); if (!isHostAllowed(clientId, host)) { response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); String responseTxt = "This proxy does not allow you to access that location (" + host + ")."; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } else if (protocol.equals("http") || protocol.equals("https")) { HttpGet httpGet = new HttpGet(url.toURI()); HttpEntity entity = null; try { HttpResponse httpClientResponse = httpClient.execute(httpGet); StatusLine httpStatus = httpClientResponse.getStatusLine(); int responseCode = -1; if (httpStatus != null) { responseCode = httpStatus.getStatusCode(); } response.setStatus(responseCode); if (responseCode < 400) { // The entity is streamed entity = httpClientResponse.getEntity(); String contentType = null; if (entity != null) { Header header = entity.getContentType(); contentType = header.getValue(); } // -1: Unknown status code // 1XX: Informational // 2XX: Successful // 3XX: Redirection if (contentType == null || contentType.isEmpty()) { response.setContentType("text/plain"); LOGGER.log(Level.INFO, "Can not retrieved the content type, falling back to: {0}", response.getContentType()); } else { response.setContentType(contentType); LOGGER.log(Level.INFO, "Set content type using URL connection content type: {0}", response.getContentType()); } InputStream inputStream = null; try { inputStream = entity.getContent(); ServletUtils.sendResponse(response, inputStream); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { LOGGER.log(Level.WARNING, "Cant close the URL input stream: {0}", Utils.getExceptionMessage(e)); LOGGER.log(Level.FINE, "Stack trace: ", e); } } } } else if (responseCode == HttpServletResponse.SC_BAD_REQUEST) { // 400: Bad Request response.setContentType("text/plain"); String responseTxt = "Error " + responseCode + " - Bad Request: " + decodedUrl; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } else if (responseCode == HttpServletResponse.SC_NOT_FOUND) { // 404: Not Found response.setContentType("text/plain"); String responseTxt = "Error " + responseCode + " - Not Found: " + decodedUrl; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } else if (responseCode == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { // 500: Internal Server Error response.setContentType("text/plain"); String responseTxt = "Error " + responseCode + " - Internal Server Error: " + decodedUrl; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } else { // Any other errors response.setContentType("text/plain"); String responseTxt = "Error " + responseCode + ": " + decodedUrl; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } } finally { if (httpGet != null) { // Cancel the connection, if it's still alive httpGet.abort(); // Close connections httpGet.reset(); } } } else { response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); String responseTxt = "Error - Unsupported protocol: " + decodedUrl; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } } } catch (Exception e) { response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String responseTxt = "An unexpected error occurred: " + Utils.getExceptionMessage(e); LOGGER.log(Level.WARNING, responseTxt); LOGGER.log(Level.FINE, "Stack trace: ", e); ServletUtils.sendResponse(response, responseTxt); } } else { response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String responseTxt = "Can't get url value from request."; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } }
From source file:de.innovationgate.wgpublisher.WGPDispatcher.java
public boolean isBinary(HttpServletRequest request, HttpServletResponse response) { String mimeType = response.getContentType(); if (request.getParameterMap().containsKey("binaryOutput")) { return true; } else if (mimeType != null) { if (mimeType.toLowerCase().startsWith("text/")) { return false; } else {//from w ww .jav a 2 s. c om return true; } } else { return true; } }
From source file:fr.openwide.talendalfresco.rest.server.ContentImportCommandServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */// w ww .j a v a2 s .com protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String uri = req.getRequestURI(); if (logger.isDebugEnabled()) logger.debug( "Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "")); AuthenticationStatus status = servletAuthenticate(req, res); if (status == AuthenticationStatus.Failure) { return; } setNoCacheHeaders(res); uri = uri.substring(req.getContextPath().length()); StringTokenizer t = new StringTokenizer(uri, "/"); int tokenCount = t.countTokens(); if (tokenCount < 3) { throw new IllegalArgumentException("Command Servlet URL did not contain all required args: " + uri); } t.nextToken(); // skip servlet name // get the command processor to execute the command e.g. "workflow" String procName = t.nextToken(); // get the command to perform String command = t.nextToken(); // get any remaining uri elements to pass to the processor String[] urlElements = new String[tokenCount - 3]; for (int i = 0; i < tokenCount - 3; i++) { urlElements[i] = t.nextToken(); } // retrieve the URL arguments to pass to the processor Map<String, String> args = new HashMap<String, String>(8, 1.0f); Enumeration names = req.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); args.put(name, req.getParameter(name)); } try { // get configured command processor by name from Config Service CommandProcessor processor = createCommandProcessor(procName); // validate that the processor has everything it needs to run the command if (processor.validateArguments(getServletContext(), command, args, urlElements) == false) { redirectToLoginPage(req, res, getServletContext()); return; } ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); UserTransaction txn = null; try { if (!(processor instanceof RestCommandProcessor) || ((RestCommandProcessor) processor).isTransactional()) { // [talendalfresco] disable tx for ImportCommand txn = serviceRegistry.getTransactionService().getUserTransaction(); txn.begin(); } // inform the processor to execute the specified command if (processor instanceof ExtCommandProcessor) { ((ExtCommandProcessor) processor).process(serviceRegistry, req, res, command); } else { processor.process(serviceRegistry, req, command); } if (!(processor instanceof RestCommandProcessor) || ((RestCommandProcessor) processor).isTransactional()) { // [talendalfresco] disable tx for ImportCommand // commit the transaction txn.commit(); } } catch (Throwable txnErr) { if (!(processor instanceof RestCommandProcessor) || ((RestCommandProcessor) processor).isTransactional()) { // [talendalfresco] disable tx for ImportCommand try { if (txn != null) { txn.rollback(); } } catch (Exception tex) { } } throw txnErr; } String returnPage = req.getParameter(ARG_RETURNPAGE); if (returnPage != null && returnPage.length() != 0) { if (logger.isDebugEnabled()) logger.debug("Redirecting to specified return page: " + returnPage); res.sendRedirect(returnPage); } else { if (logger.isDebugEnabled()) logger.debug("No return page specified, displaying status output."); if (res.getContentType() == null) { res.setContentType("text/html"); } // request that the processor output a useful status message PrintWriter out = res.getWriter(); processor.outputStatus(out); out.close(); } } catch (Throwable err) { throw new AlfrescoRuntimeException("Error during command servlet processing: " + err.getMessage(), err); } }
From source file:photosharing.api.conx.UploadFileDefinition.java
/** * uploads a file to the IBM Connections Cloud using the Files Service * /*from ww w .j a v a 2 s .co m*/ * @param bearer token * @param nonce * @param request * @param response */ public void uploadFile(String bearer, String nonce, HttpServletRequest request, HttpServletResponse response) { // Extracts from the Request Parameters String visibility = request.getParameter("visibility"); String title = request.getParameter("title"); String share = request.getParameter("share"); String tagsUnsplit = request.getParameter("q"); // Check for the Required Parameters if (visibility == null || title == null || title.isEmpty() || visibility.isEmpty()) { response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); } else { /* * Builds the URL Parameters */ StringBuilder builder = new StringBuilder(); builder.append("visibility=" + visibility + "&"); builder.append("title=" + title + "&"); // The Share parameters for the URL if (share != null && !share.isEmpty()) { builder.append("shared=true&"); builder.append("shareWith=" + share + "&"); } if (visibility.compareTo("private") == 0 && share == null) { builder.append("shared=false&"); } // Splits the TagString into Indvidual Tags // - Technically this API is limited to 3 tags at most. String[] tags = tagsUnsplit.split(","); for (String tag : tags) { logger.info("Tag-> " + tag); builder.append("tag=" + tag + "&"); } // Build the apiURL String apiUrl = getApiUrl() + "/myuserlibrary/feed?" + builder.toString(); //API Url logger.info(apiUrl); // Add the Headers String length = request.getHeader("X-Content-Length"); String contentType = request.getHeader("Content-Type"); String fileext = contentType.split("/")[1].split(";")[0]; String slug = title + "." + fileext; Request post = Request.Post(apiUrl); post.addHeader("Authorization", "Bearer " + bearer); post.addHeader("X-Update-Nonce", nonce); post.addHeader("Slug", slug); post.addHeader("Content-Type", contentType); logger.info("Authorization: Bearer " + bearer); logger.info("X-Update-Nonce: " + nonce); logger.info("Slug: " + slug); logger.info("Content-Type: " + contentType); try { // InputStream in = request.getInputStream(); Base64InputStream bis = new Base64InputStream(in); long len = Long.parseLong(length); InputStreamEntity entity = new InputStreamEntity(bis, len); post.body(entity); post.removeHeaders("Cookie"); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(post); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); logger.info("code is " + code); // Session is no longer valid or access token is expired if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Duplicate Item else if (code == HttpStatus.SC_CONFLICT) { response.setStatus(HttpStatus.SC_CONFLICT); } // Checks if Created else if (code == HttpStatus.SC_CREATED) { response.setStatus(HttpStatus.SC_OK); /** * Do Extra Processing Here to process the body */ InputStream inRes = hr.getEntity().getContent(); // Converts XML to JSON String String jsonString = org.apache.wink.json4j.utils.XML.toJson(inRes); JSONObject obj = new JSONObject(jsonString); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); writer.append(obj.toString()); writer.close(); } else { // Catch All response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); InputStream inRes = hr.getEntity().getContent(); String out = IOUtils.toString(inRes); logger.info("Content: " + out); logger.info("Content Type of Response: " + response.getContentType()); Collection<String> coll = response.getHeaderNames(); Iterator<String> iter = coll.iterator(); while (iter.hasNext()) { String header = iter.next(); logger.info(header + " " + response.getHeader(header)); } } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("IOException " + e.toString()); e.printStackTrace(); } catch (SAXException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("SAXException " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("JSONException " + e.toString()); } } }
From source file:net.sourceforge.subsonic.controller.CoverArtControllerEx.java
private void sendFallback(Integer size, HttpServletResponse response) throws IOException { if (response.getContentType() == null) { response.setContentType(StringUtil.getMimeType("png")); }//from www . j av a 2s . c o m InputStream in = null; try { in = getClass().getResourceAsStream("default_cover.png"); BufferedImage image = ImageIO.read(in); if (size != null) { image = scale(image, size, size); } ImageIO.write(image, "png", response.getOutputStream()); } finally { IOUtils.closeQuietly(in); } }
From source file:net.yacy.http.servlets.YaCyDefaultServlet.java
/** * send static content/*www . j a v a 2 s. com*/ * * @param request * @param response * @param include is a include file (send without changing/adding headers) * @param resource the static content * @param reqRanges * @throws IOException */ protected void sendData(HttpServletRequest request, HttpServletResponse response, boolean include, Resource resource, Enumeration<String> reqRanges) throws IOException { final long content_length = resource.length(); // Get the output stream (or writer) OutputStream out; try { out = response.getOutputStream(); } catch (IllegalStateException e) { out = new WriterOutputStream(response.getWriter()); } // remove the last-modified field since caching otherwise does not work /* https://www.ietf.org/rfc/rfc2616.txt "if the response does have a Last-Modified time, the heuristic expiration value SHOULD be no more than some fraction of the interval since that time. A typical setting of this fraction might be 10%." */ if (response.containsHeader(HeaderFramework.LAST_MODIFIED)) { response.getHeaders(HeaderFramework.LAST_MODIFIED).clear(); // if this field is present, the reload-time is a 10% fraction of ttl and other caching headers do not work } // cache-control: allow shared caching (i.e. proxies) and set expires age for cache response.setHeader(HeaderFramework.CACHE_CONTROL, "public, max-age=" + Integer.toString(600)); // seconds; ten minutes if (reqRanges == null || !reqRanges.hasMoreElements() || content_length < 0) { // if there were no ranges, send entire entity if (include) { resource.writeTo(out, 0, content_length); } else { writeHeaders(response, resource, content_length); resource.writeTo(out, 0, content_length); } } else { // Parse the satisfiable ranges List<?> ranges = InclusiveByteRange.satisfiableRanges(reqRanges, content_length); // if there are no satisfiable ranges, send 416 response if (ranges == null || ranges.isEmpty()) { writeHeaders(response, resource, content_length); response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); response.setHeader(HttpHeader.CONTENT_RANGE.asString(), InclusiveByteRange.to416HeaderRangeString(content_length)); resource.writeTo(out, 0, content_length); out.close(); return; } // if there is only a single valid range (must be satisfiable // since were here now), send that range with a 216 response if (ranges.size() == 1) { InclusiveByteRange singleSatisfiableRange = (InclusiveByteRange) ranges.get(0); long singleLength = singleSatisfiableRange.getSize(content_length); writeHeaders(response, resource, singleLength); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); response.setHeader(HttpHeader.CONTENT_RANGE.asString(), singleSatisfiableRange.toHeaderRangeString(content_length)); resource.writeTo(out, singleSatisfiableRange.getFirst(content_length), singleLength); out.close(); return; } // multiple non-overlapping valid ranges cause a multipart // 216 response which does not require an overall // content-length header // writeHeaders(response, resource, -1); String mimetype = response.getContentType(); if (mimetype == null) { ConcurrentLog.warn("FILEHANDLER", "YaCyDefaultServlet: Unknown mimetype for " + request.getRequestURI()); } MultiPartOutputStream multi = new MultiPartOutputStream(out); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // If the request has a "Request-Range" header then we need to // send an old style multipart/x-byteranges Content-Type. This // keeps Netscape and acrobat happy. This is what Apache does. String ctp; if (request.getHeader(HttpHeader.REQUEST_RANGE.asString()) != null) { ctp = "multipart/x-byteranges; boundary="; } else { ctp = "multipart/byteranges; boundary="; } response.setContentType(ctp + multi.getBoundary()); InputStream in = resource.getInputStream(); long pos = 0; // calculate the content-length int length = 0; String[] header = new String[ranges.size()]; for (int i = 0; i < ranges.size(); i++) { InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i); header[i] = ibr.toHeaderRangeString(content_length); length += ((i > 0) ? 2 : 0) + 2 + multi.getBoundary().length() + 2 + (mimetype == null ? 0 : HeaderFramework.CONTENT_TYPE.length() + 2 + mimetype.length()) + 2 + HeaderFramework.CONTENT_RANGE.length() + 2 + header[i].length() + 2 + 2 + (ibr.getLast(content_length) - ibr.getFirst(content_length)) + 1; } length += 2 + 2 + multi.getBoundary().length() + 2 + 2; response.setContentLength(length); for (int i = 0; i < ranges.size(); i++) { InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i); multi.startPart(mimetype, new String[] { HeaderFramework.CONTENT_RANGE + ": " + header[i] }); long start = ibr.getFirst(content_length); long size = ibr.getSize(content_length); if (in != null) { // Handle non cached resource if (start < pos) { in.close(); in = resource.getInputStream(); pos = 0; } if (pos < start) { in.skip(start - pos); pos = start; } FileUtils.copy(in, multi, size); pos += size; } else // Handle cached resource { (resource).writeTo(multi, start, size); } } if (in != null) in.close(); multi.close(); } }
From source file:net.yacy.http.servlets.YaCyDefaultServlet.java
protected void writeHeaders(HttpServletResponse response, Resource resource, long count) { if (response.getContentType() == null) { final String extensionmime; if ((extensionmime = _mimeTypes.getMimeByExtension(resource.getName())) != null) { response.setContentType(extensionmime); }//from w w w . jav a 2s . c o m } /* * DO NOT enable this again, removal of the LAST_MODIFIED field enables caching long lml = resource.lastModified(); if (lml >= 0) { response.setDateHeader(HeaderFramework.LAST_MODIFIED, lml); } */ if (count != -1) { if (count < Integer.MAX_VALUE) { response.setContentLength((int) count); } else { response.setHeader(HeaderFramework.CONTENT_LENGTH, Long.toString(count)); } } if (_acceptRanges) { response.setHeader(HeaderFramework.ACCEPT_RANGES, "bytes"); } }
From source file:nl.openweb.hippo.umd.ui.ResourceServlet.java
private OutputStream selectOutputStream(HttpServletRequest request, HttpServletResponse response) throws IOException { if (gzipEnabled) { String mimeType = response.getContentType(); if (matchesCompressedMimeTypes(mimeType)) { String acceptEncoding = request.getHeader("Accept-Encoding"); if (acceptEncoding != null && acceptEncoding.indexOf("gzip") != -1) { if (LOG.isDebugEnabled()) { LOG.debug("Enabling GZIP compression for the current response."); }/*from ww w . ja v a2 s . co m*/ return new GZIPResponseStream(response); } } } return response.getOutputStream(); }
From source file:org.alfresco.web.app.servlet.CommandServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w. j a va2 s. c om protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String uri = req.getRequestURI(); if (logger.isDebugEnabled()) logger.debug( "Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "")); AuthenticationStatus status = servletAuthenticate(req, res); if (status == AuthenticationStatus.Failure) { return; } setNoCacheHeaders(res); uri = uri.substring(req.getContextPath().length()); StringTokenizer t = new StringTokenizer(uri, "/"); int tokenCount = t.countTokens(); if (tokenCount < 3) { throw new IllegalArgumentException("Command Servlet URL did not contain all required args: " + uri); } t.nextToken(); // skip servlet name // get the command processor to execute the command e.g. "workflow" String procName = t.nextToken(); // get the command to perform String command = t.nextToken(); // get any remaining uri elements to pass to the processor String[] urlElements = new String[tokenCount - 3]; for (int i = 0; i < tokenCount - 3; i++) { urlElements[i] = t.nextToken(); } // retrieve the URL arguments to pass to the processor Map<String, String> args = new HashMap<String, String>(8, 1.0f); Enumeration names = req.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); args.put(name, req.getParameter(name)); } try { // get configured command processor by name from Config Service CommandProcessor processor = createCommandProcessor(procName); // validate that the processor has everything it needs to run the command if (processor.validateArguments(getServletContext(), command, args, urlElements) == false) { redirectToLoginPage(req, res, getServletContext()); return; } ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); UserTransaction txn = null; try { txn = serviceRegistry.getTransactionService().getUserTransaction(); txn.begin(); // inform the processor to execute the specified command if (processor instanceof ExtCommandProcessor) { ((ExtCommandProcessor) processor).process(serviceRegistry, req, res, command); } else { processor.process(serviceRegistry, req, command); } // commit the transaction txn.commit(); } catch (Throwable txnErr) { try { if (txn != null) { txn.rollback(); } } catch (Exception tex) { } throw txnErr; } String returnPage = req.getParameter(ARG_RETURNPAGE); if (returnPage != null && returnPage.length() != 0) { validateReturnPage(returnPage, req); if (logger.isDebugEnabled()) logger.debug("Redirecting to specified return page: " + returnPage); res.sendRedirect(returnPage); } else { if (logger.isDebugEnabled()) logger.debug("No return page specified, displaying status output."); if (res.getContentType() == null && !res.isCommitted()) { res.setContentType("text/html"); // request that the processor output a useful status message PrintWriter out = res.getWriter(); processor.outputStatus(out); out.close(); } } } catch (Throwable err) { throw new AlfrescoRuntimeException("Error during command servlet processing: " + err.getMessage(), err); } }
From source file:org.apache.shindig.gadgets.servlet.MakeRequestHandler.java
/** * Sets cache control headers for the response. *//* w w w . j av a 2s . c om*/ @SuppressWarnings("boxing") protected static void setResponseHeaders(HttpServletRequest request, HttpServletResponse response, HttpResponse results) throws GadgetException { int refreshInterval = 0; if (results.isStrictNoCache() || "1".equals(request.getParameter(UriCommon.Param.NO_CACHE.getKey()))) { refreshInterval = 0; } else if (request.getParameter(UriCommon.Param.REFRESH.getKey()) != null) { try { refreshInterval = Integer.valueOf(request.getParameter(UriCommon.Param.REFRESH.getKey())); } catch (NumberFormatException nfe) { throw new GadgetException(GadgetException.Code.INVALID_PARAMETER, "refresh parameter is not a number", HttpResponse.SC_BAD_REQUEST); } } else { refreshInterval = Math.max(60 * 60, (int) (results.getCacheTtl() / 1000L)); } HttpUtil.setCachingHeaders(response, refreshInterval, false); // Always set Content-Disposition header as XSS prevention mechanism. response.setHeader("Content-Disposition", "attachment;filename=p.txt"); if (response.getContentType() == null) { response.setContentType("application/octet-stream"); } }