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:org.nsesa.editor.gwt.an.amendments.server.service.WordExportService.java

@Override
public void export(AmendmentContainerDTO object, HttpServletResponse response) throws IOException {

    response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    response.setHeader("Content-Disposition",
            "attachment;filename=" + object.getAmendmentContainerID() + ".docx");
    response.setCharacterEncoding("UTF8");

    final String content = object.getBody();
    final InputSource inputSource;
    inputSource = new InputSource(new StringReader(content));

    try {/*w ww .  jav a  2s . c o m*/

        final NodeModel model = NodeModel.parse(inputSource);
        final Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
        configuration.setDirectoryForTemplateLoading(template.getFile().getParentFile());
        final StringWriter sw = new StringWriter();
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("amendment", model);
        configuration.getTemplate(template.getFile().getName()).process(root, sw);
        byte[] bytes = sw.toString().getBytes("utf-8");
        IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
        response.setContentLength(sw.toString().length());
        response.flushBuffer();
    } catch (IOException e) {
        throw new RuntimeException("Could not read file.", e);
    } catch (SAXException e) {
        throw new RuntimeException("Could not parse file.", e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Could not parse file.", e);
    } catch (TemplateException e) {
        throw new RuntimeException("Could not load template.", e);
    }
}

From source file:com.actionbazaar.image.ImageServlet.java

/**
 * Retrieves the specified image//from  w w w. ja va 2s . c  om
 * @param req - request
 * @param resp - response
 * @throws ServletException - thrown if there is an error
 * @throws IOException - another exception
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("image/png");
    OutputStream outStream;
    outStream = resp.getOutputStream();
    InputStream is;
    String name = req.getParameter("name");
    if (name == null) {
        is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png");
    } else {
        ImageRecord imageRecord = imageBean.getFile(name);
        if (imageRecord != null) {
            is = new BufferedInputStream(new FileInputStream(imageRecord.getThumbnailFile()));
        } else {
            is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png");
        }
    }
    IOUtils.copy(is, outStream);
    outStream.close();
    outStream.flush();
}

From source file:am.ik.categolj2.app.feed.RssEntryFeedView.java

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

    response.setContentType(getContentType());

    SyndFeed feed = new SyndFeedImpl();
    feed.setTitle(feedTitle);/*w w w .j av  a 2s.c o m*/
    feed.setEncoding("UTF-8");
    feed.setLink(feedLink);
    feed.setPublishedDate(new Date());
    feed.setDescription(feedDescription);
    feed.setFeedType("rss_2.0");

    FeedEntries entries = (FeedEntries) model.get("entries");
    List<SyndEntry> feedEntries = entries.getEntries().stream().map(e -> {
        SyndContent description = new SyndContentImpl();
        EntryFormat format = EntryFormat.valueOf(e.getFormat().toUpperCase());
        description.setValue("<![CDATA[" + format.format(e.getContents()) + "]]>");
        description.setType("text/html");

        SyndEntry entry = new SyndEntryImpl();
        entry.setTitle(e.getTitle());
        entry.setLink(feed.getLink() + "#entries/" + e.getId());
        entry.setPublishedDate(e.getCreatedDate().toDate());
        entry.setUpdatedDate(e.getLastModifiedDate().toDate());
        entry.setDescription(description);
        return entry;
    }).collect(Collectors.toList());
    feed.setEntries(feedEntries);

    CustomizedWireFeedOutput feedOutput = new CustomizedWireFeedOutput();
    ServletOutputStream out = response.getOutputStream();
    feedOutput.output(feed.createWireFeed(), new OutputStreamWriter(out, feed.getEncoding()), true);
}

From source file:controllers.ColorGroupController.java

@RequestMapping("/getXls")
public void getXls(Map<String, Object> model, HttpServletResponse response) throws Exception {
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=ColorGroup.xls");
    colorGroupService.getXls().write(response.getOutputStream());
}

From source file:org.iti.agrimarket.service.ImageController.java

/**
 * Image getter service//from   w w  w. j  a  va 2s.  co m
 *
 * @param name image file's name
 * @param response to control its type
 * @return image
 */
@RequestMapping(value = Constants.IMAGE_PRE_URL + Constants.TYPE_NAME_URL, method = RequestMethod.GET)
@ResponseBody
public byte[] getImage(@PathVariable(Constants.TYPE_PARAM) String type,
        @PathVariable(Constants.NAME_PARAM) String name, HttpServletResponse response) {

    response.setContentType(CONTENT_IMAGES);
    File file;
    byte arr[] = {};
    try {
        file = new File(Constants.IMAGE_PATH + type + "/" + name);
        if (file.isFile()) {

            logger.trace(FILE_EXISTS);
        } else {
            logger.trace(FILE_NOT_EXIST);
            response.setContentType(CONTENT_HTML);
            response.setStatus(Constants.PARAM_ERROR);
            return null;
        }
        arr = new byte[(int) file.length()];

        FileInputStream fis = new FileInputStream(file);
        fis.read(arr, 0, arr.length);
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    return arr;
}

From source file:org.iti.agrimarket.service.ImageController.java

/**
 * Image getter service/*from  w ww. jav  a2  s. c  o m*/
 *
 * @param name image file's name
 * @param response to control its type
 * @return image
 */
@RequestMapping(value = Constants.SOUND_PRE_URL + Constants.TYPE_NAME_URL, method = RequestMethod.GET)
@ResponseBody
public byte[] getSound(@PathVariable(Constants.TYPE_PARAM) String type,
        @PathVariable(Constants.NAME_PARAM) String name, HttpServletResponse response) {

    response.setContentType(CONTENT_FILE);
    File file;
    byte arr[] = {};
    try {
        file = new File(Constants.SOUND_PATH + type + "/" + name);
        if (file.isFile()) {

            logger.trace(FILE_EXISTS);
        } else {
            logger.trace(FILE_NOT_EXIST + file.getAbsolutePath());
            response.setContentType(CONTENT_HTML);
            response.setStatus(Constants.PARAM_ERROR);
            return null;
        }
        arr = new byte[(int) file.length()];

        FileInputStream fis = new FileInputStream(file);
        fis.read(arr, 0, arr.length);
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    return arr;
}

From source file:org.terasoluna.gfw.functionaltest.app.download.TextFileDownloadView.java

@Override
protected void addResponseHeader(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) {
    response.setHeader("Content-Disposition", "attachment; filename=framework.txt");
    response.setContentType("text/plain");
}

From source file:com.skcraft.launcher.creator.server.PackagesHandler.java

public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/plain; charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);

    List<ManifestInfo> packages = Lists.newArrayList();
    PackageList packageList = new PackageList();
    packageList.setPackages(packages);//from   w  w w  .ja v a2  s.c om

    File[] files = baseDir.listFiles(new PackageFileFilter());
    if (files != null) {
        for (File file : files) {
            Manifest manifest = mapper.readValue(file, Manifest.class);
            ManifestInfo info = new ManifestInfo();
            info.setName(manifest.getName());
            info.setTitle(manifest.getTitle());
            info.setVersion(manifest.getVersion());
            info.setLocation(file.getName());
            packages.add(info);
        }
    }

    mapper.writeValue(response.getWriter(), packageList);
    baseRequest.setHandled(true);
}

From source file:de.devbliss.apitester.dummyserver.DummyRequestHandler.java

private void handleException(Exception e, HttpServletResponse response) throws IOException {
    response.setContentType(CONTENT_TYPE_ERROR);
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    response.getWriter().write("exception type: " + e.getClass());
    response.getWriter().write(e.getMessage());
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.IndividualListRdfController.java

private void sendEmptyModel(RdfResultMediaType mediaType, HttpServletResponse resp) throws IOException {
    resp.setContentType(mediaType.getContentType());
    Model m = ModelFactory.createDefaultModel();
    m.write(resp.getOutputStream(), mediaType.getJenaResponseFormat());
}