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:de.mpg.escidoc.pubman.viewItem.bean.FileBean.java

/**
 * Prepares the file the user wants to download
 * //from   w  w w . j a v a 2 s.  co  m
 */
public String downloadFile() {

    try {
        LoginHelper loginHelper = (LoginHelper) FacesContext.getCurrentInstance().getApplication()
                .getVariableResolver().resolveVariable(FacesContext.getCurrentInstance(), "LoginHelper");

        String fileLocation = ServiceLocator.getFrameworkUrl() + this.file.getContent();
        String filename = this.file.getName(); // Filename suggested in browser Save As dialog
        filename = filename.replace(" ", "_"); // replace empty spaces because they cannot be procesed by the http-response (filename will be cutted after the first empty space)
        String contentType = this.file.getMimeType(); // For dialog, try
        System.out.println("MIME: " + contentType);

        // application/x-download
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        response.setHeader("Content-disposition",
                "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        if (this.file.getDefaultMetadata() != null) {
            response.setContentLength(this.file.getDefaultMetadata().getSize());
        }

        response.setContentType(contentType);
        System.out.println("MIME: " + response.getContentType());

        byte[] buffer = null;
        if (this.file.getDefaultMetadata() != null) {
            try {
                GetMethod method = new GetMethod(fileLocation);
                method.setFollowRedirects(false);
                if (loginHelper.getESciDocUserHandle() != null) {
                    // downloading by account user
                    addHandleToMethod(method, loginHelper.getESciDocUserHandle());
                }

                // Execute the method with HttpClient.
                HttpClient client = new HttpClient();
                ProxyHelper.setProxy(client, fileLocation); //????
                client.executeMethod(method);
                OutputStream out = response.getOutputStream();
                InputStream input = method.getResponseBodyAsStream();
                try {
                    if (this.file.getDefaultMetadata() != null) {
                        buffer = new byte[this.file.getDefaultMetadata().getSize()];
                        int numRead;
                        long numWritten = 0;
                        while ((numRead = input.read(buffer)) != -1) {
                            out.write(buffer, 0, numRead);
                            out.flush();
                            numWritten += numRead;
                        }
                        facesContext.responseComplete();
                    }
                } catch (IOException e1) {
                    logger.debug("Download IO Error: " + e1.toString());
                }
                input.close();
                out.close();
            } catch (FileNotFoundException e) {
                logger.debug("File not found: " + e.toString());
            }
        }
    } catch (Exception e) {
        logger.debug("File Download Error: " + e.toString());
        System.out.println(e.toString());
    }
    return null;
}

From source file:com.janrain.backplane.server.Backplane1Controller.java

@RequestMapping(value = "/admin", method = { RequestMethod.GET, RequestMethod.HEAD })
public ModelAndView admin(HttpServletRequest request, HttpServletResponse response) {

    ServletUtil.checkSecure(request);/*from  w ww  .j  a  v  a  2 s .  c  o m*/
    boolean adminUserExists = true;

    // check to see if an admin record already exists, if it does, do not allow an update
    User admin = DaoFactory.getAdminDAO().get(BackplaneSystemProps.ADMIN_USER);
    if (admin == null) {
        adminUserExists = false;
    }

    if (RequestMethod.HEAD.toString().equals(request.getMethod())) {
        response.setContentLength(0);
    }

    BpServerConfig bpServerConfig = DaoFactory.getConfigDAO().get(BackplaneSystemProps.BPSERVER_CONFIG_KEY);
    if (bpServerConfig == null) {
        bpServerConfig = new BpServerConfig();
    }
    // add it to the L1 cache
    CachedL1.getInstance().setObject(BackplaneSystemProps.BPSERVER_CONFIG_KEY, -1, bpServerConfig);

    ModelAndView view = new ModelAndView("admin");
    view.addObject("adminUserExists", adminUserExists);
    view.addObject("configKey", bpServerConfig.getIdValue());
    view.addObject("debugMode", bpConfig.isDebugMode());
    view.addObject("defaultMessagesMax", bpServerConfig.get(BpServerConfig.Field.DEFAULT_MESSAGES_MAX));

    return view;
}

From source file:de.mpg.mpdl.inge.pubman.web.viewItem.bean.FileBean.java

/**
 * Prepares the file the user wants to download
 * /* ww w .  j  a  v  a2s  .co m*/
 */
public String downloadFile() {

    try {
        LoginHelper loginHelper = (LoginHelper) FacesContext.getCurrentInstance().getApplication()
                .getVariableResolver().resolveVariable(FacesContext.getCurrentInstance(), "LoginHelper");

        String fileLocation = PropertyReader.getFrameworkUrl() + this.file.getContent();
        String filename = this.file.getName(); // Filename suggested in browser Save As dialog
        filename = filename.replace(" ", "_"); // replace empty spaces because they cannot be procesed
                                               // by the http-response (filename will be cutted after
                                               // the first empty space)
        String contentType = this.file.getMimeType(); // For dialog, try
        System.out.println("MIME: " + contentType);

        // application/x-download
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        response.setHeader("Content-disposition",
                "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        if (this.file.getDefaultMetadata() != null) {
            response.setContentLength(this.file.getDefaultMetadata().getSize());
        }

        response.setContentType(contentType);
        System.out.println("MIME: " + response.getContentType());

        byte[] buffer = null;
        if (this.file.getDefaultMetadata() != null) {
            try {
                GetMethod method = new GetMethod(fileLocation);
                method.setFollowRedirects(false);
                if (loginHelper.getESciDocUserHandle() != null) {
                    // downloading by account user
                    addHandleToMethod(method, loginHelper.getESciDocUserHandle());
                }

                // Execute the method with HttpClient.
                HttpClient client = new HttpClient();
                ProxyHelper.setProxy(client, fileLocation); // ????
                client.executeMethod(method);
                OutputStream out = response.getOutputStream();
                InputStream input = method.getResponseBodyAsStream();
                try {
                    if (this.file.getDefaultMetadata() != null) {
                        buffer = new byte[this.file.getDefaultMetadata().getSize()];
                        int numRead;
                        long numWritten = 0;
                        while ((numRead = input.read(buffer)) != -1) {
                            out.write(buffer, 0, numRead);
                            out.flush();
                            numWritten += numRead;
                        }
                        facesContext.responseComplete();
                    }
                } catch (IOException e1) {
                    logger.debug("Download IO Error: " + e1.toString());
                }
                input.close();
                out.close();
            } catch (FileNotFoundException e) {
                logger.debug("File not found: " + e.toString());
            }
        }
    } catch (Exception e) {
        logger.debug("File Download Error: " + e.toString());
        System.out.println(e.toString());
    }
    return null;
}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

public void handleGet(RequestContext context) throws ServletException, IOException {
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();
    if (request.getParameter("download") != null) {
        byte[] conf = (byte[]) request.getSession().getAttribute(SESSION_CONFIGURATION);
        if (conf == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "No configuration available for download");
            return;
        }//from w  w w . ja  v  a2s.  c  o m
        response.setContentType("application/octet-stream");
        response.setContentLength(conf.length);
        response.addHeader("Content-disposition", "attachment; filename=oiosaml.java-config.zip");
        response.getOutputStream().write(conf);
        return;
    }
    if (!checkConfiguration(response))
        return;

    Map<String, Object> params = getStandardParameters(request);

    String res = renderTemplate("configure.vm", params, true);
    sendResponse(response, res);
}

From source file:com.scooter1556.sms.server.service.AdaptiveStreamingService.java

public void sendSubtitleSegment(HttpServletResponse response) throws IOException {
    List<String> segment = new ArrayList<>();
    segment.add("WEBVTT");

    // Write segment to buffer so we can get the content length
    StringWriter segmentWriter = new StringWriter();
    for (String line : segment) {
        segmentWriter.write(line + "\n");
    }/*from w ww .ja  v a  2  s. c om*/

    // Set Header Parameters
    response.reset();
    response.setContentType("text/vtt");
    response.setContentLength(segmentWriter.toString().length());

    // Enable CORS
    response.setHeader(("Access-Control-Allow-Origin"), "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setIntHeader("Access-Control-Max-Age", 3600);

    // Write segment out to the client
    response.getWriter().write(segmentWriter.toString());
}

From source file:nz.net.orcon.kanban.controllers.XmlFileController.java

private void generateXml(HttpServletResponse response, String boardId, Collection<Card> cardList)
        throws Exception {
    String xmlFileName = boardId + "-" + Calendar.getInstance().getTime() + ".xml";
    HashMap<String, String> aliases = new HashMap<String, String>();
    aliases.put("Card", "nz.net.orcon.kanban.model.Card");
    xstreamMarshaller.setAliases(aliases);
    XStream xStream = xstreamMarshaller.getXStream();
    xStream.registerConverter(new CardConverter());

    StringBuffer xmlCards = new StringBuffer();
    xmlCards.append("<Cards> \n");
    for (Card card : cardList) {
        xmlCards.append(xStream.toXML(card));
        xmlCards.append("\n");
    }/*  www.ja  va2  s.com*/
    xmlCards.append("</Cards>");

    InputStream in = new ByteArrayInputStream(xmlCards.toString().getBytes("UTF-8"));
    ServletOutputStream out = response.getOutputStream();
    response.setContentLength(xmlCards.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + xmlFileName + "\"");

    byte[] outputByte = new byte[4096];
    //copy binary content to output stream
    while (in.read(outputByte, 0, 4096) != -1) {
        out.write(outputByte, 0, 4096);
    }
    in.close();
    out.flush();
    out.close();
}

From source file:be.fedict.eid.applet.service.KmlServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");

    HttpSession httpSession = request.getSession();
    EIdData eIdData = (EIdData) httpSession.getAttribute("eid");

    byte[] document;
    try {//from   w w  w . j a  v  a2  s.  c o  m
        document = this.kmlGenerator.generateKml(eIdData);
    } catch (IOException e) {
        throw new ServletException("KML generator error: " + e.getMessage(), e);
    }

    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    if (false == request.getScheme().equals("https")) {
        // else the download fails in IE
        response.setHeader("Pragma", "no-cache"); // http 1.0
    } else {
        response.setHeader("Pragma", "public");
    }
    response.setDateHeader("Expires", -1);
    response.setHeader("Content-disposition", "attachment");
    response.setContentLength(document.length);

    response.setContentType(KmlLight.MIME_TYPE);
    response.setContentLength(document.length);
    ServletOutputStream out = response.getOutputStream();
    out.write(document);
    out.flush();
}

From source file:cpabe.controladores.UploadDecriptacaoServlet.java

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

    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("O nome do arquivo no pode ser null ou vazio.");
    }//from   w  w w  . j  ava  2s .c o  m
    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
    if (!file.exists()) {
        throw new ServletException("O arquivo desejado no existe no Servidor.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while ((read = fis.read(bufferData)) != -1) {
        os.write(bufferData, 0, read);
    }
    os.flush();
    os.close();
    fis.close();
    System.out.println("File downloaded at client successfully");
}

From source file:alpha.portal.webapp.controller.CardFormController.java

/**
 * Gets the payload.//from  w  w w .  j a v  a2  s .  c o m
 * 
 * @param jspCard
 *            the jsp card
 * @param response
 *            the response
 * @return the payload
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@RequestMapping(method = RequestMethod.POST, params = { "payloadGet" })
public String getPayload(final AlphaCard jspCard, final HttpServletResponse response) throws IOException {
    final AlphaCard alphaCard = this.alphaCardManager.get(jspCard.getAlphaCardIdentifier());
    final Payload payload = alphaCard.getPayload();

    if (payload != null) {

        final BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(payload.getContent()));

        response.setBufferSize(payload.getContent().length);
        response.setContentType(payload.getMimeType());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + payload.getFilename() + "\"");
        response.setContentLength(payload.getContent().length);

        FileCopyUtils.copy(in, response.getOutputStream());
        in.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    final AlphaCardIdentifier identifier = alphaCard.getAlphaCardIdentifier();
    return "redirect:/caseform?caseId=" + identifier.getCaseId() + "&activeCardId=" + identifier.getCardId();
}