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:at.gv.egovernment.moa.id.auth.servlet.GetMISSessionIDServlet.java

/**
 * Gets the signer certificate from the InfoboxReadRequest and responds with
 * a new <code>CreateXMLSignatureRequest</code>. <br>
 * Request parameters://from w  w w  . ja  va  2 s .  c  o m
 * <ul>
 * <li>MOASessionID: ID of associated authentication session</li>
 * <li>XMLResponse: <code>&lt;InfoboxReadResponse&gt;</code></li>
 * </ul>
 * 
 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest,
 *      HttpServletResponse)
 */
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Logger.debug("POST GetMISSessionIDServlet");

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

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

    AuthenticationSession session = null;
    String pendingRequestID = null;
    try {
        // check parameter
        if (!ParamValidatorUtils.isValidSessionID(sessionID))
            throw new WrongParametersException("VerifyCertificate", PARAM_SESSIONID, "auth.12");

        pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID);

        session = AuthenticationServer.getSession(sessionID);

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

        String misSessionID = session.getMISSessionID();

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

        List<MISMandate> list = MISSimpleClient.sendGetMandatesRequest(connectionParameters.getUrl(),
                misSessionID, sslFactory);

        if (list == null || list.size() == 0) {
            Logger.error("Keine Vollmacht gefunden.");
            throw new AuthenticationException("auth.15", null);
        }

        // for now: list contains only one element
        MISMandate mandate = (MISMandate) list.get(0);

        // TODO[tlenz]: UTF-8 ?
        String sMandate = new String(mandate.getMandate());
        if (sMandate == null || sMandate.compareToIgnoreCase("") == 0) {
            Logger.error("Mandate is empty.");
            throw new AuthenticationException("auth.15", new Object[] { GET_MIS_SESSIONID });
        }

        //check if it is a parsable XML
        byte[] byteMandate = mandate.getMandate();
        // TODO[tlenz]: UTF-8 ?
        String stringMandate = new String(byteMandate);
        DOMUtils.parseDocument(stringMandate, false, null, null).getDocumentElement();

        // extract RepresentationType
        AuthenticationServer.getInstance().verifyMandate(session, mandate);

        session.setMISMandate(mandate);
        session.setAuthenticatedUsed(false);
        session.setAuthenticated(true);

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

        String oldsessionID = session.getSessionID();

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

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

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

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

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

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

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

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

    } finally {
        ConfigurationDBUtils.closeSession();
    }
}

From source file:ch.entwine.weblounge.dispatcher.impl.WebloungeDispatcherServlet.java

/**
 * {@inheritDoc}//w  ww  . j  av a  2s .c  om
 * 
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
protected void service(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws ServletException, IOException {

    // Return the instance name if available
    if (instanceName != null) {
        httpResponse.addHeader("X-Weblounge-Instance", instanceName);
    }

    if (sites == null) {
        httpResponse.sendError(SC_SERVICE_UNAVAILABLE);
        return;
    }

    logger.debug("Serving {}", httpRequest.getRequestURI());

    // Get the site dispatcher
    Site site = securityService.getSite();
    if (site == null) {
        site = getSiteByRequest(httpRequest);
        securityService.setSite(site);
    }

    boolean isSpecialRequest = StringUtils.isNotBlank(httpRequest.getHeader("X-Weblounge-Special"));

    // See if a site dispatcher was found, and if so, if it's enabled
    if (site == null) {
        String serverName = httpRequest.getScheme() + "://" + httpRequest.getServerName();
        if (httpRequest.getServerPort() != 80)
            serverName += ":" + httpRequest.getServerPort();
        if (!wellknownFiles.contains(httpRequest.getRequestURI())
                && !missingSiteWarnings.contains(serverName)) {
            missingSiteWarnings.add(serverName);
            logger.warn("No site found to handle {}", serverName);
        }
        httpResponse.sendError(SC_NOT_FOUND);
        return;
    } else if (!site.isOnline() && !isSpecialRequest) {
        if (site.getContentRepository() == null) {
            if (!missingRepositoryWarnings.contains(site.getIdentifier())) {
                logger.warn("No content repository connected to site '{}'", site);
                missingRepositoryWarnings.add(site.getIdentifier());
            } else {
                logger.debug("No content repository connected to site '{}'", site);
            }
        } else {
            logger.debug("Ignoring request for disabled site '{}'", site);
        }
        httpResponse.sendError(SC_SERVICE_UNAVAILABLE);
        return;
    }

    // Make sure the response is buffered
    httpResponse = new BufferedHttpServletResponse(httpResponse);

    // Get the servlet that is responsible for the site's content
    Servlet siteServlet = sites.getSiteServlet(site);

    // Get the response cache, if available
    ResponseCache cache = caches.get(site.getIdentifier());

    // Wrap for caching
    if (cache != null) {
        httpResponse = cache.createCacheableResponse(httpRequest, httpResponse);
    }

    // Wrap request and response
    WebloungeRequestImpl request = new WebloungeRequestImpl(httpRequest, siteServlet, environment);
    WebloungeResponseImpl response = new WebloungeResponseImpl(httpResponse);

    // Configure request and response objects
    request.init(site);
    response.setRequest(request);
    response.setResponseCache(cache);
    response.setCharacterEncoding(DEFAULT_RESPONSE_ENCODING);
    response.setHeader("X-Powered-By", POWERED_BY);
    response.setDateHeader("Date", Calendar.getInstance().getTimeInMillis());

    // Notify listeners about starting request
    fireRequestStarted(request, response, site);

    boolean requestServed = false;

    // Ask the registered request handler if they are willing to handle
    // the request.
    try {
        securityService.setSite(site);
        request.setUser(securityService.getUser());
        for (RequestHandler handler : requestHandler) {
            try {
                logger.trace("Asking {} to serve {}", handler, request);
                if (handler.service(request, response)) {
                    requestServed = true;
                    logger.debug("{} served request {}", handler, request);
                    if (response.hasError()) {
                        logger.debug("Request processing failed on {}", request);
                        fireRequestFailed(request, response, site);
                    } else {
                        fireRequestDelivered(request, response, site);
                    }
                    return;
                }
            } catch (Throwable t) {
                response.invalidate();
                String params = RequestUtils.dumpParameters(request);
                if (t.getCause() != null) {
                    t = t.getCause();
                }
                logger.error("Request handler '{}' failed to handle {} {}",
                        new Object[] { handler, request, params });
                logger.error(t.getMessage(), t);
                DispatchUtils.sendInternalError(t.getMessage(), request, response);
                break;
            }
        }
    } finally {
        securityService.setSite(null);
        if (requestServed) {
            response.endResponse();
            response.flushBuffer();
            logger.debug("Finished processing of {}", httpRequest.getRequestURI());
        } else {
            logger.debug("No handler found for {}", request);
            DispatchUtils.sendNotFound(request, response);
            if (cache != null)
                cache.invalidate(response);
            fireRequestFailed(request, response, site);
        }
    }
}

From source file:eionet.webq.web.controller.FileDownloadController.java

/**
 * Writes specified content to http response.
 *
 * @param response http response//from  w  w  w  . j a v a  2s .c  om
 * @param data     content to be written to response
 */
private void writeToResponse(HttpServletResponse response, byte[] data) {
    ServletOutputStream output = null;
    try {
        response.setContentLength(data.length);
        boolean noCache = true;

        if (response.getContentType() != null && response.getContentType().startsWith("image")) {
            noCache = false;
        }
        if (noCache) {
            response.addHeader("Cache-control", "no-cache");
        }

        output = response.getOutputStream();
        IOUtils.write(data, output);
        output.flush();
    } catch (IOException e) {
        throw new RuntimeException("Unable to write response", e);
    } finally {
        IOUtils.closeQuietly(output);
    }
}

From source file:com.redblackit.web.server.EchoServlet.java

/**
 * doEcho//from   w ww.jav a  2s . c  o m
 * 
 * <ul>
 * <li>Log method, URL, headers, body</li>
 * <li>Replicate request headers, except for setting location to received
 * URL</li>
 * <li>Replicate request body in response</li>
 * </ul>
 * 
 * @param req
 * @param resp
 * @param method
 */
@SuppressWarnings("rawtypes")
private void doEcho(HttpServletRequest req, HttpServletResponse resp, String method) throws IOException {
    String reqURI = req.getRequestURI();
    logger.debug(this.getClass().getName() + ":" + method + " - " + reqURI);

    for (Enumeration hdrse = req.getHeaderNames(); hdrse.hasMoreElements();) {
        String headerName = (String) hdrse.nextElement();
        int hnct = 0;
        for (Enumeration hdre = req.getHeaders(headerName); hdre.hasMoreElements();) {
            String headerValue = (String) hdre.nextElement();
            logger.debug(
                    this.getClass().getName() + ":  header[" + headerName + "," + hnct + "]=" + headerValue);
            if (!headerName.equals("Location")) {
                resp.addHeader(headerName, headerValue);
            }
            hnct++;
        }

        if (hnct == 0) {
            resp.setHeader(headerName, "");
            logger.info(this.getClass().getName() + ":  header[" + headerName + "," + hnct + "]='' (empty)");
        }
    }

    resp.setHeader("Location", reqURI);
    resp.setStatus(HttpServletResponse.SC_OK);

    if (req.getContentLength() > 0 && !(method.equals("HEAD") || method.equals("DELETE"))) {
        String body = FileCopyUtils.copyToString(req.getReader());
        logger.debug(this.getClass().getName() + ":  body>>\n" + body + "\nbody<<");
        FileCopyUtils.copy(body, resp.getWriter());
        resp.flushBuffer();
        resp.setContentLength(req.getContentLength());
    } else {
        logger.debug(this.getClass().getName() + ":  body is empty");
        resp.setContentLength(0);
    }

}

From source file:com.dbi.jmmerge.MapController.java

@RequestMapping(value = "maps/{server}", produces = "application/zip")
public byte[] downloadMap(@PathVariable("server") String server, HttpServletResponse response)
        throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedOutputStream bufstream = new BufferedOutputStream(baos);
    ZipOutputStream zip = new ZipOutputStream(bufstream);

    addDirectoryContents(null, new File(storageDir, server), zip);

    zip.finish();// w  w w.  ja v a  2  s  . c  o m
    zip.flush();
    IOUtils.closeQuietly(zip);
    IOUtils.closeQuietly(bufstream);
    IOUtils.closeQuietly(baos);

    response.setStatus(HttpServletResponse.SC_OK);
    response.addHeader("Content-Disposition", "attachment; filename=\"" + server + ".zip\"");
    return baos.toByteArray();
}

From source file:net.sf.jasperreports.web.servlets.ReportServlet.java

/**
 *
 *//*  w ww .  j  a v a2 s. c  om*/
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 {
            runReport(request, webReportContext);
            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>");
        */
    }

}

From source file:com.iyonger.apm.web.controller.FileEntryController.java

/**
 * Download file entry of given path./*from www .j a  v  a 2 s . co  m*/
 *
 * @param user     current user
 * @param path     user
 * @param response response
 */
@RequestMapping("/download/**")
public void download(User user, String path, HttpServletResponse response) {
    FileEntry fileEntry = fileEntryService.getOne(user, path);
    if (fileEntry == null) {
        LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path);
        return;
    }
    response.reset();
    try {
        response.addHeader("Content-Disposition", "attachment;filename="
                + java.net.URLEncoder.encode(FilenameUtils.getName(fileEntry.getPath()), "utf8"));
    } catch (UnsupportedEncodingException e1) {
        LOG.error(e1.getMessage(), e1);
    }
    response.setContentType("application/octet-stream; charset=UTF-8");
    response.addHeader("Content-Length", "" + fileEntry.getFileSize());
    byte[] buffer = new byte[4096];
    ByteArrayInputStream fis = null;
    OutputStream toClient = null;
    try {
        fis = new ByteArrayInputStream(fileEntry.getContentBytes());
        toClient = new BufferedOutputStream(response.getOutputStream());
        int readLength;
        while (((readLength = fis.read(buffer)) != -1)) {
            toClient.write(buffer, 0, readLength);
        }
    } catch (IOException e) {
        throw processException("error while download file", e);
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(toClient);
    }
}

From source file:flex.messaging.services.http.proxy.ResponseFilter.java

protected void copyHeadersFromEndpoint(ProxyContext context) {
    HttpServletResponse clientResponse = FlexContext.getHttpResponse();

    if (clientResponse != null) {
        Header[] headers = context.getHttpMethod().getResponseHeaders();
        for (int i = 0; i < headers.length; i++) {
            Header header = headers[i];//from w  w  w.  j a v  a  2 s.c o  m
            String name = header.getName();
            String value = header.getValue();
            if (ResponseUtil.ignoreHeader(name, context)) {
                continue;
            }

            if ((name != null) && (value != null)) {
                clientResponse.addHeader(name, value);
                if (Log.isInfo()) {
                    Log.getLogger(HTTPProxyService.LOG_CATEGORY)
                            .debug("-- Header in response: " + name + " : " + value);
                }
            }
        }
        // set Pragma needed for ATG on HTTPS
        clientResponse.setHeader("Pragma", "public");
    }
}

From source file:com.feilong.controller.DownloadController.java

public HttpServletResponse download(String path, HttpServletResponse response) {
    try {//from w  ww  .  j  av  a2  s.c  om
        // path
        File file = new File(path);
        // ???
        String filename = file.getName();
        // ????
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // ??
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // response
        response.reset();
        // responseHeader
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return response;
}

From source file:it.cilea.osd.jdyna.web.controller.ExportConfigurazioneAlberiClassificatori.java

/**
 * Esporta la configurazione corrente di tutti gli alberi classificatori o,
 * se la request contiene un albero_id, solo del'albero classificatorio con
 * quell'ID specifico./* w  w  w. jav  a  2  s  .co  m*/
 * 
 */
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
        BindException errors) throws RuntimeException, IOException {
    String alberoIDStr = request.getParameter("albero_id");
    Integer alberoID = null;
    if (alberoIDStr != null) {
        alberoID = Integer.parseInt(alberoIDStr);
    }
    AlberoClassificatorio albero = null;
    if (alberoID != null) {
        albero = applicationService.get(AlberoClassificatorio.class, alberoID);
    }

    String filename;
    if (albero == null) {
        filename = "configurazione-alberi_classificatori.xml";
    } else {
        filename = "configurazione-albero_classificatorio_" + albero.getNome().replaceAll(" ", "_") + ".xml";
    }
    response.setContentType("application/xml");
    response.addHeader("Content-Disposition", "attachment; filename=" + filename);

    PrintWriter writer = response.getWriter();
    exportUtils.writeDocTypeANDCustomEditorAlberoClassificatore(writer);

    if (albero != null) {
        exportUtils.alberoClassificatorioToXML(writer, albero);
    } else {
        List<AlberoClassificatorio> allAlberi = applicationService.getList(AlberoClassificatorio.class);
        for (AlberoClassificatorio alberoIter : allAlberi) {
            exportUtils.alberoClassificatorioToXML(writer, alberoIter);
        }
    }
    response.getWriter().print("</beans>");
    return null;
}