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.jd.survey.web.settings.DataSetController.java

/**
 * exports a dataset to a comma delimited file
 * @param dataSetId/*from   ww  w . j a  v a  2 s. c o  m*/
 * @param principal
 * @param response
 */

@RequestMapping(value = "/{id}", params = "export", produces = "text/html")
public void export(@PathVariable("id") Long dataSetId, Principal principal, HttpServletResponse response) {
    try {

        String commaDelimtedString = surveySettingsService.exportDatasetItemsToCommaDelimited(dataSetId);
        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // 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");
        response.setHeader("Content-Disposition", "inline;filename=dataSetItems" + dataSetId + ".csv");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(commaDelimtedString.getBytes("UTF-8"));
        servletOutputStream.flush();

    }

    catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:org.apache.cxf.fediz.spring.web.FederationLogoutSuccessHandler.java

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    String contextName = request.getContextPath();
    if (contextName == null || contextName.isEmpty()) {
        contextName = "/";
    }/*from www.  j  ava  2s  .  c  om*/
    FedizContext fedCtx = federationConfig.getFedizContext(contextName);
    try {
        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedCtx.getProtocol());
        RedirectionResponse redirectionResponse = wfProc.createSignOutRequest(request, null, fedCtx); //TODO
        String redirectURL = redirectionResponse.getRedirectionURL();
        if (redirectURL != null) {
            Map<String, String> headers = redirectionResponse.getHeaders();
            if (!headers.isEmpty()) {
                for (String headerName : headers.keySet()) {
                    response.addHeader(headerName, headers.get(headerName));
                }
            }

            response.sendRedirect(redirectURL);
        } else {
            LOG.warn("Failed to create SignOutRequest.");
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to create SignOutRequest.");
        }
    } catch (ProcessingException ex) {
        LOG.warn("Failed to create SignOutRequest: " + ex.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignOutRequest.");
    }
}

From source file:org.eclipse.virgo.apps.repository.web.RepositoryController.java

@RequestMapping(method = RequestMethod.GET, value = "/*")
void getIndex(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String path = request.getRequestURI();
    String repository = path.substring(path.lastIndexOf('/') + 1);

    RepositoryIndex index = this.repositoryManager.getIndex(repository);
    if (index != null) {
        String indexETag = index.getETag();

        String eTagHeader = request.getHeader(IF_NONE_MATCH_HEADER_NAME);
        if (eTagHeader != null) {
            String[] eTags = eTagHeader.split(",");
            for (String eTag : eTags) {
                if (eTag.equals(indexETag)) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                }//from w ww.  j  a  v  a2 s  .c  om
            }
        }

        response.setContentType(INDEX_CONTENT_TYPE);
        response.setContentLength(index.getLength());
        response.addHeader(ETAG_HEADER_NAME, index.getETag());

        FileCopyUtils.copy(index.getInputStream(), response.getOutputStream());
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:SendMp3.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String fileName = (String) request.getParameter("file");
    if (fileName == null || fileName.equals(""))
        throw new ServletException("Invalid or non-existent file parameter in SendMp3 servlet.");

    if (fileName.indexOf(".mp3") == -1)
        fileName = fileName + ".mp3";

    String mp3Dir = getServletContext().getInitParameter("mp3-dir");
    if (mp3Dir == null || mp3Dir.equals(""))
        throw new ServletException("Invalid or non-existent mp3Dir context-param.");

    ServletOutputStream stream = null;//w  w w .j av  a 2s. c o  m
    BufferedInputStream buf = null;
    try {

        stream = response.getOutputStream();
        File mp3 = new File(mp3Dir + "/" + fileName);

        //set response headers
        response.setContentType("audio/mpeg");

        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

        response.setContentLength((int) mp3.length());

        FileInputStream input = new FileInputStream(mp3);
        buf = new BufferedInputStream(input);
        int readBytes = 0;
        //read from the file; write to the ServletOutputStream
        while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);
    } catch (IOException ioe) {
        throw new ServletException(ioe.getMessage());
    } finally {
        if (stream != null)
            stream.close();
        if (buf != null)
            buf.close();
    }
}

From source file:com.pkrete.locationservice.admin.controller.mvc.StatisticsController.java

@RequestMapping(method = { RequestMethod.POST })
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();
    StatisticsGroup group = StatisticsUtil.parseGroup(request.getParameter("group"));
    SearchEventType type = StatisticsUtil.parseType(request.getParameter("type"));
    String from = StatisticsUtil.parseFromDate(request.getParameter("from"));
    String to = StatisticsUtil.parseToDate(request.getParameter("to"));
    String order = request.getParameter("order");
    String output = request.getParameter("output");
    String ownerCode = getOwner(request).getCode();

    StatisticsSearchResult results = statisticsService.getStatistics(ownerCode, group, type, from, to, order);

    if (output != null) {
        if (output.equals("file")) {
            response.setContentType("application/txt");
            response.addHeader("content-disposition", "attachment;filename=statistics.txt");
            return new ModelAndView("statistics_file", "stats", resultsToString(results));
        }/*from w  ww  .  jav  a 2s  . c om*/
    }
    model.put("stats", results.getData());
    return new ModelAndView("statistics", "model", model);
}

From source file:de.kp.ames.web.core.service.ServiceImpl.java

public void sendImageDownloadResponse(ImageUtil image, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    if (image == null)
        return;/*from  w w  w.java 2  s .  c o  m*/

    String clientPath = request.getParameter("clientpath");
    if (clientPath == null)
        return;

    /*
     * Distinguish between secure and non-secure download requests
     */
    if (request.isSecure()) {

        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Pragma", "no-cache");

        response.addHeader("Expires", "-1");

    } else {

        response.addHeader("Cache-Control", "private");
        response.addHeader("Pragma", "public");

    }

    /*
     * Signal download ready with cookie
     */
    Cookie cookie = new Cookie("DOWNLOAD_READY", "END");
    cookie.setPath(clientPath);
    response.addCookie(cookie);

    /*
     * Determine user agent
     */
    String ua = request.getHeader("User-Agent").toLowerCase();
    boolean isIE = ((ua.indexOf("msie 6.0") != -1) || (ua.indexOf("msie 7.0") != -1)) ? true : false;

    /*
     * Encode file name
     */
    String encFileName = URLEncoder.encode(image.getFilename(), "UTF-8");

    if (isIE) {

        response.addHeader("Content-Disposition", "attachment;  filename=\"" + encFileName + "\"");
        response.addHeader("Connection", "close");

        response.setContentType("application/force-download;  name=\"" + encFileName + "\"");

    } else {

        response.addHeader("Content-Disposition", "attachment; filename=\"" + encFileName + "\"");

        response.setContentType("application/octet-stream; name=\"" + encFileName + "\"");
        response.setContentLength(image.getLength());

    }

    // finally set http status
    response.setStatus(HttpServletResponse.SC_OK);

    OutputStream os = response.getOutputStream();

    os.write(image.getBytes());
    os.close();
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.simple.services.presentation.SimpleAuthenticationServiceImpl.java

/**
 * Authenticates an user. Requires basic authentication header.
 * @param httpServletRequest/*w  ww. java  2 s. c  o m*/
 * @param httpServletResponse
 * @return
 * @throws Exception
 */
@RequestMapping(value = "${appverse.frontfacade.rest.simpleAuthenticationEndpoint.path:/sec/simplelogin}", method = RequestMethod.POST)
public ResponseEntity<AuthorizationData> login(@RequestBody CredentialsVO credentials,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    try {
        if (credentials == null || credentials.getUsername() == null) {
            throw new BadCredentialsException("Invalid parameters");
        }
        // Authenticate principal and return authorization data
        AuthorizationData authData = userAndPasswordAuthenticationManager
                .authenticatePrincipal(credentials.getUsername(), credentials.getPassword());

        if (securityEnableCsrf) {
            // Obtain XSRFToken and add it as a response header
            // The token comes in the request (CsrFilter adds it) and we need to set it in the response so the clients 
            // have it to use it in the next requests
            CsrfToken csrfToken = (CsrfToken) httpServletRequest.getAttribute(CSRF_TOKEN_SESSION_ATTRIBUTE);
            httpServletResponse.addHeader(csrfToken.getHeaderName(), csrfToken.getToken());
        }

        // AuthorizationDataVO
        return new ResponseEntity<AuthorizationData>(authData, HttpStatus.OK);
    } catch (AuthenticationException e) {
        return new ResponseEntity<AuthorizationData>(HttpStatus.UNAUTHORIZED);
    }
}

From source file:de.kp.ames.web.core.service.ServiceImpl.java

/**
 * A specific method to enable file download even in a secure (SSL) environment
 * // w w w .  ja  v  a 2s .  c o  m
 * @param file
 * @param request
 * @param response
 * @throws IOException
 */
public void sendFileDownloadResponse(FileUtil file, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    if (file == null)
        return;

    String clientPath = request.getParameter("clientpath");
    if (clientPath == null)
        return;

    /*
     * Distinguish between secure and non-secure download requests
     */
    if (request.isSecure()) {

        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Pragma", "no-cache");

        response.addHeader("Expires", "-1");

    } else {

        response.addHeader("Cache-Control", "private");
        response.addHeader("Pragma", "public");

    }

    /*
     * Determine user agent
     */
    String ua = request.getHeader("User-Agent").toLowerCase();
    boolean isIE = ((ua.indexOf("msie 6.0") != -1) || (ua.indexOf("msie 7.0") != -1)) ? true : false;

    /*
     * Encode file name
     */
    String encFileName = URLEncoder.encode(file.getFilename(), "UTF-8");

    if (isIE) {

        response.addHeader("Content-Disposition", "attachment;  filename=\"" + encFileName + "\"");
        response.addHeader("Connection", "close");

        response.setContentType("application/force-download;  name=\"" + encFileName + "\"");

    } else {

        response.addHeader("Content-Disposition", "attachment; filename=\"" + encFileName + "\"");

        response.setContentType("application/octet-stream; name=\"" + encFileName + "\"");
        response.setContentLength(file.getLength());

    }

    /*
     * Signal download ready with cookie
     */
    Cookie cookie = new Cookie("DOWNLOAD_READY", "END");
    cookie.setPath(clientPath);
    response.addCookie(cookie);

    // finally set http status
    response.setStatus(HttpServletResponse.SC_OK);

    OutputStream os = response.getOutputStream();

    os.write(file.getFile());
    os.close();

}

From source file:com.arifultonu.mappingServlet.RegistrationServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request// w  ww .  jav a2 s  .c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        JSONObject json = new JSONObject();
        RegistrationDAO registrationDAO = new RegistrationDAO();
        for (RegistrationBO oRegistrationBO : registrationDAO.getDataFromDB()) {
            Map<String, Object> map = new HashMap<String, Object>();

            map.put("UserName", oRegistrationBO.getUserName());
            map.put("Email", oRegistrationBO.getEmail());
            map.put("Password", oRegistrationBO.getPassword());
            list.add(map);
            json.put("UserDataList", list);

        }
        // System.out.println("Data List: "+ list);
        System.out.println("Json Nodes >>>: " + json);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json.toString());
    } catch (Exception e) {
        Logger.getLogger(RegistrationServlet.class.getName()).log(Level.SEVERE, null, e);
    }

}

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

/**
 * Verifies the signed authentication block and redirects the browser
 * to the online application requested, adding a parameter needed for
 * retrieving the authentication data./*from w ww  . jav a 2  s  . c  o  m*/
 * <br>
 * Request parameters:
 * <ul>
 * <li>MOASessionID: ID of associated authentication session</li>
 * <li>XMLResponse: <code>&lt;CreateXMLSignatureResponse&gt;</code></li>
 * </ul>
 * Response:
 * <ul>
 * <li>Status: <code>302</code></li>
 * <li>Header <code>"Location"</code>: URL of the online application requested, with
 *                   parameters <code>"Target"</code>(only if the online application is
 *            a public service) and <code>"SAMLArtifact"</code> added</li>
 * <li>Error status: <code>500</code>
 * </ul>
 * @see AuthenticationServer#verifyAuthenticationBlock
 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse)
 */
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Logger.debug("POST VerifyAuthenticationBlock");

    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);

    String pendingRequestID = null;

    Map<String, String> parameters;
    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);
    String createXMLSignatureResponse = (String) parameters.get(PARAM_XMLRESPONSE);

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

    String redirectURL = null;
    try {
        // check parameter
        if (!ParamValidatorUtils.isValidSessionID(sessionID))
            throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12");
        if (!ParamValidatorUtils.isValidXMLDocument(createXMLSignatureResponse))
            throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_XMLRESPONSE, "auth.12");

        AuthenticationSession session = AuthenticationServer.getSession(sessionID);

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

        String samlArtifactBase64 = AuthenticationServer.getInstance().verifyAuthenticationBlock(session,
                createXMLSignatureResponse);

        if (samlArtifactBase64 == null) {
            //mandate Mode

            AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance();
            ConnectionParameter connectionParameters = authConf.getOnlineMandatesConnectionParameter();
            SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(),
                    connectionParameters);

            // get identitity link as byte[]
            Element elem = session.getIdentityLink().getSamlAssertion();
            String s = DOMUtils.serializeNode(elem);

            //System.out.println("IDL: " + s);

            byte[] idl = s.getBytes("UTF-8");

            // redirect url
            // build redirect(to the GetMISSessionIdSerlvet)

            //change MOASessionID before MIS request
            String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session);

            redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), GET_MIS_SESSIONID,
                    newMOASessionID);

            String oaURL = session.getOAURLRequested();
            OAAuthParameter oaParam = authConf.getOnlineApplicationParameter(oaURL);
            List<String> profiles = oaParam.getMandateProfiles();

            if (profiles == null) {
                Logger.error("No Mandate/Profile for OA configured.");
                throw new AuthenticationException("config.21", new Object[] { GET_MIS_SESSIONID });
            }

            //                 String profilesArray[] = profiles.split(",");             
            //                 for(int i = 0; i < profilesArray.length; i++) {
            //                    profilesArray[i] = profilesArray[i].trim();
            //                 }

            String oaFriendlyName = oaParam.getFriendlyName();
            String mandateReferenceValue = session.getMandateReferenceValue();
            byte[] cert = session.getEncodedSignerCertificate();
            byte[] authBlock = session.getAuthBlock().getBytes("UTF-8");

            //TODO: check in case of SSO!!!
            String targetType = null;
            if (oaParam.getBusinessService()) {
                String id = oaParam.getIdentityLinkDomainIdentifier();
                if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_))
                    targetType = id;
                else
                    targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_ + session.getDomainIdentifier();

            } else {
                targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget();
            }

            MISSessionId misSessionID = MISSimpleClient.sendSessionIdRequest(connectionParameters.getUrl(), idl,
                    cert, oaFriendlyName, redirectURL, mandateReferenceValue, profiles, targetType, authBlock,
                    sslFactory);

            if (misSessionID == null) {
                Logger.error("Fehler bei Anfrage an Vollmachten Service. MIS Session ID ist null.");
                throw new MISSimpleClientException("Fehler bei Anfrage an Vollmachten Service.");
            }

            String redirectMISGUI = misSessionID.getRedirectURL();
            session.setMISSessionID(misSessionID.getSessiondId());

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

            resp.setStatus(302);
            resp.addHeader("Location", redirectMISGUI);
            Logger.debug("REDIRECT TO: " + redirectURL);
        } else {

            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),
                        samlArtifactBase64);

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

            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 (GeneralSecurityException e) {
        handleError(null, e, req, resp, pendingRequestID);

    } catch (PKIException e) {
        handleError(null, e, req, resp, pendingRequestID);

    } catch (TransformerException e) {
        handleError(null, e, req, resp, pendingRequestID);

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

    finally {
        ConfigurationDBUtils.closeSession();
    }

}