Example usage for javax.servlet.http HttpServletResponse setContentType

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

Introduction

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

Prototype


public void setContentType(String type);

Source Link

Document

Sets the content type of the response being sent to the client, if the response has not been committed yet.

Usage

From source file:edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions.java

public static void handleMalformedParameters(String errorMessage, HttpServletResponse response, Log log)
        throws IOException {

    GenericQueryMap errorDataResponse = new GenericQueryMap();
    errorDataResponse.addEntry("error", errorMessage);

    Gson jsonErrorResponse = new Gson();

    response.setContentType("application/octet-stream");
    response.getWriter().write(jsonErrorResponse.toJson(errorDataResponse));
}

From source file:com.jaspersoft.jasperserver.rest.RESTUtils.java

public static void sendFile(DataSource ds, HttpServletResponse response) {
    response.setContentType(ds.getContentType());

    if (ds.getName() != null && ds.getName().length() > 0) {
        response.addHeader("Content-Disposition", "attachment; filename=" + ds.getName());
    }/*from  w ww  .j a va  2  s .  c om*/

    OutputStream outputStream = null;
    BufferedInputStream bufferedInputStream = null;
    try {
        outputStream = response.getOutputStream();

        bufferedInputStream = new BufferedInputStream(ds.getInputStream());
        int readBytes = 0;

        while ((readBytes = bufferedInputStream.read()) != -1) {
            outputStream.write(readBytes);
        }

        if (log.isDebugEnabled()) {
            log.debug("finished sending bytes");
        }

    } catch (IOException ex) {
        log.error("Error serving a file: " + ex.getMessage(), ex);
    } finally {
        if (outputStream != null)
            try {
                outputStream.close();
            } catch (Exception ex) {
            }
        if (bufferedInputStream != null)
            try {
                bufferedInputStream.close();
            } catch (Exception ex) {
            }
    }
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Usuario.Read.java

protected static void isInscritoTaller(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    boolean b = CtrlUsuario.isInscritoTaller(Integer.parseInt(request.getParameter("1")),
            Integer.parseInt(request.getParameter("2")));
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    JSONObject obj = new JSONObject();
    obj.put("is", b);
    out.print(obj);/*from  www .  j  ava 2 s.c o m*/
}

From source file:net.sourceforge.fenixedu.presentationTier.servlets.filters.JerseyOAuth2Filter.java

private static boolean sendError(final HttpServletResponse response, String error, String errorDescription)
        throws IOException, ServletException {
    OAuthResponse errorResponse;/* w  ww.j  av a2  s.co  m*/
    try {
        errorResponse = new OAuthErrorResponseBuilder(401).setError(error).setErrorDescription(errorDescription)
                .buildJSONMessage();
        response.setContentType("application/json; charset=UTF-8");
        response.setStatus(errorResponse.getResponseStatus());
        PrintWriter pw = response.getWriter();
        pw.print(errorResponse.getBody());
        return false;
    } catch (OAuthSystemException e) {
        throw new ServletException(e);
    }
}

From source file:gov.nist.appvet.tool.synchtest.util.ReportUtil.java

/**
 * This method returns report information to the AppVet ToolAdapter as ASCII
 * text and cannot attach a file to the response.
 *///  w ww  .  j a v  a  2s .  c  om
public static boolean sendPDFInHttpResponse(HttpServletResponse response, String reportText,
        ToolStatus reportStatus) {
    try {
        File reportFile = new File(reportFilePath);
        String mimeType = new MimetypesFileTypeMap().getContentType(reportFile);
        log.debug("Sending mimetype: " + mimeType);
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", "attachment;filename=" + reportFile.getName());
        response.setStatus(HttpServletResponse.SC_OK); // HTTP 200
        response.setHeader("apprisk", reportStatus.name());

        FileInputStream inputStream = new FileInputStream(reportFile); //read the file

        try {
            int c;
            while ((c = inputStream.read()) != -1) {
                response.getWriter().write(c);
            }
        } finally {
            if (inputStream != null)
                inputStream.close();
            response.getWriter().close();
        }

        //         PrintWriter out = response.getWriter();
        //         out.println(reportText);
        //         out.flush();
        //         out.close();
        log.info("Returned report");
        return true;
    } catch (IOException e) {
        log.error("Report not sent: " + e.toString());
        return false;
    }
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Usuario.Read.java

protected static void isInscritoconvocatoria(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    boolean b = CtrlUsuario.isInscritoconvocatoria(Integer.parseInt(request.getParameter("1")),
            Integer.parseInt(request.getParameter("2")));
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    JSONObject obj = new JSONObject();
    obj.put("is", b);
    out.print(obj);//ww w  .j  ava2 s  .c  o  m
}

From source file:org.openmrs.module.omodexport.util.OmodExportUtil.java

/**
 * Utility method for exporting a set of selected modules. The select modules will be exported
 * in zip file called "modules.zip"//w  ww  .j  a  v a  2 s.  c om
 * 
 * @param moduleId -Dash-separated list of the module Ids
 * @param response
 * @throws IOException
 */
public static void exportSelectedModules(String moduleId, HttpServletResponse response) throws IOException {
    // Split the id string into an array of id's
    String[] moduleIds = moduleId.split("-");
    List<File> files = new ArrayList<File>();
    for (String mId : moduleIds) {
        Module m = ModuleFactory.getModuleById(mId);
        files.add(m.getFile());
    }
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=\"modules.ZIP\"");

    ZipOutputStream out = new ZipOutputStream(response.getOutputStream());

    zipFiles(files, out);
}

From source file:org.openmrs.module.omodexport.util.OmodExportUtil.java

/**
 * Utility method for exporting a module with its dependencies
 * //from   w w  w . j a  va2 s .  c  om
 * @param module -The module to export. It will be exported with all its dependencies and
 *            compressed in a file called "modules.zip"
 * @param response
 * @throws IOException
 */
public static void exportModuleWithDependecies(Module module, HttpServletResponse response) throws IOException {
    List<File> files = new ArrayList<File>();
    List<String> dependecies = module.getRequiredModules();
    for (String name : dependecies) {
        Module m = ModuleFactory.getModuleByPackage(name);
        files.add(m.getFile());
    }
    files.add(module.getFile());

    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=\"modules.ZIP\"");

    ZipOutputStream out = new ZipOutputStream(response.getOutputStream());

    zipFiles(files, out);
}

From source file:ch.rasc.downloadchart.DownloadChartServlet.java

private static void handlePdf(HttpServletResponse response, byte[] imageData, Integer width, Integer height,
        String filename, PdfOptions options) throws IOException {

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".pdf\";");

    try (PDDocument document = new PDDocument()) {
        PDRectangle format = PDPage.PAGE_SIZE_A4;
        if (options != null) {
            if ("A3".equals(options.format)) {
                format = PDPage.PAGE_SIZE_A3;
            } else if ("A5".equals(options.format)) {
                format = PDPage.PAGE_SIZE_A5;
            } else if ("Letter".equals(options.format)) {
                format = PDPage.PAGE_SIZE_LETTER;
            } else if ("Legal".equals(options.format)) {
                format = new PDRectangle(215.9f * MM_TO_UNITS, 355.6f * MM_TO_UNITS);
            } else if ("Tabloid".equals(options.format)) {
                format = new PDRectangle(279 * MM_TO_UNITS, 432 * MM_TO_UNITS);
            } else if (options.width != null && options.height != null) {
                Float pdfWidth = convertToPixel(options.width);
                Float pdfHeight = convertToPixel(options.height);
                if (pdfWidth != null && pdfHeight != null) {
                    format = new PDRectangle(pdfWidth, pdfHeight);
                }/*from w  w w.j a va2s.  c o  m*/
            }
        }

        PDPage page = new PDPage(format);

        if (options != null && "landscape".equals(options.orientation)) {
            page.setRotation(90);
        }

        document.addPage(page);

        BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));

        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {

            PDPixelMap ximage = new PDPixelMap(document, originalImage);

            Dimension newDimension = calculateDimension(originalImage, width, height);
            int imgWidth = ximage.getWidth();
            int imgHeight = ximage.getHeight();
            if (newDimension != null) {
                imgWidth = newDimension.width;
                imgHeight = newDimension.height;
            }

            Float border = options != null ? convertToPixel(options.border) : null;
            if (border == null) {
                border = 0.0f;
            }

            AffineTransform transform;

            if (page.getRotation() == null) {
                float scale = (page.getMediaBox().getWidth() - border * 2) / imgWidth;
                if (scale < 1.0) {
                    transform = new AffineTransform(imgWidth, 0, 0, imgHeight, border,
                            page.getMediaBox().getHeight() - border - imgHeight * scale);

                    transform.scale(scale, scale);
                } else {
                    transform = new AffineTransform(imgWidth, 0, 0, imgHeight, border,
                            page.getMediaBox().getHeight() - border - imgHeight);
                }

            } else {
                float scale = (page.getMediaBox().getHeight() - border * 2) / imgWidth;
                if (scale < 1.0) {
                    transform = new AffineTransform(imgHeight, 0, 0, imgWidth, imgHeight * scale + border,
                            border);

                    transform.scale(scale, scale);
                } else {
                    transform = new AffineTransform(imgHeight, 0, 0, imgWidth, imgHeight + border, border);
                }

                transform.rotate(1.0 * Math.PI / 2.0);
            }

            contentStream.drawXObject(ximage, transform);

        }

        try {
            document.save(response.getOutputStream());
        } catch (COSVisitorException e) {
            throw new IOException(e);
        }
    }
}

From source file:ee.ria.xroad.common.request.DummyCentralServiceHandler.java

private static void sendErrorResponse(HttpServletResponse response, String faultCode, String faultString,
        String faultActor, String faultDetail) throws IOException {
    String soapMessageXml = SoapFault.createFaultXml(faultCode, faultString, faultActor, faultDetail);

    String encoding = StandardCharsets.UTF_8.name();
    byte[] messageBytes = soapMessageXml.getBytes(encoding);

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(MimeTypes.TEXT_XML);
    response.setContentLength(messageBytes.length);
    response.setHeader("SOAPAction", "");
    response.setCharacterEncoding(encoding);
    response.getOutputStream().write(messageBytes);
}