List of usage examples for javax.servlet.http HttpServletResponse setIntHeader
public void setIntHeader(String name, int value);
From source file:com.scooter1556.sms.server.service.AdaptiveStreamingService.java
public void sendHLSPlaylist(UUID id, String type, Integer extra, HttpServletRequest request, HttpServletResponse response) throws IOException { // Get the request base URL so we can use it in our playlist String baseUrl = request.getRequestURL().toString().replaceFirst("/stream(.*)", ""); List<String> playlist; // Get playlist as a string array if (type == null) { playlist = generateHLSVariantPlaylist(id, baseUrl); } else {// w w w. j a v a 2 s . c o m playlist = generateHLSPlaylist(id, baseUrl, type, extra); } if (playlist == null) { LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME, "Unable to generate HLS playlist.", null); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to generate HLS playlist."); return; } // Write playlist to buffer so we can get the content length StringWriter playlistWriter = new StringWriter(); for (String line : playlist) { playlistWriter.write(line + "\n"); } // Set Header Parameters response.reset(); response.setContentType("application/x-mpegurl"); response.setContentLength(playlistWriter.toString().length()); // Enable CORS response.setHeader(("Access-Control-Allow-Origin"), "*"); response.setHeader("Access-Control-Allow-Methods", "GET"); response.setIntHeader("Access-Control-Max-Age", 3600); // Write playlist out to the client response.getWriter().write(playlistWriter.toString()); /*********************** DEBUG: Response Headers *********************************/ String requestHeader = "\n***************\nResponse Header:\n***************\n"; Collection<String> responseHeaderNames = response.getHeaderNames(); for (int i = 0; i < responseHeaderNames.size(); i++) { String header = (String) responseHeaderNames.toArray()[i]; String value = response.getHeader(header); requestHeader += header + ": " + value + "\n"; } // Log Headers LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME, requestHeader, null); /********************************************************************************/ // Log playlist LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME, "\n************\nHLS Playlist\n************\n" + playlistWriter.toString(), null); }
From source file:org.apache.karaf.cellar.http.balancer.CellarBalancerProxyServlet.java
protected boolean doResponseRedirectOrNotModifiedLogic(HttpServletRequest servletRequest, HttpServletResponse servletResponse, HttpResponse proxyResponse, int statusCode, String location) throws ServletException, IOException { // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION); if (locationHeader == null) { throw new ServletException("Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION + " header was found in the response"); }/* w w w. ja v a 2s.c o m*/ // Modify the redirect to go to this proxy servlet rather that the proxied host String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue(), location); servletResponse.sendRedirect(locStr); return true; } // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) { servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0); servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; } return false; }
From source file:de.derschimi.proxyservlet.TestServlet.java
protected boolean doResponseRedirectOrNotModifiedLogic(HttpServletRequest servletRequest, HttpServletResponse servletResponse, HttpResponse proxyResponse, int statusCode) throws ServletException, IOException { // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION); if (locationHeader == null) { throw new ServletException("Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION + " header was found in the response"); }// ww w .j a va 2 s . c om // Modify the redirect to go to this proxy servlet rather that the proxied host String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue()); servletResponse.sendRedirect(locStr); return true; } // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) { servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0); servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; } return false; }
From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.java
private boolean doResponseRedirectOrNotModifiedLogic(HttpServletRequest servletRequest, HttpServletResponse servletResponse, HttpResponse proxyResponse, int statusCode) throws ServletException, IOException { // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION); if (locationHeader == null) { throw new ServletException("Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION + " header was found in the response"); }//from w w w . j a va 2 s .c o m // Modify the redirect to go to this proxy servlet rather that the proxied host String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue()); servletResponse.sendRedirect(locStr); return true; } // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) { servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0); servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; } return false; }
From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java
protected boolean doResponseRedirectOrNotModifiedLogic(HttpServletRequest servletRequest, HttpServletResponse servletResponse, HttpResponse proxyResponse, int statusCode) throws ServletException, IOException { // Check if the proxy response is a redirect // The following code is adapted from // org.tigris.noodle.filters.CheckForRedirect if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION); if (locationHeader == null) { throw new ServletException("Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION + " header was found in the response"); }/*from w ww . ja v a 2 s .co m*/ // Modify the redirect to go to this proxy servlet rather that the // proxied host String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue()); servletResponse.sendRedirect(locStr); return true; } // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) { servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0); servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; } return false; }
From source file:grails.plugin.cache.web.filter.PageFragmentCachingFilter.java
/** * Set the headers in the response object, excluding the Gzip header * @param pageInfo/*from www . j a v a2 s .c o m*/ * @param response */ protected void setHeaders(final PageInfo pageInfo, final HttpServletResponse response) { Collection<Header<? extends Serializable>> headers = pageInfo.getHeaders(); // Track which headers have been set so all headers of the same name // after the first are added TreeSet<String> setHeaders = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); for (Header<? extends Serializable> header : headers) { String name = header.getName(); switch (header.getType()) { case STRING: if (setHeaders.contains(name)) { response.addHeader(name, (String) header.getValue()); } else { setHeaders.add(name); response.setHeader(name, (String) header.getValue()); } break; case DATE: if (setHeaders.contains(name)) { response.addDateHeader(name, (Long) header.getValue()); } else { setHeaders.add(name); response.setDateHeader(name, (Long) header.getValue()); } break; case INT: if (setHeaders.contains(name)) { response.addIntHeader(name, (Integer) header.getValue()); } else { setHeaders.add(name); response.setIntHeader(name, (Integer) header.getValue()); } break; default: throw new IllegalArgumentException("No mapping for Header: " + header); } } }
From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java
protected boolean doResponseRedirectOrNotModifiedLogic(HttpServletRequest servletRequest, HttpServletResponse servletResponse, HttpResponse proxyResponse, int statusCode) throws ServletException, IOException { // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* * 300 */ && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* * 304 */) { Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION); if (locationHeader == null) { throw new ServletException("Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION + " header was found in the response"); }/*from w w w. j av a 2 s.co m*/ // Modify the redirect to go to this proxy servlet rather that the proxied host String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue()); servletResponse.sendRedirect(locStr); return true; } // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) { servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0); servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; } return false; }
From source file:com.reachcall.pretty.http.ProxyServlet.java
private void execute(Match match, HttpRequestBase method, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { LOG.log(Level.FINE, "Requesting {0}", method.getURI()); HttpClient client = this.getClient(); HttpResponse response = client.execute(method); for (Header h : response.getHeaders("Set-Cookie")) { String line = parseCookie(h.getValue()); LOG.log(Level.FINER, method.getURI() + "{0}", new Object[] { line }); if (line != null) { LOG.log(Level.INFO, "Bonding session {0} to host {1}", new Object[] { line, match.destination.hostAndPort() }); try { resolver.bond(line, match); } catch (ExecutionException ex) { Logger.getLogger(ProxyServlet.class.getName()).log(Level.SEVERE, null, ex); this.releaseClient(client); throw new ServletException(ex); }//from ww w . j a v a2 s .c o m } } int rc = response.getStatusLine().getStatusCode(); if ((rc >= HttpServletResponse.SC_MULTIPLE_CHOICES) && (rc < HttpServletResponse.SC_NOT_MODIFIED)) { String location = response.getFirstHeader(HEADER_LOCATION).getValue(); if (location == null) { throw new ServletException("Recieved status code: " + rc + " but no " + HEADER_LOCATION + " header was found in the response"); } String hostname = req.getServerName(); if ((req.getServerPort() != 80) && (req.getServerPort() != 443)) { hostname += (":" + req.getServerPort()); } hostname += req.getContextPath(); String replaced = location.replace(match.destination.hostAndPort() + match.path.getDestination(), hostname); if (replaced.startsWith("http://")) { replaced = replaced.replace("http:", req.getScheme() + ":"); } resp.sendRedirect(replaced); this.releaseClient(client); return; } else if (rc == HttpServletResponse.SC_NOT_MODIFIED) { resp.setIntHeader(HEADER_CONTENT_LENTH, 0); resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); this.releaseClient(client); return; } resp.setStatus(rc); Header[] headerArrayResponse = response.getAllHeaders(); for (Header header : headerArrayResponse) { resp.setHeader(header.getName(), header.getValue()); } if (response.getEntity() != null) { resp.setContentLength((int) response.getEntity().getContentLength()); response.getEntity().writeTo(resp.getOutputStream()); } this.releaseClient(client); LOG.finer("Done."); }
From source file:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link javax.servlet.http.HttpServletResponse} * * @param proxyDetails//from www . jav a2 s . c o m * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws java.io.IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { httpMethodProxyRequest.setDoAuthentication(false); httpMethodProxyRequest.setFollowRedirects(false); // Create a default HttpClient HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(stringLocation .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName)); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (!ProxySupport.isHopByHopHeader(header.getName())) { if (ProxySupport.isSetCookieHeader(header)) { HttpProxyRule proxyRule = proxyDetails.getProxyRule(); String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(), proxyRule.getCookiePath(), proxyRule.getCookieDomain()); httpServletResponse.setHeader(header.getName(), setCookie); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } } // check if we got data, that is either the Content-Length > 0 // or the response code != 204 int code = httpMethodProxyRequest.getStatusCode(); boolean noData = code == HttpStatus.SC_NO_CONTENT; if (!noData) { String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME); if (length != null && "0".equals(length.trim())) { noData = true; } } LOG.trace("Response has data? {}", !noData); if (!noData) { // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ((intNextByte = bufferedInputStream.read()) != -1) { outputStreamClientResponse.write(intNextByte); } } }
From source file:net.sourceforge.subsonic.controller.StreamController.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { TransferStatus status = null;/* ww w . ja v a 2 s . co m*/ PlaylistInputStream in = null; Player player = playerService.getPlayer(request, response, false, true); User user = securityService.getUserByName(player.getUsername()); try { if (!user.isStreamRole()) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Streaming is forbidden for user " + user.getUsername()); return null; } // If "playlist" request parameter is set, this is a Podcast request. In that case, create a separate // playlist (in order to support multiple parallel Podcast streams). String playlistName = request.getParameter("playlist"); boolean isPodcast = playlistName != null; if (isPodcast) { Playlist playlist = new Playlist(); playlistService.loadPlaylist(playlist, playlistName); player.setPlaylist(playlist); Util.setContentLength(response, playlist.length()); LOG.info("Incoming Podcast request for playlist " + playlistName); } String contentType = StringUtil.getMimeType(request.getParameter("suffix")); response.setContentType(contentType); String preferredTargetFormat = request.getParameter("format"); Integer maxBitRate = ServletRequestUtils.getIntParameter(request, "maxBitRate"); if (Integer.valueOf(0).equals(maxBitRate)) { maxBitRate = null; } VideoTranscodingSettings videoTranscodingSettings = null; // Is this a request for a single file (typically from the embedded Flash player)? // In that case, create a separate playlist (in order to support multiple parallel streams). // Also, enable partial download (HTTP byte range). MediaFile file = getSingleFile(request); boolean isSingleFile = file != null; LongRange range = null; if (isSingleFile) { Playlist playlist = new Playlist(); playlist.addFiles(true, file); player.setPlaylist(playlist); if (!file.isVideo()) { response.setIntHeader("ETag", file.getId()); response.setHeader("Accept-Ranges", "bytes"); } TranscodingService.Parameters parameters = transcodingService.getParameters(file, player, maxBitRate, preferredTargetFormat, videoTranscodingSettings); long fileLength = getFileLength(parameters); boolean isConversion = parameters.isDownsample() || parameters.isTranscode(); boolean estimateContentLength = ServletRequestUtils.getBooleanParameter(request, "estimateContentLength", false); range = getRange(request, file); if (range != null) { LOG.info("Got range: " + range); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); Util.setContentLength(response, fileLength - range.getMinimumLong()); long firstBytePos = range.getMinimumLong(); long lastBytePos = fileLength - 1; response.setHeader("Content-Range", "bytes " + firstBytePos + "-" + lastBytePos + "/" + fileLength); } else if (!isConversion || estimateContentLength) { Util.setContentLength(response, fileLength); } String transcodedSuffix = transcodingService.getSuffix(player, file, preferredTargetFormat); response.setContentType(StringUtil.getMimeType(transcodedSuffix)); if (file.isVideo()) { videoTranscodingSettings = createVideoTranscodingSettings(file, request); } } if (request.getMethod().equals("HEAD")) { return null; } // Terminate any other streams to this player. if (!isPodcast && !isSingleFile) { for (TransferStatus streamStatus : statusService.getStreamStatusesForPlayer(player)) { if (streamStatus.isActive()) { streamStatus.terminate(); } } } status = statusService.createStreamStatus(player); in = new PlaylistInputStream(player, status, maxBitRate, preferredTargetFormat, videoTranscodingSettings, transcodingService, audioScrobblerService, mediaFileService, searchService); OutputStream out = RangeOutputStream.wrap(response.getOutputStream(), range); // Enabled SHOUTcast, if requested. boolean isShoutCastRequested = "1".equals(request.getHeader("icy-metadata")); if (isShoutCastRequested && !isSingleFile) { response.setHeader("icy-metaint", "" + ShoutCastOutputStream.META_DATA_INTERVAL); response.setHeader("icy-notice1", "This stream is served using Subsonic"); response.setHeader("icy-notice2", "Subsonic - Free media streamer - subsonic.org"); response.setHeader("icy-name", "Subsonic"); response.setHeader("icy-genre", "Mixed"); response.setHeader("icy-url", "http://subsonic.org/"); out = new ShoutCastOutputStream(out, player.getPlaylist(), settingsService); } final int BUFFER_SIZE = 2048; byte[] buf = new byte[BUFFER_SIZE]; while (true) { // Check if stream has been terminated. if (status.terminated()) { return null; } if (player.getPlaylist().getStatus() == Playlist.Status.STOPPED) { if (isPodcast || isSingleFile) { break; } else { sendDummy(buf, out); } } else { int n = in.read(buf); if (n == -1) { if (isPodcast || isSingleFile) { break; } else { sendDummy(buf, out); } } else { out.write(buf, 0, n); } } } } finally { if (status != null) { securityService.updateUserByteCounts(user, status.getBytesTransfered(), 0L, 0L); statusService.removeStreamStatus(status); } IOUtils.closeQuietly(in); } return null; }