Example usage for javax.servlet.http HttpServletResponse setContentLength

List of usage examples for javax.servlet.http HttpServletResponse setContentLength

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setContentLength.

Prototype

public void setContentLength(int len);

Source Link

Document

Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.

Usage

From source file:org.apache.maven.archiva.web.ras.RasSearchByLogicalPath.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String keywords = req.getParameter("path");
    SearchResultLimits limits = new SearchResultLimits(0);
    limits.setPageSize(100);/* w  w w  .ja va2s .  com*/
    //limits.setSelectedPage(SearchResultLimits.ALL_PAGES);

    List<String> repos = getObservableRepos(archivaXworkUser.getGuest());
    SearchResults results = crossRepo.searchForTerm(archivaXworkUser.getGuest(), repos, keywords, limits);

    String body = new String();
    List<SearchResultHit> hits = results.getHits();
    for (SearchResultHit sh : hits) {
        body += "Artifact Reference: ";
        body += sh.getGroupId() + ".";
        body += sh.getArtifactId() + ".";
        body += sh.getVersion() + "\n";
    }

    res.setContentType(MIME_TYPE);
    res.setContentLength(body.length());
    res.getWriter().print(body);

    //res.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, keywords);

    //        try
    //        {
    //         //Find 
    //        }
    //        catch ( UserNotFoundException unfe )
    //        {
    //            log.debug( COULD_NOT_AUTHENTICATE_USER, unfe );
    //            res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
    //        }
    //        catch ( AccountLockedException acce )
    //        {            
    //            res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
    //        }
    //        catch ( AuthenticationException authe )
    //        {   
    //            log.debug( COULD_NOT_AUTHENTICATE_USER, authe );
    //            res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
    //        }
    //        catch ( MustChangePasswordException e )
    //        {            
    //            res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
    //        }
    //        catch ( UnauthorizedException e )
    //        {
    //            log.debug( e.getMessage() );
    //            if ( repoId != null )
    //            {
    //                res.setHeader("WWW-Authenticate", "Basic realm=\"Repository Archiva Managed " + repoId + " Repository" );
    //            }
    //            else
    //            {
    //                res.setHeader("WWW-Authenticate", "Basic realm=\"Artifact " + groupId + ":" + artifactId );
    //            }
    //            
    //            res.sendError( HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED );
    //        }
}

From source file:org.apache.maven.archiva.web.ras.RasSearchByKeyword.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String keywords = req.getParameter("keyword");
    SearchResultLimits limits = new SearchResultLimits(0);
    limits.setPageSize(100);/*  w w w .  ja v a  2 s  . com*/
    //limits.setSelectedPage(SearchResultLimits.ALL_PAGES);

    List<String> repos = getObservableRepos(archivaXworkUser.getGuest());
    SearchResults results = crossRepo.searchForTerm(archivaXworkUser.getGuest(), repos, keywords, limits);

    String body = new String();
    List<SearchResultHit> hits = results.getHits();
    for (SearchResultHit sh : hits) {
        body += "Artifact Reference: ";
        body += sh.getGroupId() + ".";
        body += sh.getArtifactId() + ".";
        body += sh.getVersion() + "\n";
    }

    res.setContentType(MIME_TYPE);
    res.setContentLength(body.length());
    res.getWriter().print(body);

    //res.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, keywords);

    //        try
    //        {
    //         //Find 
    //        }
    //        catch ( UserNotFoundException unfe )
    //        {
    //            log.debug( COULD_NOT_AUTHENTICATE_USER, unfe );
    //            res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
    //        }
    //        catch ( AccountLockedException acce )
    //        {            
    //            res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
    //        }
    //        catch ( AuthenticationException authe )
    //        {   
    //            log.debug( COULD_NOT_AUTHENTICATE_USER, authe );
    //            res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
    //        }
    //        catch ( MustChangePasswordException e )
    //        {            
    //            res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
    //        }
    //        catch ( UnauthorizedException e )
    //        {
    //            log.debug( e.getMessage() );
    //            if ( repoId != null )
    //            {
    //                res.setHeader("WWW-Authenticate", "Basic realm=\"Repository Archiva Managed " + repoId + " Repository" );
    //            }
    //            else
    //            {
    //                res.setHeader("WWW-Authenticate", "Basic realm=\"Artifact " + groupId + ":" + artifactId );
    //            }
    //            
    //            res.sendError( HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED );
    //        }
}

From source file:m.w.sys.module.FileModule.java

@At("/downfileQuery/?")
@Ok("raw:stream")
public void downfileQuery(String fileName, HttpServletResponse rep) {
    fileName += ".txt";
    // String filePath = "C://tmp//License.txt";
    String filePath = "C://tmp//output_" + UserUtils.CurrentUser().getUsername() + ".txt";

    if (!Strings.isBlank(fileName) && !Strings.isBlank(filePath)) {

        if (filePath.startsWith(FileService.UPLOAD_URL)) {
            filePath = filePath.substring(FileService.UPLOAD_URL.length());
        }//from www  . j a  va 2  s . c o m
        File file = new File(FilenameUtils.concat(FileService.UPLOAD_ROOT_DIR, filePath));
        if (file.exists()) {
            InputStream fileIn = Streams.fileIn(file);
            long fileSize = FileUtils.sizeOf(file);
            rep.setContentType("application/x-msdownload");
            rep.setContentLength((int) fileSize);
            String outFileName = Names.encodeFileName(fileName);
            rep.setHeader("Content-Disposition", "attachment; filename=".concat(outFileName));
            int blockSize = 4096;
            int totalRead = 0;
            int readBytes = 0;
            byte b[] = new byte[blockSize];
            try {
                while ((long) totalRead < fileSize) {
                    readBytes = fileIn.read(b, 0, blockSize);
                    totalRead += readBytes;
                    rep.getOutputStream().write(b, 0, readBytes);
                }
                fileIn.close();
            } catch (Exception e) {
                // ???
            }
        }
    }
}

From source file:SendXml.java

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

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

    // add the .doc suffix if it doesn't already exist
    if (fileName.indexOf(".xml") == -1)
        fileName = fileName + ".xml";

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

    ServletOutputStream stream = null;//from   w w w.  j  a  v  a  2 s.  co m
    BufferedInputStream buf = null;
    try {

        stream = response.getOutputStream();
        File xml = new File(xmlDir + "/" + fileName);
        response.setContentType("text/xml");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

        response.setContentLength((int) xml.length());
        FileInputStream input = new FileInputStream(xml);
        buf = new BufferedInputStream(input);
        int readBytes = 0;
        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.krawler.formbuilder.servlet.FileDownloadServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from ww  w.  java 2  s  .c o m

        WebApplicationContext applicationContext = WebApplicationContextUtils
                .getWebApplicationContext(getServletContext());
        ModuleBuilderService moduleBuilderService = (ModuleBuilderService) applicationContext
                .getBean("moduleBuilderService");
        mb_docs docsObj = (mb_docs) moduleBuilderService.getMBDocById(mb_docs.class,
                request.getParameter("docid"));
        String src = PropsValues.STORE_PATH + request.getParameter("url");

        File fp = new File(src);
        byte[] buff = new byte[(int) fp.length()];
        FileInputStream fis = new FileInputStream(fp);
        int read = fis.read(buff);
        javax.activation.FileTypeMap mmap = new javax.activation.MimetypesFileTypeMap();
        String fileName = docsObj.getDocname();
        response.setContentType(mmap.getContentType(fp));
        response.setContentLength((int) fp.length());
        String contentDisposition = "";
        if (request.getParameter("attachment") != null) {
            contentDisposition = "attachment";
        } else {
            contentDisposition = "inline";
        }

        response.setHeader("Content-Disposition", contentDisposition + "; filename=\"" + fileName + "\";");
        response.getOutputStream().write(buff, 0, buff.length);
        response.getOutputStream().flush();
    } catch (Exception ex) {
        logger.warn("Unable To Download File :" + ex.toString(), ex);
    }

}

From source file:SendWord.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //get the 'file' parameter
    String fileName = (String) request.getParameter("file");
    if (fileName == null || fileName.equals(""))
        throw new ServletException("Invalid or non-existent file parameter in SendWord servlet.");

    // add the .doc suffix if it doesn't already exist
    if (fileName.indexOf(".doc") == -1)
        fileName = fileName + ".doc";

    String wordDir = getServletContext().getInitParameter("word-dir");
    if (wordDir == null || wordDir.equals(""))
        throw new ServletException("Invalid or non-existent wordDir context-param.");
    ServletOutputStream stream = null;//from w ww  .  j  a  v  a2 s  . co  m
    BufferedInputStream buf = null;
    try {
        stream = response.getOutputStream();
        File doc = new File(wordDir + "/" + fileName);
        response.setContentType("application/msword");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setContentLength((int) doc.length());
        FileInputStream input = new FileInputStream(doc);
        buf = new BufferedInputStream(input);
        int readBytes = 0;
        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:net.sourceforge.fenixedu.presentationTier.Action.coordinator.thesis.ManageThesisDA.java

public ActionForward printApprovalDocument(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    Thesis thesis = getThesis(request);//from ww  w  .  j av a2  s  .c  o  m

    try {
        ApproveJuryDocument document = new ApproveJuryDocument(thesis);
        byte[] data = ReportsUtils.exportToProcessedPdfAsByteArray(document);

        response.setContentLength(data.length);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition",
                String.format("attachment; filename=%s.pdf", document.getReportFileName()));
        response.getOutputStream().write(data);

        return null;
    } catch (JRException e) {
        addActionMessage("error", request, "coordinator.thesis.approved.print.failed");
        return viewSubmitted(mapping, actionForm, request, response);
    }
}

From source file:edu.wisc.web.filter.ShallowEtagHeaderFilter.java

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

    ShallowEtagResponseWrapper responseWrapper = new ShallowEtagResponseWrapper(response);
    filterChain.doFilter(request, responseWrapper);

    byte[] body = responseWrapper.toByteArray();
    int statusCode = responseWrapper.getStatusCode();

    if (isEligibleForEtag(request, responseWrapper, statusCode, body)) {
        String responseETag = generateETagHeaderValue(body);
        response.setHeader(HEADER_ETAG, responseETag);

        String requestETag = request.getHeader(HEADER_IF_NONE_MATCH);
        if (responseETag.equals(requestETag)) {
            if (logger.isTraceEnabled()) {
                logger.trace("ETag [" + responseETag + "] equal to If-None-Match, sending 304");
            }/*from   ww w .  ja va  2 s  . c om*/
            response.setContentLength(0);
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        } else {
            if (logger.isTraceEnabled()) {
                logger.trace("ETag [" + responseETag + "] not equal to If-None-Match [" + requestETag
                        + "], sending normal response");
            }
            copyBodyToResponse(body, response);
        }
    } else {
        if (logger.isTraceEnabled()) {
            logger.trace("Response with status code [" + statusCode + "] not eligible for ETag");
        }
        copyBodyToResponse(body, response);
    }
}

From source file:it.eng.spagobi.mapcatalogue.service.DetailMapModule.java

/**
 * Handle a download request of a map file. Reads the file, sends it as an http response attachment.
 * and in the end deletes the file.// w ww. j  a v a 2s .  c  o  m
 * @param request the http request
 * @param response the http response
 */
private void downloadFile(SourceBean request) throws EMFUserError, EMFInternalError {
    String binId = (String) request.getAttribute("BIN_ID");

    //download file
    try {
        if (binId == null || binId.equals("0")) {
            logger.error("Cannot get content file. The identifier is null.");
            HashMap params = new HashMap();
            params.put(AdmintoolsConstants.PAGE, DetailMapModule.MODULE_PAGE);
            throw new EMFUserError(EMFErrorSeverity.ERROR, "5030", new Vector(), params,
                    "component_mapcatalogue_messages");
        } else {
            freezeHttpResponse();
            //HttpServletRequest request = getHttpRequest();
            HttpServletResponse response = getHttpResponse();
            if (content == null) {
                content = DAOFactory.getBinContentDAO().getBinContent(new Integer(binId));
            }
            String fileName = "map.svg";
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
            response.setContentLength(content.length);
            response.getOutputStream().write(content);
            response.getOutputStream().flush();
        }

    } catch (IOException ioe) {
        logger.error("Cannot flush response" + ioe);
    }
}

From source file:com.webpagebytes.cms.utility.HttpServletToolbox.java

public void writeBodyResponseAsJson(HttpServletResponse response, String data, Map<String, String> errors) {

    try {/*from   w  w w.j  av a2  s.  c  o  m*/
        org.json.JSONObject jsonResponse = new org.json.JSONObject();
        org.json.JSONObject jsonErrors = new org.json.JSONObject();
        if (errors == null || errors.keySet().size() == 0) {
            jsonResponse.put("status", "OK");
        } else {
            jsonResponse.put("status", "FAIL");
            for (String key : errors.keySet()) {
                jsonErrors.put(key, errors.get(key));
            }
        }
        jsonResponse.put("errors", jsonErrors);
        jsonResponse.put("payload", data);
        String jsonString = jsonResponse.toString();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream writer = response.getOutputStream();
        byte[] utf8bytes = jsonString.getBytes("UTF-8");
        writer.write(utf8bytes);
        response.setContentLength(utf8bytes.length);
        writer.flush();

    } catch (Exception e) {
        try {
            String errorResponse = "{\"status\":\"FAIL\",\"payload\":\"{}\",\"errors\":{\"reason\":\"WB_UNKNOWN_ERROR\"}}";
            ServletOutputStream writer = response.getOutputStream();
            response.setContentType("application/json");
            byte[] utf8bytes = errorResponse.getBytes("UTF-8");
            response.setContentLength(utf8bytes.length);
            writer.write(utf8bytes);
            writer.flush();
        } catch (IOException ioe) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}