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.phenotype.web.proxy.ExternalUrlConfiguratbleProxyServlet.java

/** Copy proxied response headers back to the servlet client. */
protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletResponse servletResponse) {
    for (Header header : proxyResponse.getAllHeaders()) {
        //remove transfer encoding as for gbrowse png this is set and stops the browser pulling back the whole image get a Error 321 (net::ERR_INVALID_CHUNKED_ENCODING): Unknown error.
        if (!"Transfer-Encoding".equals(header.getName())) {
            servletResponse.addHeader(header.getName(), header.getValue());

        }// w  w  w. j  a  v  a 2s.c  o  m
    }
}

From source file:com.cloud.bridge.service.controller.s3.S3ObjectAction.java

public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String method = request.getMethod();
    String queryString = request.getQueryString();

    response.addHeader("x-amz-request-id", UUID.randomUUID().toString());

    if (method.equalsIgnoreCase("GET")) {

        if (queryString != null && queryString.length() > 0) {
            if (queryString.equalsIgnoreCase("acl"))
                executeGetObjectAcl(request, response);
        } else/*  ww  w. jav  a2  s  .c o  m*/
            executeGetObject(request, response);
    } else if (method.equalsIgnoreCase("PUT")) {

        if (queryString != null && queryString.length() > 0) {
            if (queryString.equalsIgnoreCase("acl"))
                executePutObjectAcl(request, response);
        } else
            executePutObject(request, response);
    } else if (method.equalsIgnoreCase("DELETE")) {
        executeDeleteObject(request, response);
    } else if (method.equalsIgnoreCase("HEAD")) {
        executeHeadObject(request, response);
    } else if (method.equalsIgnoreCase("POST")) {
        executePostObject(request, response);
    } else
        throw new IllegalArgumentException("Unsupported method in REST request");
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.controllers.BasicAuthenticationRESTController.java

/**
 * Authenticates an user. Requires basic authentication header.
 * @param httpServletRequest//w  ww. j a  va2 s .co  m
 * @param httpServletResponse
 * @return
 * @throws Exception
 */
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("login")
public Response login(@Context HttpServletRequest httpServletRequest,
        @Context HttpServletResponse httpServletResponse) throws Exception {

    String[] userNameAndPassword;

    // Invalidate session if exists
    HttpSession httpSession = httpServletRequest.getSession(false);
    if (httpSession != null)
        httpSession.invalidate();

    authenticationServiceFacade = (AuthenticationServiceFacade) applicationContext
            .getBean(AUTHENTICATION_SERVICE_NAME);

    try {
        userNameAndPassword = obtainUserAndPasswordFromBasicAuthenticationHeader(httpServletRequest);
    } catch (BadCredentialsException e) {
        httpServletResponse.addHeader("WWW-Authenticate", "Basic");
        return Response.status(Response.Status.UNAUTHORIZED).entity(new AuthorizationDataVO()).build();
    }

    //Create and set the cookie
    httpServletRequest.getSession(true);
    String jsessionId = httpServletRequest.getSession().getId();
    Cookie sessionIdCookie = new Cookie("JSESSIONID", jsessionId);
    httpServletResponse.addCookie(sessionIdCookie);

    // Obtain XSRFToken and add it as a response header
    String xsrfToken = SecurityHelper.createXSRFToken(httpServletRequest);
    httpServletResponse.addHeader(SecurityHelper.XSRF_TOKEN_NAME, xsrfToken);

    // Authenticate principal and return authorization data
    AuthorizationDataVO authData = authenticationServiceFacade.authenticatePrincipal(userNameAndPassword[0],
            userNameAndPassword[1]);

    // AuthorizationDataVO
    return Response.status(Response.Status.OK).entity(authData).build();
}

From source file:com.cloudbees.tomcat.valves.PrivateAppValveIntegratedTest.java

@Before
@Override//w  w  w .ja  v  a2s . com
public void setUp() throws Exception {
    super.setUp();

    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    org.apache.catalina.Context context = tomcat.addContext("", System.getProperty("java.io.tmpdir"));

    Tomcat.addServlet(context, "hello-servlet", new HttpServlet() {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            System.out.println(req.getRequestURL());
            IoUtils2.flush(req.getInputStream(), System.out);
            Enumeration<String> headers = req.getHeaderNames();
            while (headers.hasMoreElements()) {
                String header = headers.nextElement();
                System.out.println("   " + header + ": " + req.getHeader(header));
            }
            resp.addHeader("x-response", "hello");
            resp.getWriter().println("Hello world!");
        }
    });
    context.addServletMapping("/*", "hello-servlet");

    privateAppValve = new PrivateAppValve();
    privateAppValve.setSecretKey(secretKey);

    context.getPipeline().addValve(privateAppValve);

    tomcat.start();

    httpClient = new DefaultHttpClient();
    httpHost = new HttpHost("localhost", getPort());
}

From source file:at.gv.egovernment.moa.id.auth.servlet.AuthServlet.java

/**
 * Set response headers to avoid caching
 * //from  w ww. j  a  v a2  s .co  m
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 */
protected void setNoCachingHeadersInHttpRespone(HttpServletRequest request, HttpServletResponse response) {
    response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
    response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
    response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
    response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,
            MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);

}

From source file:jp.terasoluna.fw.web.struts.actions.FileDownloadUtil.java

/**
 * uEU_E??[h?B/*  w  w w . j  a v  a  2s . c  om*/
 * @param downloadObject _E??[h??B
 * @param request NGXg?B
 * @param response X|X?B
 *
 * @throws IOException _E??[h?oO????B
 */
public static void download(AbstractDownloadObject downloadObject, HttpServletRequest request,
        HttpServletResponse response, boolean forceDownload) throws IOException {

    // downloadObjectnull???A??
    if (downloadObject == null) {
        if (log.isWarnEnabled()) {
            log.warn("No download object.");
        }
        return;
    }

    // wb_??B
    Map<String, List<String>> additionalHeaders = downloadObject.getAdditionalHeaders();

    // wb_?null???A??
    if (additionalHeaders == null) {
        if (log.isWarnEnabled()) {
            log.warn("Header must not be null.");
        }
        return;
    }

    // wb_??B
    Set<Entry<String, List<String>>> entrySet = additionalHeaders.entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        String headerName = entry.getKey();
        List<String> headerValues = entry.getValue();

        // wb_?L?[lXgnull???A??
        if (headerValues == null || headerName == null) {
            if (log.isWarnEnabled()) {
                log.warn("Header name and value must not be null.");
            }
            return;
        }
        for (String headerValue : headerValues) {
            // wb_?lnull
            if (headerValue == null) {
                headerValue = "";
            }
            response.addHeader(headerName, headerValue);
        }
    }

    // GR?[fBO?
    String charSet = downloadObject.getCharset();
    if (StringUtils.isNotEmpty(charSet)) {
        response.setCharacterEncoding(downloadObject.getCharset());
    }

    // Reg^Cv?
    String contentType = downloadObject.getContentType();
    if (StringUtils.isNotEmpty(contentType)) {
        response.setContentType(downloadObject.getContentType());
    }

    // f?[^TCY?
    int contentLength = downloadObject.getLengthOfData();
    if (contentLength > 0) {
        response.setContentLength(downloadObject.getLengthOfData());
    }

    // t@C????A??B
    // ?????B
    String name = downloadObject.getName();
    if (name != null) {
        name = encoder.encode(name, request, response);
    } else {
        name = encoder.encode("", request, response);
    }
    setFileName(response, name, forceDownload);

    InputStream inputStream = downloadObject.getStream();
    OutputStream outputStream = null;

    try {
        // _E??[h???s
        outputStream = response.getOutputStream();
        Streams.copy(inputStream, outputStream, false);
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.flush();
            outputStream.close();
        }
    }

}

From source file:com.erudika.scoold.utils.ScooldUtils.java

public void setSecurityHeaders(HttpServletRequest request, HttpServletResponse response) {
    // CSP Header
    if (Config.getConfigBoolean("csp_header_enabled", true)) {
        response.addHeader("Content-Security-Policy",
                Config.getConfigParam("csp_header", getDefaultContentSecurityPolicy(request.isSecure())));
    }// w ww  .ja va 2s.co m
    // HSTS Header
    if (Config.getConfigBoolean("hsts_header_enabled", true)) {
        response.addHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
    }
    // Frame Options Header
    if (Config.getConfigBoolean("framing_header_enabled", true)) {
        response.addHeader("X-Frame-Options", "SAMEORIGIN");
    }
    // XSS Header
    if (Config.getConfigBoolean("xss_header_enabled", true)) {
        response.addHeader("X-XSS-Protection", "1; mode=block");
    }
    // Content Type Header
    if (Config.getConfigBoolean("contenttype_header_enabled", true)) {
        response.addHeader("X-Content-Type-Options", "nosniff");
    }
    // Referrer Header
    if (Config.getConfigBoolean("referrer_header_enabled", true)) {
        response.addHeader("Referrer-Policy", "strict-origin");
    }
}

From source file:com.ucap.uccc.cmis.impl.atompub.CmisAtomPubServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    CallContext context = null;/*from w  w w  . j  a v  a2 s. co m*/
    try {
        if (METHOD_HEAD.equals(request.getMethod())) {
            request = new HEADHttpServletRequestWrapper(request);
            response = new NoBodyHttpServletResponseWrapper(response);
        } else {
            request = new QueryStringHttpServletRequestWrapper(request);
        }

        // set default headers
        response.addHeader("Cache-Control", "private, max-age=0");
        response.addHeader("Server", ServerVersion.OPENCMIS_SERVER);

        context = createContext(getServletContext(), request, response);
        dispatch(context, request, response);
    } catch (Exception e) {
        if (e instanceof CmisUnauthorizedException) {
            response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
        } else if (e instanceof CmisPermissionDeniedException) {
            if ((context == null) || (context.getUsername() == null)) {
                response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\"");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
            } else {
                response.sendError(getErrorCode((CmisPermissionDeniedException) e), e.getMessage());
            }
        } else {
            printError(e, response);
        }
    } finally {
        // we are done.
        response.flushBuffer();
    }
}

From source file:com.cloudbees.servlet.filters.PrivateAppFilterIntegratedTest.java

@Before
@Override/* w ww . j a  va 2  s .c  om*/
public void setUp() throws Exception {
    super.setUp();

    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    org.apache.catalina.Context context = tomcat.addContext("", System.getProperty("java.io.tmpdir"));

    privateAppFilter = new PrivateAppFilter();
    privateAppFilter.setSecretKey(secretKey);
    privateAppFilter.setEnabled(true);

    FilterDef filterDef = new FilterDef();
    filterDef.setFilter(privateAppFilter);
    filterDef.setFilterName(PrivateAppFilter.class.getName());
    context.addFilterDef(filterDef);

    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(PrivateAppFilter.class.getName());
    filterMap.addURLPattern("*");
    context.addFilterMap(filterMap);

    context.addFilterDef(filterDef);

    Tomcat.addServlet(context, "hello-servlet", new HttpServlet() {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            System.out.println(req.getRequestURL());
            IoUtils2.flush(req.getInputStream(), System.out);
            Enumeration<String> headers = req.getHeaderNames();
            while (headers.hasMoreElements()) {
                String header = headers.nextElement();
                System.out.println("   " + header + ": " + req.getHeader(header));
            }
            resp.addHeader("x-response", "hello");
            resp.getWriter().println("Hello world!");
        }
    });
    context.addServletMapping("/*", "hello-servlet");

    tomcat.start();

    httpClient = new DefaultHttpClient();
    httpHost = new HttpHost("localhost", getPort());
}