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.unirostock.sems.cbarchive.web.servlet.IconServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    // set charset
    response.setCharacterEncoding(Fields.CHARSET);
    request.setCharacterEncoding(Fields.CHARSET);

    // splitting request URL
    String requestUrl = request.getRequestURI();
    LOGGER.debug("IconServlet request: ", requestUrl);

    if (requestUrl != null && !requestUrl.isEmpty()) {

        String formatString = null;
        try {//from ww w.  j a v  a 2  s .  co  m
            response.setContentType("image/png");

            formatString = requestUrl.substring(requestUrl.indexOf("res/icon/") + 9);
            LOGGER.debug("format: ", formatString);

            URI format = new URI(formatString);
            LOGGER.debug("format url: ", format);
            OutputStream output = response.getOutputStream();

            InputStream input = Iconizer.formatToIconStream(format);
            int size = IOUtils.copy(input, output);
            response.setContentLength(size);

            output.flush();
            output.close();
            input.close();

            response.flushBuffer();

        } catch (IOException e) {
            LOGGER.error(e, "IOException while loading icon");
        } catch (URISyntaxException e) {
            LOGGER.warn(e, "Not able to generate URL for Iconizer: ", formatString);
        }

    }

}

From source file:cc.kune.core.server.manager.file.EntityBackgroundDownloadManager.java

/**
 * Builds the response.//  w w w . ja va2 s . c om
 *
 * @param statetoken
 *          the statetoken
 * @param filename
 *          the filename
 * @param mimeType
 *          the mime type
 * @param imgsize
 *          the imgsize
 * @param resp
 *          the resp
 * @return the string
 * @throws FileNotFoundException
 *           the file not found exception
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
String buildResponse(final StateToken statetoken, final String filename, final String mimeType,
        final ImageSize imgsize, final HttpServletResponse resp) throws FileNotFoundException, IOException {
    final String absDir = kuneProperties.get(KuneProperties.UPLOAD_LOCATION)
            + FileUtils.groupToDir(statetoken.getGroup());
    String absFilename = absDir + filename;

    if (imgsize != null) {
        final String imgsizePrefix = "." + imgsize;
        final String extension = FileUtils.getFileNameExtension(filename, true);
        final String filenameWithoutExtension = FileUtils.getFileNameWithoutExtension(filename, extension);
        final String filenameResized = filenameWithoutExtension + imgsizePrefix + extension;
        if (fileUtils.exist(absDir + filenameResized)) {
            absFilename = absDir + filenameResized;
        }
    }

    final File file = new File(absFilename);
    lastModified = file.lastModified();

    resp.setContentLength((int) file.length());

    if (mimeType != null) {
        final String contentType = mimeType.toString();
        resp.setContentType(contentType);
        LOG.info("Content type returned: " + contentType);
    }

    resp.setHeader(RESP_HEADER_CONTEND_DISP, RESP_HEADER_ATTACHMENT_FILENAME + filename + RESP_HEADER_END);
    CacheUtils.setCache1Day(resp);
    return absFilename;
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 * Apache HttpClient./*from ww w  .  j a  va  2s  .c o m*/
 */

private void fetchContentByApacheHttpClient(HttpServletResponse response, String contentUrl)
        throws IOException {
    // ?
    HttpGet httpGet = new HttpGet(contentUrl);
    CloseableHttpResponse remoteResponse = httpClient.execute(httpGet);
    try {
        // 
        int statusCode = remoteResponse.getStatusLine().getStatusCode();
        if (statusCode >= 400) {
            response.sendError(statusCode, "fetch image error from " + contentUrl);
            return;
        }

        HttpEntity entity = remoteResponse.getEntity();

        // Header
        response.setContentType(entity.getContentType().getValue());
        if (entity.getContentLength() > 0) {
            response.setContentLength((int) entity.getContentLength());
        }
        // 
        InputStream input = entity.getContent();
        OutputStream output = response.getOutputStream();
        // byte?InputStreamOutputStream, ?4k.
        IOUtils.copy(input, output);
        output.flush();
    } finally {
        remoteResponse.close();
    }
}

From source file:com.lushapp.common.web.servlet.RemoteContentServlet.java

/**
 * HttpClient?.// www . j ava  2  s.c o m
 */
private void fetchContentByApacheHttpClient(HttpServletResponse response, String contentUrl)
        throws IOException {

    // ?
    HttpEntity entity = null;
    HttpGet httpGet = new HttpGet(contentUrl);
    try {
        HttpContext context = new BasicHttpContext();
        HttpResponse remoteResponse = httpClient.execute(httpGet, context);
        entity = remoteResponse.getEntity();
    } catch (Exception e) {
        logger.error("fetch remote content" + contentUrl + "  error", e);
        httpGet.abort();
        return;
    }

    // 404
    if (entity == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, contentUrl + " is not found.");
        return;
    }

    // Header
    response.setContentType(entity.getContentType().getValue());
    if (entity.getContentLength() > 0) {
        response.setContentLength((int) entity.getContentLength());
    }

    // 
    InputStream input = entity.getContent();
    OutputStream output = response.getOutputStream();
    try {
        // byte?InputStreamOutputStream, ?4k.
        IOUtils.copy(input, output);
        output.flush();
    } finally {
        // ??InputStream.
        IOUtils.closeQuietly(input);
    }

}

From source file:es.sm2.openppm.front.servlets.AbstractGenericServlet.java

/**
 * Send file//from   w  w  w .  j a  v a2  s.co m
 * 
 * @param req
 * @param resp
 * @param file
 * @param fileName
 * @param contentType
 * @throws ServletException
 * @throws IOException
 */
protected void sendFile(HttpServletRequest req, HttpServletResponse resp, byte[] file, String fileName,
        String contentType) throws ServletException, IOException {

    resp.setContentType(contentType);
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    resp.setContentLength(file.length);

    ByteArrayInputStream bais = new ByteArrayInputStream(file);
    OutputStream outs = resp.getOutputStream();

    int start = 0;
    int length = 4 * 1024; // Buffer 4KB
    byte[] buff = new byte[length];

    while (bais.read(buff, start, length) != -1) {
        outs.write(buff, start, length);
    }

    bais.close();
}

From source file:org.openmrs.module.sync.web.controller.ImportListController.java

private void sendCloneResponse(String content, HttpServletResponse response, boolean isUpload)
        throws Exception {

    boolean useCompression = Boolean.parseBoolean(Context.getAdministrationService()
            .getGlobalProperty(SyncConstants.PROPERTY_ENABLE_COMPRESSION, "true"));
    log.debug("Global property sychronization.enable_compression = " + useCompression);

    // Otherwise, all other requests are compressed and sent back to the
    // client//from  www .j  av  a 2 s .c  om
    ConnectionRequest syncRequest = new ConnectionRequest(content, useCompression);
    log.info("Compressed content length: " + syncRequest.getContentLength());
    log.info("Compression Checksum: " + syncRequest.getChecksum());

    response.setContentLength((int) syncRequest.getContentLength());
    response.addHeader("Enable-Compression", String.valueOf(useCompression));
    response.addHeader("Content-Checksum", String.valueOf(syncRequest.getChecksum()));
    response.addHeader("Content-Encoding", "gzip");

    // Write compressed sync data to response
    InputStream in = new ByteArrayInputStream(syncRequest.getBytes());
    IOUtils.copy(in, response.getOutputStream());

    return;

}

From source file:net.sf.jsog.spring.JsogView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // This is the string that will ultimately be rendered.
    String responseString;/*w w  w.j  a v  a 2s . c  o m*/

    // Build the result object
    JSOG result;
    if ((model.size() == 1 || model.size() == 2) && model.containsKey("JSOG")) {
        result = (JSOG) model.get("JSOG");
    } else {
        result = modelToJsog(model);
    }

    // If the JSONP callback parameter is specified, grab it
    String callback = request.getParameter(jsonpCallbackParam);
    if (callback != null) {
        responseString = callback + "(" + result.toString() + ")";
    } else {
        responseString = result.toString();
    }

    // Setup the response
    byte[] responseBytes = responseString.getBytes(encoding);
    response.setContentType(outputContentType.toString());
    response.setCharacterEncoding(encoding.name());
    response.setContentLength(responseBytes.length);

    // Write the response
    OutputStream out = response.getOutputStream();
    out.write(responseBytes);
    out.flush();
    out.close();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.administrativeOffice.payments.ReceiptsManagementDA.java

public ActionForward printReceipt(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws IOException, JRException {

    final Receipt receipt = getRenderedObject("receipt");
    try {/*www  . ja va  2 s.co  m*/

        final ReceiptDocument original = new ReceiptDocument(receipt, getMessageResourceProvider(request),
                true);
        final ReceiptDocument duplicate = new ReceiptDocument(receipt, getMessageResourceProvider(request),
                false);

        final byte[] data = ReportsUtils.exportMultipleToPdfAsByteArray(original, duplicate);

        ReceiptGeneratedDocument.store(receipt, original.getReportFileName() + ".pdf", data);

        RegisterReceiptPrint.run(receipt, getUserView(request).getPerson());

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

        response.getOutputStream().write(data);

        return null;

    } catch (DomainException e) {
        addActionMessage(request, e.getKey(), e.getArgs());

        request.setAttribute("personId", receipt.getPerson().getExternalId());
        request.setAttribute("receiptID", receipt.getExternalId());

        return prepareShowReceipt(mapping, actionForm, request, response);
    }

}

From source file:com.jadyounan.Packager.java

/**
 * Servlet handler , should listen on the callback URL (as in webServiceURL)
 * @param requestPath//from   w ww  . j  av  a2 s.  co m
 * @param req
 * @param servletRequest
 * @param servletResponse
 * @throws Exception
 */
public static void handle(String requestPath, Request req, HttpServletRequest servletRequest,
        HttpServletResponse servletResponse) throws Exception {

    StringTokenizer st = new StringTokenizer(requestPath, "/");
    st.nextToken();
    String companyDomain = st.nextToken();

    String version = st.nextToken();

    byte bytes[] = new byte[] {};

    switch (st.nextToken().toLowerCase()) {
    case "log": {
        bytes = new byte[] {};

        byte r[] = org.eclipse.jetty.util.IO.readBytes(servletRequest.getInputStream());

        System.out.println("LOG " + new String(r));
    }
        break;
    case "devices": {
        String deviceID = st.nextToken();

        String authToken = req.getHeader("Authorization").split(" ")[1];

        // use the authToken to get the userID who started the request

        switch (servletRequest.getMethod().toUpperCase()) {
        case "DELETE":
            //handle deleting the token from your database
            break;
        default: {
            //handle adding the token/deviceID to your database
        }
            break;
        }

        FLUSH.updatePushDevices(userID);

        bytes = new byte[] {};
    }
        break;
    case "pushpackages": {
        /**
         * Safari requests the pacakge
         */
        String id = st.nextToken();

        JSONObject obj = new JSONObject(
                new String(org.eclipse.jetty.util.IO.readBytes(servletRequest.getInputStream())));

        String userID = obj.getString("user_id");

        String authenticationToken = "..a random string so you can later identify the user who started the request";

        bytes = createPackageFile(authenticationToken);
    }
        break;
    default:
        bytes = new byte[] {};
        break;
    }

    servletResponse.setStatus(200);
    servletResponse.setContentLength(bytes.length);
    try (OutputStream out = servletResponse.getOutputStream()) {
        out.write(bytes);
        out.flush();
    }
}