Java Code Examples for javax.servlet.http.HttpServletResponse#setIntHeader()

The following examples show how to use javax.servlet.http.HttpServletResponse#setIntHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResponseHeaderIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    response.setHeader("One", "abc");
    response.setHeader("one", "ab");
    response.addHeader("one", "xy");
    response.setHeader("Two", "1");
    response.setHeader("Three", "xyz");

    response.setDateHeader("Date-One", 1393553211832L);
    response.setDateHeader("Date-one", 1393553212832L);
    response.addDateHeader("Date-one", 1393553213832L);
    response.setDateHeader("Date-Two", 1393553214832L);
    response.setDateHeader("Date-Thr", 1393553215832L);
    response.addDateHeader("Date-Four", 1393553215832L);

    response.setIntHeader("Int-One", 1);
    response.setIntHeader("Int-one", 2);
    response.addIntHeader("Int-one", 3);
    response.setIntHeader("Int-Two", 4);
    response.setIntHeader("Int-Thr", 5);
    response.addIntHeader("Int-Four", 6);

    response.addHeader("X-One", "xy");
    response.addDateHeader("X-one", 1393553216832L);
    response.addIntHeader("X-one", 6);
}
 
Example 2
Source File: HttpUtils.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static void addSecurityHeaders(final HttpServletResponse resp) {
    if (resp.containsHeader("X-Content-Type-Options")) {
        resp.setHeader("X-Content-Type-Options", "nosniff");
    }
    else {
        resp.addHeader("X-Content-Type-Options", "nosniff");
    }
    if (resp.containsHeader("X-XSS-Protection")) {
        resp.setHeader("X-XSS-Protection", "1;mode=block");
    }
    else {
        resp.addHeader("X-XSS-Protection", "1;mode=block");
    }

    if (resp.containsHeader("content-security-policy")) {
        resp.setIntHeader("content-security-policy", 1);
    }else {
        resp.addIntHeader("content-security-policy", 1);
    }
    resp.addHeader("content-security-policy","default-src=none");
    resp.addHeader("content-security-policy","script-src=self");
    resp.addHeader("content-security-policy","connect-src=self");
    resp.addHeader("content-security-policy","img-src=self");
    resp.addHeader("content-security-policy","style-src=self");
}
 
Example 3
Source File: ServletUtils.java    From yue-library with Apache License 2.0 5 votes vote down vote up
/**
 * 设置响应的Header
 * 
 * @param name 名
 * @param value 值,可以是String,Date, int
 */
public static void setHeader(String name, Object value) {
	HttpServletResponse response = getResponse();
	if (value instanceof String) {
		response.setHeader(name, (String) value);
	} else if (Date.class.isAssignableFrom(value.getClass())) {
		response.setDateHeader(name, ((Date) value).getTime());
	} else if (value instanceof Integer || "int".equals(value.getClass().getSimpleName().toLowerCase())) {
		response.setIntHeader(name, (int) value);
	} else {
		response.setHeader(name, value.toString());
	}
}
 
Example 4
Source File: QueryServlet.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  resp.setContentType("text/html;charset=utf-8");
  req.setCharacterEncoding("utf-8");
  resp.setStatus(HttpServletResponse.SC_OK);
  resp.setIntHeader("refresh", 300);
  PrintWriter out = resp.getWriter();
  out.print(page.render());
  out.flush();
  out.close();
}
 
Example 5
Source File: HttpProxy.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
private boolean doResponseRedirectOrNotModifiedLogic(HttpProxyContext proxyContext,
                                                     HttpResponse proxyResponse,
                                                     int statusCode) throws ServletException, IOException {
    HttpServletResponse servletResponse = proxyContext.getResponse();
    // 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");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String locStr = rewriteUrlFromResponse(proxyContext, 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;
}
 
Example 6
Source File: ProxyServlet.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
protected void forwardResponse(final Routes.Route route, final Response response,
                               final HttpServletRequest request, final HttpServletResponse resp,
                               final Function<InputStream, InputStream> responseRewriter) throws IOException {
    final int status = response.getStatus();
    resp.setStatus(status);
    forwardHeaders(route, response, resp);
    if (status == HttpServletResponse.SC_NOT_MODIFIED && resp.getHeader(HttpHeaders.CONTENT_LENGTH) == null) {
        resp.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
    }
    forwardCookies(route, response, resp);
    writeOutput(resp, responseRewriter.apply(response.readEntity(InputStream.class)));
}
 
Example 7
Source File: AbstractView.java    From ymate-platform-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public IView addIntHeader(String name, int value) {
    HttpServletResponse _response = WebContext.getResponse();
    if (_response.containsHeader(name)) {
        _response.addIntHeader(name, value);
    } else {
        _response.setIntHeader(name, value);
    }
    return this;
}
 
Example 8
Source File: WebUtils.java    From ymate-platform-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * @param response    HttpServletResponse对象
 * @param templateUrl JSP等模板文件URL
 * @param time        间隔时间
 * @param url         页面URL地址,空为当前页面
 * @return 通过设置Header的Refresh属性执行页面刷新或跳转,若url参数为空,则仅向Header添加time时间后自动刷新当前页面
 */
public static String doRedirectHeaderRefresh(HttpServletResponse response, String templateUrl, int time, String url) {
    if (StringUtils.isBlank(url)) {
        response.setIntHeader("REFRESH", time);
    } else {
        String _content = time + ";URL=" + url;
        response.setHeader("REFRESH", _content);
    }
    return templateUrl;
}
 
Example 9
Source File: MockServlet.java    From soabase with Apache License 2.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    String responseStr = "hello";
    response.setIntHeader("Content-Length", responseStr.length());
    response.getOutputStream().print(responseStr);
}
 
Example 10
Source File: ApiProxyServlet.java    From onboard with Apache License 2.0 5 votes vote down vote up
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");
        }
        // 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;
}
 
Example 11
Source File: ProxyServlet.java    From aem-solr-search with Apache License 2.0 5 votes vote down vote up
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");
        }
        // 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;
}
 
Example 12
Source File: WXPayPrecreateController.java    From springboot-pay-example with Apache License 2.0 4 votes vote down vote up
/**
 * 扫码支付 - 统一下单
 * 相当于支付不的电脑网站支付
 *
 * <a href="https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1">扫码支付API</a>
 */
@PostMapping("/order")
public void precreate(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, String> reqData = new HashMap<>();
    reqData.put("out_trade_no", String.valueOf(System.nanoTime()));
    reqData.put("trade_type", "NATIVE");
    reqData.put("product_id", "1");
    reqData.put("body", "商户下单");
    // 订单总金额,单位为分
    reqData.put("total_fee", "2");
    // APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。
    reqData.put("spbill_create_ip", "14.23.150.211");
    // 异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。
    reqData.put("notify_url", "http://3sbqi7.natappfree.cc/wxpay/precreate/notify");
    // 自定义参数, 可以为终端设备号(门店号或收银设备ID),PC网页或公众号内支付可以传"WEB"
    reqData.put("device_info", "");
    // 附加数据,在查询API和支付通知中原样返回,可作为自定义参数使用。
    reqData.put("attach", "");

    /**
     * {
     * code_url=weixin://wxpay/bizpayurl?pr=vvz4xwC,
     * trade_type=NATIVE,
     * return_msg=OK,
     * result_code=SUCCESS,
     * return_code=SUCCESS,
     * prepay_id=wx18111952823301d9fa53ab8e1414642725
     * }
     */
    Map<String, String> responseMap = wxPay.unifiedOrder(reqData);
    log.info(responseMap.toString());
    String returnCode = responseMap.get("return_code");
    String resultCode = responseMap.get("result_code");
    if (WXPayConstants.SUCCESS.equals(returnCode) && WXPayConstants.SUCCESS.equals(resultCode)) {
        String prepayId = responseMap.get("prepay_id");
        String codeUrl = responseMap.get("code_url");

        BufferedImage image = PayUtil.getQRCodeImge(codeUrl);

        response.setContentType("image/jpeg");
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setIntHeader("Expires",-1);
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

}
 
Example 13
Source File: DownloadController.java    From airsonic with GNU General Public License v3.0 4 votes vote down vote up
@GetMapping
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

    User user = securityService.getCurrentUser(request);
    TransferStatus status = null;
    try {

        status = statusService.createDownloadStatus(playerService.getPlayer(request, response, false, false));

        MediaFile mediaFile = getMediaFile(request);

        Integer playlistId = ServletRequestUtils.getIntParameter(request, "playlist");
        Integer playerId = ServletRequestUtils.getIntParameter(request, "player");
        int[] indexes = request.getParameter("i") == null ? null : ServletRequestUtils.getIntParameters(request, "i");

        if (mediaFile != null) {
            response.setIntHeader("ETag", mediaFile.getId());
            response.setHeader("Accept-Ranges", "bytes");
        }

        HttpRange range = HttpRange.valueOf(request.getHeader("Range"));
        if (range != null) {
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            LOG.info("Got HTTP range: " + range);
        }

        if (mediaFile != null) {
            if (!securityService.isFolderAccessAllowed(mediaFile, user.getUsername())) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN,
                        "Access to file " + mediaFile.getId() + " is forbidden for user " + user.getUsername());
                return;
            }

            if (mediaFile.isFile()) {
                downloadFile(response, status, mediaFile.getFile(), range);
            } else {
                List<MediaFile> children = mediaFileService.getChildrenOf(mediaFile, true, false, true);
                String zipFileName = FilenameUtils.getBaseName(mediaFile.getPath()) + ".zip";
                File coverArtFile = indexes == null ? mediaFile.getCoverArtFile() : null;
                downloadFiles(response, status, children, indexes, coverArtFile, range, zipFileName);
            }

        } else if (playlistId != null) {
            List<MediaFile> songs = playlistService.getFilesInPlaylist(playlistId);
            Playlist playlist = playlistService.getPlaylist(playlistId);
            downloadFiles(response, status, songs, null, null, range, playlist.getName() + ".zip");

        } else if (playerId != null) {
            Player player = playerService.getPlayerById(playerId);
            PlayQueue playQueue = player.getPlayQueue();
            playQueue.setName("Playlist");
            downloadFiles(response, status, playQueue.getFiles(), indexes, null, range, "download.zip");
        }

    } finally {
        if (status != null) {
            statusService.removeDownloadStatus(status);
            securityService.updateUserByteCounts(user, 0L, status.getBytesTransfered(), 0L);
        }
    }
}
 
Example 14
Source File: DownloadController.java    From subsonic with GNU General Public License v3.0 4 votes vote down vote up
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

        User user = securityService.getCurrentUser(request);
        TransferStatus status = null;
        try {

            status = statusService.createDownloadStatus(playerService.getPlayer(request, response, false, false));

            MediaFile mediaFile = getMediaFile(request);

            Integer playlistId = ServletRequestUtils.getIntParameter(request, "playlist");
            String playerId = request.getParameter("player");
            int[] indexes = request.getParameter("i") == null ? null : ServletRequestUtils.getIntParameters(request, "i");

            if (mediaFile != null) {
                response.setIntHeader("ETag", mediaFile.getId());
                response.setHeader("Accept-Ranges", "bytes");
            }

            HttpRange range = HttpRange.valueOf(request.getHeader("Range"));
            if (range != null) {
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                LOG.info("Got HTTP range: " + range);
            }

            if (mediaFile != null) {
                if (!securityService.isFolderAccessAllowed(mediaFile, user.getUsername())) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN,
                                       "Access to file " + mediaFile.getId() + " is forbidden for user " + user.getUsername());
                    return null;
                }

                if (mediaFile.isFile()) {
                    downloadFile(response, status, mediaFile.getFile(), range);
                } else {
                    List<MediaFile> children = mediaFileService.getChildrenOf(mediaFile, true, false, true);
                    String zipFileName = FilenameUtils.getBaseName(mediaFile.getPath()) + ".zip";
                    File coverArtFile = indexes == null ? mediaFile.getCoverArtFile() : null;
                    downloadFiles(response, status, children, indexes, coverArtFile, range, zipFileName);
                }

            } else if (playlistId != null) {
                List<MediaFile> songs = playlistService.getFilesInPlaylist(playlistId);
                Playlist playlist = playlistService.getPlaylist(playlistId);
                downloadFiles(response, status, songs, null, null, range, playlist.getName() + ".zip");

            } else if (playerId != null) {
                Player player = playerService.getPlayerById(playerId);
                PlayQueue playQueue = player.getPlayQueue();
                playQueue.setName("Playlist");
                downloadFiles(response, status, playQueue.getFiles(), indexes, null, range, "download.zip");
            }

        } finally {
            if (status != null) {
                statusService.removeDownloadStatus(status);
                securityService.updateUserByteCounts(user, 0L, status.getBytesTransfered(), 0L);
            }
        }

        return null;
    }
 
Example 15
Source File: FileDownloadController.java    From cuba with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserSession userSession = getSession(request, response);
    if (userSession == null)
        return;

    AppContext.setSecurityContext(new SecurityContext(userSession));
    try {
        File file = null;
        FileDescriptor fd = null;
        if (request.getParameter("p") != null)
            file = getFile(request, response);
        else
            fd = getFileDescriptor(request, response);
        if (fd == null && file == null)
            return;

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setIntHeader("Expires", -1);
        response.setHeader("Content-Type", FileTypesHelper.DEFAULT_MIME_TYPE);

        InputStream is = null;
        ServletOutputStream os = null;
        try {
            is = fd != null ? fileStorage.openStream(fd) : FileUtils.openInputStream(file);
            os = response.getOutputStream();
            IOUtils.copy(is, os);
            os.flush();
        } catch (FileStorageException e) {
            log.error("Unable to download file", e);
            response.sendError(e.getType().getHttpStatus());
        } catch (Exception ex) {
            log.error("Unable to download file", ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    } finally {
        AppContext.setSecurityContext(null);
    }
}