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:net.shopxx.interceptor.ValidateInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    if (!isValid(request)) {
        String requestType = request.getHeader("X-Requested-With");
        if (StringUtils.equalsIgnoreCase(requestType, "XMLHttpRequest")) {
            response.addHeader("validateStatus", "accessDenied");
        }/* ww w . ja v a2s  . c om*/
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ERROR_MESSAGE);
        return false;
    }
    return true;
}

From source file:net.officefloor.plugin.servlet.container.integrate.HttpServletIntegrateTest.java

/**
 * Ensure can {@link HttpServlet} can service a simple {@link HttpRequest}.
 *///  w  w w  . ja  va  2 s  .c o m
public void testSimpleRequest() throws Exception {

    // Specify servicing
    setServicing(new Servicer() {
        @Override
        public String service(HttpServlet servlet, HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            resp.addHeader("test", "value");
            return "Hello World";
        }
    });

    // Send request
    HttpClient client = this.createHttpClient();
    HttpGet request = new HttpGet(this.getServerUrl());
    HttpResponse response = client.execute(request);

    // Validate the response
    assertHttpResponse(response, 200, "Hello World", "test", "value");
}

From source file:alpine.filters.ContentSecurityPolicyFilter.java

@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {
    final HttpServletResponse response = (HttpServletResponse) res;
    chain.doFilter(req, response);/*w  w w  .j a va 2  s.com*/
    response.addHeader("Content-Security-Policy", policy);
}

From source file:de.mpg.escidoc.services.pidcache.web.MainServlet.java

private boolean authenticate(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String auth = request.getHeader("authorization");
    if (auth == null) {
        response.addHeader("WWW-Authenticate", "Basic realm=\"PID Cache\"");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    } else {//from   ww  w. j a  va  2  s  . c  o m
        auth = auth.substring(6);
        String cred = new String(Base64.decodeBase64(auth.getBytes()));
        if (cred.contains(":")) {

            String[] userPass = cred.split(":");
            String userName = PropertyReader.getProperty("escidoc.pidcache.user.name");
            String password = PropertyReader.getProperty("escidoc.pidcache.user.password");

            if (!userPass[0].equals(userName) || !userPass[1].equals(password)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return false;
            } else {
                return true;
            }
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
    }
}

From source file:eu.rethink.lhcb.broker.servlet.WellKnownServlet.java

private void handleRequest(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    // add header for cross domain stuff
    resp.addHeader("Access-Control-Allow-Origin", "*");
    String host = req.getHeader("X-Forwarded-Host");
    if (host == null)
        host = req.getHeader("Host");

    // setting external host here helps BrokerWebSocketListener to return info about HTTP interface
    // Broker might not know how it is accessible. This is a workaround for it
    LHCBBroker.externalHost = host;//from w ww  . j  a  va  2  s  . c  o m
    final AsyncContext asyncContext = req.startAsync();
    asyncContext.start(() -> {
        ServletRequest aReq = asyncContext.getRequest();
        String payload = null;
        try {
            payload = IOUtils.toString(aReq.getReader());
        } catch (IOException e) {
            e.printStackTrace();
        }

        String finalPayload = payload;

        Map<String, String[]> params = aReq.getParameterMap();
        LOG.debug("payload: {}\r\nparams: {}", payload, params);

        RequestCallback cb = new RequestCallback() {

            @Override
            public void response(Message msg) {
                resp.setStatus(HttpServletResponse.SC_OK);
                try {
                    asyncContext.getResponse().getWriter().write(msg.toString());
                    asyncContext.getResponse().getWriter().flush();
                    asyncContext.complete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(Exception e) {
                String error = "Request failed.\r\npayload: " + finalPayload + "\r\nparams: " + params;
                LOG.error(error + "\r\nreason: " + e.getLocalizedMessage(),
                        e instanceof InvalidMessageException ? null : e);
                if (e instanceof InvalidMessageException) {
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                } else {
                    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

                }
                completeAsyncContext(asyncContext, error + "\r\nreason: " + e.getLocalizedMessage());
            }
        };

        try {
            Message msg = null;

            if (payload.length() > 0) {
                msg = Message.fromString(payload);
            } else {
                msg = Message.fromParams(params);
            }

            requestHandler.handleRequest(msg, cb);
        } catch (InvalidMessageException e) {
            cb.error(e);
        }
    });
}

From source file:org.appverse.web.framework.backend.frontfacade.json.controllers.JSONController.java

private void addDefaultResponseHeaders(HttpServletResponse response) {
    // Add headers to prevent Cross-site ajax calls issues
    response.addHeader("Content-Type", "application/json; charset=UTF-8");
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
}

From source file:be.dnsbelgium.rdap.DomainController.java

@ExceptionHandler(value = RDAPError.NotAuthoritative.class)
@ResponseBody/*from  ww w  . j a  v a 2 s  . c o m*/
protected RDAPError handleResourceNotFoundException(RDAPError.NotAuthoritative error,
        HttpServletResponse response) throws UnsupportedEncodingException {
    response.setStatus(error.getErrorCode());
    String location = baseRedirectURL + "/domain/" + URLEncoder.encode(error.getDomainName(), "UTF-8");
    response.addHeader(Controllers.LOCATION_HEADER, location);
    return error;
}

From source file:com.indoqa.httpproxy.HttpClientProxy.java

private void writeResponseHeaders(HttpServletResponse response, HttpResponse proxyResponse) {
    for (Header header : proxyResponse.getAllHeaders()) {
        response.addHeader(header.getName(), header.getValue());
    }/* w  w  w .java2 s.c  o m*/
}

From source file:com.hmsinc.epicenter.webapp.map.MapStylingController.java

@Transactional(readOnly = true)
@RequestMapping("/map-style")
public void handleMapStyleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final StyleParameters styleParameters = parse(request);

    response.setContentType(SLD_CONTENT_TYPE);
    response.addHeader("cache-control", "must-revalidate");

    styleBuilder.build(response.getOutputStream(), styleParameters);

}

From source file:com.conwet.silbops.connectors.comet.CometAPIHandler.java

@Override
public void onRequest(AtmosphereResource<HttpServletRequest, HttpServletResponse> event) throws IOException {

    HttpServletRequest req = event.getRequest();
    HttpServletResponse res = event.getResponse();

    res.addHeader("Cache-Control", "max-age=0, no-cache, must-revalidate");
    res.addHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT");

    String method = req.getMethod();

    if (method.equals("GET")) {
        onRequestGet(event);/*from w  w  w  .ja  va 2 s  . co m*/
    } else if (method.equals("POST")) {
        onRequestPost(event);
    } else if (method.equals("OPTIONS")) {
        onRequestOption(event);
    }
}