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:com.feilong.controller.DownloadController.java

public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
    // //w  w  w. j a  v a2 s. c o  m
    String fileName = "Operator.doc".toString(); // ???
    // ?
    InputStream inStream = new FileInputStream("c:/Operator.doc");// 
    // ?
    response.reset();
    response.setContentType("bin");
    response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    // ???
    byte[] b = new byte[100];
    int len;
    try {
        while ((len = inStream.read(b)) > 0)
            response.getOutputStream().write(b, 0, len);
        inStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.mec.Services.JWTService.java

public void addAuthentication(HttpServletResponse res, String username) {
    //System.out.println("TokenAuthenticationService addAuth");
    try {/*w  w w .ja v  a2  s.  com*/
        res.setHeader("Date", DateUtils.formatterTime.format(LocalDateTime.now()));
        Date expires = new Date(System.currentTimeMillis() + EXPIRATIONTIME);
        String token = JWT.create().withSubject(username).withIssuer("MEC").withExpiresAt(expires)
                .sign(algorithm);
        res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + token);
        res.addHeader("Content-Type", "application/json");
        res.setHeader("Expires", DateUtils.formatterTime.format(DateUtils.asLocalDateTime(expires)));
        try {
            JSONObject json = new JSONObject("{\"token\":\"" + token + "\",\"expires\":\""
                    + DateUtils.formatterTime.format(DateUtils.asLocalDateTime(expires)) + "\"}");
            json.write(res.getWriter());
        } catch (JSONException ex) {
            Logger.getLogger(JWTService.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JWTService.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (JWTCreationException exception) {
        System.out.println("JWTCreationException " + exception.toString());
        try {
            JSONObject json = new JSONObject("{\"token\":\"" + exception.toString() + "\"}");
            json.write(res.getWriter());
        } catch (JSONException ex) {
            Logger.getLogger(JWTService.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JWTService.class.getName()).log(Level.SEVERE, null, ex);
        } /*finally{
          throw new JWTCreationException(exception.toString(), exception.getCause());/*finally{
          throw new JWTCreationException(exception.toString(), exception.getCause());
          }*/
    }
}

From source file:org.openmrs.module.hl7query.web.controller.BaseHL7QueryController.java

@ExceptionHandler(APIAuthenticationException.class)
@ResponseBody// w w  w .  j  a v a 2s . co m
public AuthenticationErrorObject apiAuthenticationExceptionHandler(Exception ex, HttpServletResponse response)
        throws Exception {
    if (Context.isAuthenticated()) {
        // user is logged in but doesn't have the relevant privilege -> 403 FORBIDDEN
        errorCode = HttpServletResponse.SC_FORBIDDEN;
        errorDetail = "User is logged in but doesn't have the relevant privilege";
    } else {
        // user is not logged in -> 401 UNAUTHORIZED
        errorCode = HttpServletResponse.SC_UNAUTHORIZED;
        errorDetail = "User is not logged in";
        response.addHeader("WWW-Authenticate", "Basic realm=\"OpenMRS at " + HL7QueryConstants.URI_PREFIX);
    }
    response.setStatus(errorCode);
    return ExceptionUtil.wrapErrorResponse(ex, errorDetail);
}

From source file:fr.xebia.servlet.filter.ExpiresFilterTest.java

@Test
public void testUseDefaultConfiguration2() throws Exception {
    HttpServlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override/*from  ww w .ja  va2 s.  com*/
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("image/jpeg");
            response.addHeader("Cache-Control", "private");

            response.getWriter().print("Hello world");
        }
    };

    int expectedMaxAgeInSeconds = 1 * 60;

    validate(servlet, expectedMaxAgeInSeconds);
}

From source file:nl.surfnet.coin.mock.MockHandler.java

/**
 * @param response/*w w  w  .ja v  a  2s  .  co  m*/
 */
private void addContentHeader(HttpServletResponse response) {
    String contentType;
    String description = responseResource[0].getDescription();
    // poor man's solution, but it works for most Resource implementation
    if (description.contains("json")) {
        contentType = "application/json";
    } else if (description.contains("xml")) {
        contentType = "text/xml";
    } else {
        contentType = "text/html";
    }
    response.addHeader("Content-Type", contentType);

}

From source file:net.groupbuy.interceptor.TokenInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    String token = WebUtils.getCookie(request, TOKEN_COOKIE_NAME);
    if (request.getMethod().equalsIgnoreCase("POST")) {
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
            if (token != null && token.equals(request.getHeader(TOKEN_PARAMETER_NAME))) {
                return true;
            } else {
                response.addHeader("tokenStatus", "accessDenied");
            }//from   ww  w .ja v  a2  s .c  o m
        } else {
            if (token != null && token.equals(request.getParameter(TOKEN_PARAMETER_NAME))) {
                return true;
            }
        }
        if (token == null) {
            token = UUID.randomUUID().toString();
            WebUtils.addCookie(request, response, TOKEN_COOKIE_NAME, token);
        }
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ERROR_MESSAGE);
        return false;
    } else {
        if (token == null) {
            token = UUID.randomUUID().toString();
            WebUtils.addCookie(request, response, TOKEN_COOKIE_NAME, token);
        }
        request.setAttribute(TOKEN_ATTRIBUTE_NAME, token);
        return true;
    }
}

From source file:com.healthcit.analytics.servlet.DataExportServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String token = request.getParameter("token");
    TOKENS_MAP.put(token, DownloadStatus.STARTED);
    String keys = request.getParameter("keys");
    if (keys != null) {
        //JSONArray ownerIdsJSON = (JSONArray)JSONSerializer.toJSON(ownerIds ) ;
        String[] ownerIdsArray = StringUtils.split(keys, ",");

        response.setContentType(Constants.JSON_CONTENT_TYPE);
        response.addHeader(Constants.CONTENT_DISPOSITION, "attachment; filename=dataExport.zip");
        response.addHeader(Constants.PRAGMA_HEADER, Constants.NO_CACHE);

        response.setHeader(Constants.CACHE_CONTROL_HEADER, Constants.NO_CACHE);
        ServletOutputStream os = response.getOutputStream();
        ZipOutputStream zos = new ZipOutputStream(os);
        //         ZipEntry entry = new ZipEntry("dataExport."+OutputFormat.JSON.toString().toLowerCase());
        ZipEntry entry = new ZipEntry("dataExport." + OutputFormat.XML.toString().toLowerCase());
        zos.putNextEntry(entry);//from  w  ww. ja  va2 s  .  c om
        //         OwnerDataManager ownerManager = new OwnerDataManager(OutputFormat.JSON);
        OwnerDataManager ownerManager = new OwnerDataManager(OutputFormat.XML);
        try {
            ownerManager.getEntitiesData(ownerIdsArray, zos);
            TOKENS_MAP.put(token, DownloadStatus.FINISHED);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            TOKENS_MAP.put(token, DownloadStatus.ERROR);
        } finally {
            zos.close();
            //            os.flush();

            //            os.close();
        }
    } else {
        TOKENS_MAP.put(token, DownloadStatus.ERROR);
    }
}

From source file:com.vmware.identity.openidconnect.server.HttpResponse.java

public void applyTo(HttpServletResponse httpServletResponse) throws SerializeException, IOException {
    Validate.notNull(httpServletResponse, "httpServletResponse");

    if (this.cookies != null) {
        for (Cookie cookie : this.cookies) {
            if (cookie != null) {
                httpServletResponse.addCookie(cookie);
            }/*  ww w .java  2s  . c  om*/
        }
    }

    if (this.headers != null) {
        for (Header header : this.headers) {
            if (header != null) {
                httpServletResponse.addHeader(header.getName(), header.getValue());
            }
        }
    }

    if (this.response != null) {
        HTTPResponse nimbusHttpResponse = this.response.toHTTPResponse(); // throws SerializeException
        nimbusHttpResponse.applyTo(httpServletResponse); // throws IOException
    }

    if (this.serverException != null) {
        ErrorObject error = this.serverException.getErrorObject();
        httpServletResponse.sendError(error.getHTTPStatusCode(),
                error.getCode() + ": " + error.getDescription());
    }
}

From source file:com.music.web.MusicController.java

private void setNotCacheable(HttpServletResponse response) {
    response.setHeader("Pragma", "no-cache");
    // HTTP 1.0 header
    response.setDateHeader("Expires", 1L);
    // HTTP 1.1 header: "no-cache" is the standard value,
    // "no-store" is necessary to prevent caching on FireFox.
    response.setHeader("Cache-Control", "no-cache");
    response.addHeader("Cache-Control", "no-store");
}

From source file:fr.xebia.servlet.filter.ExpiresFilterTest.java

@Test
public void testSkipBecauseCacheControlMaxAgeIsDefined() throws Exception {
    HttpServlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override/*from   www  .  ja  v a 2  s . c o m*/
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/xml; charset=utf-8");
            response.addHeader("Cache-Control", "private, max-age=232");
            response.getWriter().print("Hello world");
        }
    };

    int expectedMaxAgeInSeconds = 232;
    validate(servlet, expectedMaxAgeInSeconds);
}