Example usage for javax.servlet.http HttpServletResponse addHeader

List of usage examples for javax.servlet.http HttpServletResponse addHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse addHeader.

Prototype

public void addHeader(String name, String value);

Source Link

Document

Adds a response header with the given name and value.

Usage

From source file:uk.ac.ebi.fgpt.lode.servlet.CorsFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    //        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
    // CORS "pre-flight" request
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "GET, POST");
    response.addHeader("Access-Control-Allow-Headers", "Content-Type");
    response.addHeader("Access-Control-Max-Age", "1");// 30 min
    //         }/* w  ww .  j a v  a  2 s .co m*/
    filterChain.doFilter(request, response);
}

From source file:de.appsolve.padelcampus.spring.RedirectInterceptor.java

@Override
public final void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws SystemException {
    String redirectHeader = (String) request.getSession().getAttribute(REDIRECT_HEADER);
    if (!StringUtils.isEmpty(redirectHeader)) {
        response.addHeader(REDIRECT_HEADER, redirectHeader);
        request.getSession().removeAttribute(REDIRECT_HEADER);
    } else if (modelAndView != null) {
        String viewName = null;//from  w  ww  . j  a  va 2  s .co  m
        if (modelAndView.getViewName() != null && modelAndView.getViewName().startsWith(REDIRECT_PREFIX)) {
            viewName = modelAndView.getViewName().substring(REDIRECT_PREFIX.length());
        } else if (modelAndView.getView() != null && modelAndView.getView() instanceof RedirectView) {
            viewName = modelAndView.getViewName();
        }
        if (!StringUtils.isEmpty(viewName)) {
            request.getSession().setAttribute(REDIRECT_HEADER, viewName);
        }
    }
}

From source file:org.apache.cxf.fediz.service.idp.kerberos.KerberosEntryPoint.java

public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex)
        throws IOException, ServletException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Sending back Negotiate Header for request: " + request.getRequestURL());
    }/*w  ww  .  j a v  a 2 s . c  o  m*/
    response.addHeader("WWW-Authenticate", "Negotiate");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.flushBuffer();
}

From source file:agk.chatbot.web.MainServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)/*from   w  ww.jav a2  s .  co m*/
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONObject json = new JSONObject();
    int status;
    response.addHeader("Content-Type", "application/json");
    try {
        status = 200;
        json.put("status", status);
        json.put("result", initialised);
    } catch (JSONException e) {
        status = 500;
        e.printStackTrace();
    }
    response.setStatus(status);
    response.getWriter().print(json.toString());
}

From source file:net.shopxx.filter.AuthenticationFilter.java

@Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse)
        throws Exception {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    if (StringUtils.equalsIgnoreCase(request.getHeader("X-Requested-With"), "XMLHttpRequest")) {
        response.addHeader("loginStatus", "accessDenied");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }//from   ww  w . j ava2s  .  c om
    String loginToken = net.shopxx.util.WebUtils.getCookie(request, Admin.LOGIN_TOKEN_COOKIE_NAME);
    if (!StringUtils.equalsIgnoreCase(loginToken, adminService.getLoginToken())) {
        WebUtils.issueRedirect(request, response, "/");
        return false;
    }
    return super.onAccessDenied(request, response);
}

From source file:ch.silviowangler.dox.web.admin.RepositoryController.java

@RequestMapping(method = GET, value = "/admin/export")
public void getDocument(HttpServletResponse response) {

    try {//  ww w.j a va 2s  .  co  m
        File zipFile = doxExporter.export();

        InputStream in = new FileInputStream(zipFile);

        response.setContentType(this.mimeTypes.getProperty("zip"));

        response.addHeader(CONTENT_DISPOSITION, "attachment; filename=dox-repository.zip");

        byte[] buffer = new byte[1024];
        int bytes;
        while ((bytes = in.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, bytes);
        }
    } catch (IOException e) {
        logger.error("Unable to send dox repository export", e);
        response.setStatus(SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.wxxr.nirvana.json.JSONUtil.java

public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    if (StringUtils.isNotBlank(serializationParams.getSerializedJSON()))
        stringBuilder.append(serializationParams.getSerializedJSON());

    if (StringUtils.isNotBlank(serializationParams.getWrapPrefix()))
        stringBuilder.insert(0, serializationParams.getWrapPrefix());
    else if (serializationParams.isWrapWithComments()) {
        stringBuilder.insert(0, "/* ");
        stringBuilder.append(" */");
    } else if (serializationParams.isPrefix())
        stringBuilder.insert(0, "{}&& ");

    if (StringUtils.isNotBlank(serializationParams.getWrapSuffix()))
        stringBuilder.append(serializationParams.getWrapSuffix());

    String json = stringBuilder.toString();

    if (LOG.isDebugEnabled()) {
        LOG.debug("[JSON]" + json);
    }/*from ww  w  .j a  v  a 2  s  .  c o  m*/

    HttpServletResponse response = serializationParams.getResponse();

    // status or error code
    if (serializationParams.getStatusCode() > 0)
        response.setStatus(serializationParams.getStatusCode());
    else if (serializationParams.getErrorCode() > 0)
        response.sendError(serializationParams.getErrorCode());

    // content type
    response.setContentType(
            serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding());

    if (serializationParams.isNoCache()) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("Pragma", "No-cache");
    }

    if (serializationParams.isGzip()) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes(serializationParams.getEncoding()));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null) {
                out.finish();
                out.close();
            }
        }

    } else {
        response.setContentLength(json.getBytes(serializationParams.getEncoding()).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}

From source file:com.gsr.myschool.server.reporting.bilan.ConvocationReportController.java

@RequestMapping(method = RequestMethod.GET, value = "/convocationReport", produces = "application/pdf")
@ResponseStatus(HttpStatus.OK)/*from w w  w. ja v a 2 s.  co m*/
public void generateExcel(@RequestParam String fileName, HttpServletRequest request,
        HttpServletResponse response) {
    try {
        final int buffersize = 1024;
        final byte[] buffer = new byte[buffersize];

        response.addHeader("Content-Disposition", "attachment; filename=convocation_report.pdf");

        File file = new File(
                request.getSession().getServletContext().getRealPath("/") + TMP_FOLDER_PATH + fileName);
        InputStream inputStream = new FileInputStream(file);
        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

        int available = 0;
        while ((available = inputStream.read(buffer)) >= 0) {
            outputStream.write(buffer, 0, available);
        }

        inputStream.close();

        outputStream.flush();
        outputStream.close();

        file.delete();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.eufar.asmm.server.UploadFunction.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("UploadFunction - the function started");
    response.setContentType("text/html;charset=UTF-8");
    response.addHeader("Cache-Control", "no-cache,no-store");
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {/*from  w  w w.j  a va  2s . co m*/
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();
            org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj;
            if (FilenameUtils.getExtension(item.getName()).matches("(xml|XML)")) {
                if (item.isFormField()) {
                    String name = item.getName();
                    String value = "";
                    if (name.compareTo("textBoxFormElement") == 0) {
                        value = item.getString();
                    } else {
                        value = item.getString();
                    }
                    response.getWriter().write(name + "=" + value + "\n");
                } else {
                    byte[] fileContents = item.get();
                    String message = new String(fileContents);
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(message);
                    System.out.println("UploadFunction - file uploaded");
                }
            } else {
                System.out.println("UploadFunction - file rejected: wrong format");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html");
                response.getWriter().write("format");
            }
        }
    } catch (Exception ex) {
        System.out.println("UploadFunction - a problem occured: " + ex);
        response.getWriter().write("ERROR:" + ex.getMessage());
    }
}

From source file:com.jfinal.weixin.sdk.jfinal.MsgInterceptor.java

public void writeText(HttpServletResponse response, String text) {
    response.setContentType("text/x-json;charset=utf-8");
    response.setHeader("Cache-Control", "no-store, max-age=0, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    try {//from   ww w. j a  va 2  s  .com
        PrintWriter out = response.getWriter();
        out.write(text);
        out.close();
    } catch (IOException e) {
        logger.error("error write json data", e);
    }
}