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.nkapps.billing.controllers.ReportController.java

@RequestMapping(value = "/print-click", method = RequestMethod.POST)
public void printClick(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HSSFWorkbook workbook = null;//from   w w w .  j  av  a2 s. com

    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    Date periodStart = sdf.parse(request.getParameter("periodStart"));
    Date periodEnd = sdf.parse(request.getParameter("periodEnd"));

    List<ReportClickListPojo> listPojo = reportService.getPrintClickList(periodStart, periodEnd);
    workbook = reportPrintService.printClick(listPojo);

    String fileName = new SimpleDateFormat("dd.MM.yyyy HH-mm-ss").format(Calendar.getInstance().getTime());
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xls\"");
    response.addHeader("Cache-Control", "max-age=1, must-revalidate");
    response.addHeader("Pragma", "no-cache");

    OutputStream stream = response.getOutputStream();
    workbook.write(stream);

}

From source file:io.github.howiefh.jeews.modules.oauth2.shiro.filter.TokenFilter.java

@Override
protected boolean onAccessDenied(ServletRequest req, ServletResponse resp) throws Exception {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    try {//  w w w  .  j  a  v  a  2  s  .  c om
        // OAuth?
        OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request,
                ParameterStyle.HEADER);
        // ?Access Token
        String accessToken = oauthRequest.getAccessToken();

        // ?Access Token
        if (!oAuthService.checkAccessToken(accessToken)) {
            // ?/???
            OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                    .setRealm(Constants.RESOURCE_SERVER_NAME)
                    .setError(OAuthError.ResourceResponse.INVALID_TOKEN).buildHeaderMessage();

            response.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE,
                    oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    } catch (OAuthProblemException e) {
        // ??
        String errorCode = e.getError();
        if (OAuthUtils.isEmpty(errorCode)) {
            OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                    .setRealm(Constants.RESOURCE_SERVER_NAME).buildHeaderMessage();

            response.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE,
                    oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                .setRealm(Constants.RESOURCE_SERVER_NAME).setError(e.getError())
                .setErrorDescription(e.getDescription()).setErrorUri(e.getUri()).buildHeaderMessage();

        response.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE,
                oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return false;
    }

}

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

/**
 * Verifies the identity link and responds with a new 
 * <code>CreateXMLSignatureRequest</code>.
 * <br>//from w w w . j a v a2s  .c o  m
 * Request parameters:
 * <ul>
 * <li>MOASessionID: ID of associated authentication session</li>
 * <li>XMLResponse: <code>&lt;InfoboxReadResponse&gt;</code></li>
 * </ul>
 * Response:
 * <ul>
 * <li>Content type: <code>"text/xml"</code></li>
 * <li>Content: see return value of {@link AuthenticationServer#verifyIdentityLink}</li>
 * <li>Error status: <code>500</code>
 * </ul>
 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse)
 */
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Logger.debug("POST GetForeignIDServlet");

    Logger.warn(getClass().getName() + " is deprecated and should not be used any more.");

    resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
    resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
    resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
    resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);

    Map<String, String> parameters;

    String pendingRequestID = null;

    try {
        parameters = getParameters(req);
    } catch (FileUploadException e) {
        Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage());
        throw new IOException(e.getMessage());
    }
    String sessionID = req.getParameter(PARAM_SESSIONID);
    pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID);

    // escape parameter strings
    sessionID = StringEscapeUtils.escapeHtml(sessionID);

    String redirectURL = null;
    AuthenticationSession session = null;
    try {
        String xmlCreateXMLSignatureResponse = (String) parameters.get(PARAM_XMLRESPONSE);
        // check parameter
        if (!ParamValidatorUtils.isValidSessionID(sessionID))
            throw new WrongParametersException("GetForeignID", PARAM_SESSIONID, "auth.12");
        if (!ParamValidatorUtils.isValidXMLDocument(xmlCreateXMLSignatureResponse))
            throw new WrongParametersException("GetForeignID", PARAM_XMLRESPONSE, "auth.12");

        session = AuthenticationServer.getSession(sessionID);

        //change MOASessionID
        sessionID = AuthenticationSessionStoreage.changeSessionID(session);

        Logger.debug(xmlCreateXMLSignatureResponse);

        CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser(xmlCreateXMLSignatureResponse)
                .parseResponseDsig();

        try {
            String serializedAssertion = DOMUtils.serializeNode(csresp.getDsigSignature());
            session.setAuthBlock(serializedAssertion);

        } catch (TransformerException e) {
            throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE });

        } catch (IOException e) {
            throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE });

        }

        Element signature = csresp.getDsigSignature();

        try {
            session.setSignerCertificate(AuthenticationServer.getCertificateFromXML(signature));
        } catch (CertificateException e) {
            Logger.error("Could not extract certificate from CreateXMLSignatureResponse");
            throw new MOAIDException("auth.14", null);
        }

        // make SZR request to the identity link
        CreateIdentityLinkResponse response = AuthenticationServer.getInstance().getIdentityLink(signature);

        if (null != response.getErrorResponse()) {
            // TODO fix exception parameter
            throw new SZRGWClientException("service.08", (String) response.getErrorResponse().getErrorCode(),
                    (String) response.getErrorResponse().getInfo());
        } else {
            IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(
                    new ByteArrayInputStream(response.getIdentityLink()));
            IdentityLink identitylink = ilParser.parseIdentityLink();
            session.setIdentityLink(identitylink);

            //set QAA Level four in case of card authentifcation
            session.setQAALevel(PVPConstants.STORK_QAA_1_4);

            String samlArtifactBase64 = AuthenticationServer.getInstance()
                    .getForeignAuthenticationData(session);

            //session is implicit stored in changeSessionID!!!! 
            String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session);

            Logger.info("Changed MOASession " + sessionID + " to Session " + newMOASessionID);
            Logger.info("Daten angelegt zu MOASession " + newMOASessionID);

            if (!samlArtifactBase64.equals("Redirect to Input Processor")) {
                /*redirectURL = session.getOAURLRequested();
                if (!session.getBusinessService()) {
                   redirectURL = addURLParameter(redirectURL, PARAM_TARGET, URLEncoder.encode(session.getTarget(), "UTF-8"));
                }
                redirectURL = addURLParameter(redirectURL, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8"));
                redirectURL = resp.encodeRedirectURL(redirectURL);*/

                redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(),
                        ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID),
                        newMOASessionID);
                redirectURL = resp.encodeRedirectURL(redirectURL);

            } else {
                redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(),
                        AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, newMOASessionID);

            }

            try {
                AuthenticationSessionStoreage.storeSession(session);
            } catch (MOADatabaseException e) {
                throw new MOAIDException("Session store error", null);
            }

            resp.setContentType("text/html");
            resp.setStatus(302);
            resp.addHeader("Location", redirectURL);
            Logger.debug("REDIRECT TO: " + redirectURL);
        }

    } catch (MOAIDException ex) {
        handleError(null, ex, req, resp, pendingRequestID);

    } catch (Exception e) {
        Logger.error("GetForeignIDServlet has an interal Error.", e);

    }
}

From source file:com.erudika.scoold.controllers.SigninController.java

private void setAuthCookie(String jwt, HttpServletRequest req, HttpServletResponse res) {
    int maxAge = Config.SESSION_TIMEOUT_SEC;
    String expires = DateFormatUtils.format(System.currentTimeMillis() + (maxAge * 1000),
            "EEE, dd-MMM-yyyy HH:mm:ss z", TimeZone.getTimeZone("GMT"));

    StringBuilder sb = new StringBuilder();
    sb.append(Config.AUTH_COOKIE).append("=").append(jwt).append(";");
    sb.append("Path=/;");
    sb.append("Expires=").append(expires).append(";");
    sb.append("Max-Age=").append(maxAge).append(";");
    sb.append("HttpOnly;");
    sb.append("SameSite=Strict");
    res.addHeader(HttpHeaders.SET_COOKIE, sb.toString());
}

From source file:com.kolich.spring.views.AbstractKolichView.java

@Override
public void renderMergedOutputModel(final Map<String, Object> model, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    try {//from ww  w.j  ava 2 s .  c o  m
        final KolichViewSerializable payload = (KolichViewSerializable) model.get(VIEW_PAYLOAD);
        // If the payload has an Expires date attached to it, then
        // we should honor that by adding the Expires: header to the
        // response.  Controllers may set this so that upstream caches
        // do not attempt to cache the resource.
        final Date expires;
        if ((expires = payload.getExpires()) != null) {
            response.addDateHeader(EXPIRES, expires.getTime());
        }
        // If we are asked to disable caching of this response,
        // then we need to append the correct Cache-Control and Pragma
        // headers here.
        if (payload.disableCaching()) {
            response.addHeader(PRAGMA, PRAGMA_NO_CACHE);
            response.addHeader(CACHE_CONTROL, CACHE_CONTROL_NO_CACHE);
        }
        // Call the custom prepare response after anything else has
        // been set so that the view can override these if necessary.
        myPrepareResponse(payload, request, response);
        myRenderMergedOutputModel(payload, request, response);
    } catch (Exception e) {
        logger__.error("Failed to render merged output model.", e);
        throw e;
    }
}

From source file:es.juntadeandalucia.panelGestion.presentacion.controlador.impl.GeosearchController.java

/**
 * This method //from  www . j  a  va 2 s.  com
 * TODO
 *
 * Para realizar la configuracin se obtienen los archivos de configuracin
 * se realizan las modificaciones necesarias y se le facilita al usuario
 * dichos archivos para que finalice l el procedimiento de configuracin.
 * Las ltimas versiones de Solr admiten modificaciones del Schema a travs
 * de un API REST pero consideramos lioso realizar por un lado la configuracin
 * del schema mediante API y transparente al usuario y por otro lado darle los
 * archivos al usuario para que los sustituya en Geosearch.
 * 
 * @see https://wiki.apache.org/solr/SchemaRESTAPI
 */
public void downloadConfig() {
    String errorMessage = null;

    ServletOutputStream os = null;

    try {
        // checks
        // checks if specified a table
        if (tables.isEmpty()) {
            throw new Exception("No se ha especificado ninguna tabla");
        }
        // checks if specified a field
        boolean specifiedField = false;
        tables_loop: for (GeosearchTableVO table : tables) {
            List<GeosearchFieldVO> fields = table.getFields();
            for (GeosearchFieldVO field : fields) {
                if (field.isDefined()) {
                    specifiedField = true;
                    break tables_loop;
                }
            }
        }
        if (!specifiedField) {
            throw new Exception("No se ha configurado ningn campo de las tablas seleccionadas");
        }
        // checks duplicated fields each table
        for (GeosearchTableVO table : tables) {
            if (tableHasDuplicatedFields(table)) {
                throw new Exception("Existen campos duplicados en la tabla '".concat(table.getTable().getName())
                        .concat("'. Revise su configuracin."));
            }
        }

        // ovverides the duplicated field values
        overrideDuplicatedFields();

        checkFieldErrors();

        // gets the zip file with configuration
        byte[] configurationData = generateConfigurationZipData();

        // configures the response
        HttpServletResponse response = (HttpServletResponse) externalCtx.getResponse();
        response.setContentType(CONTENT_TYPE);
        response.addHeader("Content-disposition", "attachment; filename=\"".concat(FILE_NAME).concat("\""));

        os = response.getOutputStream();
        os.write(configurationData);
        os.flush();
        os.close();
        facesContext.responseComplete();
    } catch (GeosearchException e) {
        errorMessage = "Error en la generacin de los archivos de configuracin: " + e.getLocalizedMessage();
    } catch (ParserConfigurationException e) {
        errorMessage = "Error en la generacin de los archivos de configuracin: " + e.getLocalizedMessage();
    } catch (XPathExpressionException e) {
        errorMessage = "Error en la generacin de los archivos de configuracin: " + e.getLocalizedMessage();
    } catch (TransformerException e) {
        errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage();
    } catch (IOException e) {
        errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage();
    } catch (Exception e) {
        errorMessage = "Error en la descarga de la configuracin: " + e.getLocalizedMessage();
    } finally {
        try {
            if (os != null) {
                os.flush();
                os.close();
            }
        } catch (IOException e) {
            errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage();
        }
    }

    if (errorMessage != null) {
        StatusMessages.instance().add(Severity.ERROR, errorMessage);
        log.error(errorMessage);
    } else {
        // saves the new service for each table
        try {
            ServiceType geosearchType = serviceService.getServiceType("geobusquedas");
            for (GeosearchTableVO geosearchTable : tables) {
                Table table = geosearchTable.getTable();
                Service geosearchService = new Service();
                geosearchService.setName(table.getName());
                geosearchService.setServiceUrl(PanelSettings.geosearchMaster.getUrl().concat("/").concat(core));
                geosearchService.setType(geosearchType);
                serviceService.create(geosearchService, table);
            }
        } catch (Exception e) {
            errorMessage = "";
            StatusMessages.instance().add(Severity.ERROR, errorMessage);
            log.error(errorMessage);
        }
    }
}

From source file:com.sammyun.interceptor.MemberInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    HttpSession session = request.getSession();
    Principal principal = (Principal) session.getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
    if (HttpRequestDeviceUtils.isMobileDevice(request)) {
        loginUrl = DEFAULT_MOBILE_LOGIN_RUL;
    } else {//  w w  w .  j a va2 s  .com
        //2014120812:02:08Bug fix ?waploginUrl????DEFAULT_MOBILE_LOGIN_RUL
        loginUrl = DEFAULT_LOGIN_URL;
    }
    if (principal != null) {
        return true;
    } else {
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
            response.addHeader("loginStatus", "accessDenied");
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        } else {
            if (request.getMethod().equalsIgnoreCase("GET")) {
                String redirectUrl = request.getQueryString() != null
                        ? request.getRequestURI() + "?" + request.getQueryString()
                        : request.getRequestURI();
                response.sendRedirect(request.getContextPath() + loginUrl + "?" + REDIRECT_URL_PARAMETER_NAME
                        + "=" + URLEncoder.encode(redirectUrl, urlEscapingCharset));
            } else {
                response.sendRedirect(request.getContextPath() + loginUrl);
            }
            return false;
        }
    }
}

From source file:it.reply.orchestrator.config.filters.CustomRequestLoggingFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    long startTime = System.nanoTime();
    boolean isFirstRequest = !isAsyncDispatch(request);
    HttpServletRequest requestToUse = request;

    String requestId = "";// safeTrimmedString(request.getHeader(X_REQUEST_ID));

    if (requestId.isEmpty()) {
        requestId = "req-" + UUID.randomUUID().toString();
    }/*from   www .  ja  v  a  2s . c  o  m*/
    try {
        MDC.put(REQUEST_ID_MDC_KEY, requestId);
        response.addHeader(X_REQUEST_ID, requestId);

        if (isIncludePayload() && isFirstRequest && !(request instanceof ContentCachingRequestWrapper)) {
            requestToUse = new ContentCachingRequestWrapper(request);
        }

        boolean shouldLog = shouldLog(requestToUse);
        if (shouldLog && isFirstRequest) {
            beforeRequest(requestToUse);
        }
        try {
            filterChain.doFilter(requestToUse, response);
        } finally {
            if (shouldLog && !isAsyncStarted(requestToUse)) {
                afterRequest(requestToUse, response, getElapsedMillisec(startTime));
            }
        }
    } finally {
        MDC.remove(REQUEST_ID_MDC_KEY);
    }
}

From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.java

/** Copy proxied response headers back to the servlet client. */
protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletResponse servletResponse) {
    for (Header header : proxyResponse.getAllHeaders()) {
        if (hopByHopHeaders.containsHeader(header.getName()))
            continue;
        servletResponse.addHeader(header.getName(), header.getValue());
    }//  w  ww.j  av  a2 s  .c o  m
}

From source file:com.ctb.prism.report.api.CustomReportServlet.java

/**
 *
 *//*  ww w  .j av  a 2  s. c o m*/
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/html; charset=UTF-8");

    // Set to expire far in the past.
    response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
    // Set standard HTTP/1.1 no-cache headers.
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    // Set standard HTTP/1.0 no-cache header.
    response.setHeader("Pragma", "no-cache");

    PrintWriter out = response.getWriter();

    WebReportContext webReportContext = WebReportContext.getInstance(request);

    try {
        if (request.getParameterMap().containsKey(WebUtil.REQUEST_PARAMETER_PAGE_UPDATE)) {
            //FIXME move this to a different servlet
            pageUpdate(request, response, webReportContext);
        } else {
            /** PRISM **/
            //runReport(request, webReportContext);
            runReport(request, webReportContext, response);
            /** end PRISM **/
            render(request, webReportContext, out);
        }
    } catch (JRInteractiveException e) {
        log.error("Jasper Interactive error", e);

        out.println("<div><pre id=\"jrInteractiveError\">");
        if (e.getMessage() != null && e.getMessage().indexOf(AbstractAction.ERR_CONCAT_STRING) != -1) {
            String[] tokens = e.getMessage().split(AbstractAction.ERR_CONCAT_STRING);
            for (String token : tokens) {
                out.println(token);
            }

        } else {
            out.println(e.getMessage());
        }
        out.println("</pre></div>");
    } catch (Exception e) {
        log.error("Error on report execution", e);

        response.setContentType("application/json; charset=UTF-8");
        response.setStatus(404);

        out.println("{");
        out.println("\"msg\": \"JasperReports encountered an error!\"");
        out.println("}");

        /*
        out.println("<html>");//FIXMEJIVE do we need to render this? or should this be done by the viewer?
        out.println("<head>");
        out.println("<title>JasperReports - Web Application Sample</title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../stylesheet.css\" title=\"Style\">");
                
        out.println("<body bgcolor=\"white\">");
                
        out.println("<span class=\"bnew\">JasperReports encountered this error :</span>");
        out.println("<pre>");
        e.printStackTrace(out);
        out.println("</pre>");
        out.println("</body>");
        out.println("</html>");
        */
    }

}