Example usage for javax.servlet ServletOutputStream write

List of usage examples for javax.servlet ServletOutputStream write

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream write.

Prototype

public abstract void write(int b) throws IOException;

Source Link

Document

Writes the specified byte to this output stream.

Usage

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();
    byte[] photoData = (byte[]) session.getAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE);
    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*//from  w  w w  .  j a  v  a 2  s.  co m
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}

From source file:com.bluexml.xforms.controller.navigation.NavigationManager.java

/**
 * Send XForms to Chiba filter.<br>
 * Inserts session id into form.<br>
 * No data manipulation has to be made here.
 * /*from ww  w.j ava  2s  .  c om*/
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void sendXForms(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpSession session = req.getSession(true);
    String sessionId = session.getId();

    controller = getController();

    String testStr = StringUtils.trimToNull(req.getParameter(MsgId.PARAM_SERVE_TEST_PAGE.getText()));
    boolean serveTestPage = StringUtils.equals(testStr, "true");
    String pageId = StringUtils.trimToNull(req.getParameter(PAGE_ID));

    // called from a direct link? set our info (pageId, stackId)
    if (pageId == null) {
        // check for a possible initialisation call
        boolean isInit = StringUtils.equals(req.getParameter(MsgId.PARAM_INIT_CALL.getText()), "true");
        if (isInit) {
            ServletOutputStream stream = resp.getOutputStream();
            String result = (loadConfiguration(req, true) == -1) ? "success" : "failure";
            stream.write(result.getBytes());
            stream.close();
            return;
        }
        pageId = NavigationSessionListener.getPageId(sessionId);
        NavigationPath navigationPath = NavigationSessionListener.getNavigationPath(sessionId, pageId);

        // check whether reloading of the mapping.xml file was asked for
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_RELOAD_MAPPING_FILE.getText()), "true")) {
            controller.performDynamicReload();
        }
        // check whether reloading of properties/configuration files was asked for
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_RELOAD_PROPERTIES.getText()), "true")) {
            int resLoad = loadConfiguration(req, false);
            if (logger.isDebugEnabled()) {
                if (resLoad == -1) {
                    logger.debug("Reloaded properties: OK.");
                } else {
                    String reason = "";
                    switch (resLoad) {
                    case 0:
                        reason = "an exception occured";
                        break;
                    case 1:
                        reason = "properties files";
                        break;
                    case 2:
                        reason = "redirection file";
                        break;
                    }
                    logger.debug("Failed in loading the configuration. Reason: " + reason);
                }
            }
        }
        // set specific CSS if given
        this.setCssUrl(req);
        // initial status message. CAUTION: may be overridden later in case of errors.
        String statusMsg = StringUtils.trimToNull(req.getParameter(MsgId.PARAM_STATUS_MSG.getText()));
        if (statusMsg != null) {
            navigationPath.setStatusMsg(statusMsg);
        }
        // deal with standalone mode
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_STANDALONE.getText()), "true")) {
            controller.setStandaloneMode(true);
        }
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_STANDALONE.getText()), "false")) {
            controller.setStandaloneMode(false);
        }

        PageInfoBean pageInfo = collectPageInfo(req);
        // save session and URL we were called with (useful when a host is multi-domain'ed)
        String curServletURL = this.registerSessionURL(req, sessionId);
        // remember where we are
        navigationPath.setCurrentPage(pageInfo);
        String location = curServletURL + "?pageId=" + pageId + "&stackId=" + navigationPath.getSize();
        // propagate queryString
        location += "&" + req.getQueryString();
        if (serveTestPage == false) {
            // redirect the web client, providing ids we need
            resp.sendRedirect(resp.encodeRedirectURL(location));
            return;
        }
    }
    // the ids are available
    NavigationPath navigationPath = NavigationSessionListener.getNavigationPath(sessionId, pageId);
    if (navigationPath.isEmpty()) {
        // the servlet is called directly with ids we did not register
        throw new ServletException(MsgPool.getMsg(MsgId.MSG_SESSION_TIMED_OUT));
    }
    Page currentPage = navigationPath.peekCurrentPage();
    // set the warning if page was called with an object it can't display
    if (currentPage.isWrongCallType()) {
        navigationPath.setStatusMsg("WARNING: the data Id provided is not appropriate for this form.");
    }

    // get the form template as a string
    String statusDisplayedMsg = navigationPath.getStatusDisplayedMsg();
    Document doc = loadXFormsDocument(req, sessionId, pageId, statusDisplayedMsg, currentPage);

    req.setAttribute(WebFactory.XFORMS_NODE, doc);
    resp.getOutputStream().close();
}

From source file:net.sf.appstatus.web.pages.LoggersPage.java

@Override
public void doGet(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp)
        throws UnsupportedEncodingException, IOException {
    LOGGER.debug("doGet");
    if (StringUtils.isNotBlank(req.getParameter("name")) && StringUtils.isNotBlank(req.getParameter("level"))) {
        LoggerConfig logger2Change = new LoggerConfig(req.getParameter("name"), req.getParameter("level"));
        LOGGER.debug("Change log level : {} - {}", logger2Change.getName(), logger2Change.getLevel());
        webHandler.getAppStatus().getLoggersManager().update(logger2Change);
    }//from   w  ww .  j  av  a  2 s  .  co m
    setup(resp, "text/html");
    ServletOutputStream os = resp.getOutputStream();
    Map<String, String> valuesMap = new HashMap<String, String>();
    // build sbLoggersTable
    StrBuilder sbLoggersTable = new StrBuilder();
    List<LoggerConfig> loggers = webHandler.getAppStatus().getLoggersManager().getLoggers();
    if (HtmlUtils.generateBeginTable(sbLoggersTable, loggers.size())) {
        HtmlUtils.generateHeaders(sbLoggersTable, "", "Name", "Levels", "", "", "", "");
        for (LoggerConfig logger : loggers) {
            HtmlUtils.generateRow(sbLoggersTable, Resources.STATUS_PROP, logger.getName(),
                    getButton(LEVEL_TRACE, logger), getButton(ILoggersManager.LEVEL_DEBUG, logger),
                    getButton(LEVEL_INFO, logger), getButton(LEVEL_WARN, logger),
                    getButton(LEVEL_ERROR, logger));
        }
        HtmlUtils.generateEndTable(sbLoggersTable, loggers.size());
    }
    // generating content
    valuesMap.put("loggersTable", sbLoggersTable.toString());
    valuesMap.put("loggerCount", String.valueOf(loggers.size()));
    String content = HtmlUtils.applyLayout(valuesMap, PAGECONTENTLAYOUT);
    valuesMap.clear();
    valuesMap.put("content", content);
    // generating page
    os.write(getPage(webHandler, valuesMap).getBytes(ENCODING));
}

From source file:ORG.oclc.os.SRW.SRWServletInfo.java

public void writeXmlHeader(final javax.servlet.ServletOutputStream sos, final MessageContext msgContext,
        final HttpServletRequest req, final String defaultXsl) {
    StringBuffer sb = new StringBuffer();
    sb.append("<?xml version=\"1.0\" ?> \n");
    String xsl = req.getParameter("xsl"); // version 1.0
    if (xsl == null)
        xsl = req.getParameter("stylesheet"); // version 1.1
    if (xsl == null)
        xsl = defaultXsl;//from  ww  w . jav a 2 s  .  c  om
    if (xsl != null) {
        String languages = req.getHeader("Accept-Language");
        String realXsl = (String) realXsls.get(languages + '/' + xsl);
        if (realXsl == null)
            xsl = findRealXsl(languages, req.getLocales(), xsl);
        else
            xsl = realXsl;
        sb.append("<?xml-stylesheet type=\"text/xsl\" href=\"").append(xsl).append("\"?>\n");
    }
    try {
        sos.write(sb.toString().getBytes("utf-8"));
    } catch (Exception e) {
    }
}

From source file:com.comcast.video.dawg.show.video.VideoSnap.java

/**
 * Retrieve the images with input device ids from cache and stores it in zip
 * output stream./*from  w  ww . j  ava2 s.c  o  m*/
 *
 * @param capturedImageIds
 *            Ids of captures images
 * @param deviceMacs
 *            Mac address of selected devices
 * @param response
 *            http servelet response
 * @param session
 *            http session.
 */
public void addImagesToZipFile(String[] capturedImageIds, String[] deviceMacs, HttpServletResponse response,
        HttpSession session) {

    UniqueIndexedCache<BufferedImage> imgCache = getClientCache(session).getImgCache();

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

    ServletOutputStream serveletOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        serveletOutputStream = response.getOutputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

        BufferedImage image;
        ZipEntry zipEntry;
        ByteArrayOutputStream imgByteArrayOutputStream = null;

        for (int i = 0; i < deviceMacs.length; i++) {
            // Check whether id of captured image is null or not
            if (!StringUtils.isEmpty(capturedImageIds[i])) {
                image = imgCache.getItem(capturedImageIds[i]);
                zipEntry = new ZipEntry(deviceMacs[i].toUpperCase() + "." + IMG_FORMAT);
                zipOutputStream.putNextEntry(zipEntry);
                imgByteArrayOutputStream = new ByteArrayOutputStream();
                ImageIO.write(image, IMG_FORMAT, imgByteArrayOutputStream);
                imgByteArrayOutputStream.flush();
                zipOutputStream.write(imgByteArrayOutputStream.toByteArray());
                zipOutputStream.closeEntry();
            }
        }

        zipOutputStream.flush();
        zipOutputStream.close();
        serveletOutputStream.write(byteArrayOutputStream.toByteArray());
    } catch (IOException ioe) {
        LOGGER.error("Image zipping failed !!!", ioe);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
    }
}

From source file:org.agnitas.web.ShowComponent.java

/**
  * Gets mailing components//  w  w w.  j  av  a  2  s  .c  o m
  * TYPE_IMAGE: if component not empty, write it into response
  * <br><br>
  * TYPE_HOSTED_IMAGE: if component not empty, write it into response
  * <br><br>
  * TYPE_THUMBMAIL_IMAGE: if component not empty, write it into response
  * <br><br>
  * TYPE_ATTACHMENT: create preview <br>
  *          write component into response
  * <br><br>
  * TYPE_PERSONALIZED_ATTACHMENT: create preview <br>
  *          write component into response
  * <br><br>
  */
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    ServletOutputStream out = null;
    long len = 0;
    int compId = 0;

    if (!AgnUtils.isUserLoggedIn(req)) {
        return;
    }

    try {
        compId = Integer.parseInt(req.getParameter("compID"));
    } catch (Exception e) {
        logger.warn("Error converting "
                + (req.getParameter("compID") != null ? "'" + req.getParameter("compID") + "'"
                        : req.getParameter("compID"))
                + " to integer", e);
        return;
    }

    if (compId == 0) {
        return;
    }

    int customerID = 0;

    String customerIDStr = req.getParameter("customerID");
    if (StringUtils.isNumeric(customerIDStr)) {
        customerID = Integer.parseInt(customerIDStr);
    }

    MailingComponentDao mDao = (MailingComponentDao) WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext()).getBean("MailingComponentDao");

    MailingComponent comp = mDao.getMailingComponent(compId, AgnUtils.getCompanyID(req));

    if (comp != null) {

        switch (comp.getType()) {
        case MailingComponent.TYPE_IMAGE:
        case MailingComponent.TYPE_HOSTED_IMAGE:
            if (comp.getBinaryBlock() != null) {
                res.setContentType(comp.getMimeType());
                out = res.getOutputStream();
                out.write(comp.getBinaryBlock());
                out.flush();
                out.close();
            }
            break;
        case MailingComponent.TYPE_THUMBMAIL_IMAGE:
            if (comp.getBinaryBlock() != null) {
                res.setContentType(comp.getMimeType());
                out = res.getOutputStream();
                out.write(comp.getBinaryBlock());
                out.flush();
                out.close();
            }
            break;
        case MailingComponent.TYPE_ATTACHMENT:
        case MailingComponent.TYPE_PERSONALIZED_ATTACHMENT:
            res.setHeader("Content-Disposition", "attachment; filename=" + comp.getComponentName() + ";");
            out = res.getOutputStream();
            ApplicationContext applicationContext = WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext());
            Preview preview = ((PreviewFactory) applicationContext.getBean("PreviewFactory")).createPreview();

            byte[] attachment = null;
            int mailingID = comp.getMailingID();

            if (comp.getType() == MailingComponent.TYPE_PERSONALIZED_ATTACHMENT) {
                Page page = null;
                if (customerID == 0) { // no customerID is available, take the 1st available test recipient
                    RecipientDao recipientDao = (RecipientDao) applicationContext.getBean("RecipientDao");
                    Map<Integer, String> recipientList = recipientDao
                            .getAdminAndTestRecipientsDescription(comp.getCompanyID(), mailingID);
                    customerID = recipientList.keySet().iterator().next();
                }
                page = preview.makePreview(mailingID, customerID, false);
                attachment = page.getAttachment(comp.getComponentName());

            } else {
                attachment = comp.getBinaryBlock();
            }

            len = attachment.length;
            res.setContentLength((int) len);
            out.write(attachment);
            out.flush();
            out.close();
            break;
        }
    }
}

From source file:com.seer.datacruncher.spring.SchemasReadController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    UserEntity user = (UserEntity) session.getAttribute("user");
    if (user == null) {
        return null;
    }//from   w ww  .  jav a 2  s .  c  o m
    String start = request.getParameter("start");
    String limit = request.getParameter("limit");

    if (start == null || limit == null) {
        start = "-1";
        limit = "-1";
    }
    ObjectMapper mapper = new ObjectMapper();
    long appId = -1;
    String appIds = request.getParameter("appIds");
    String paramIdSchemaType = null;
    List<String> idSchemaTypeList = null;
    int idSchemaType = -1;

    if (appIds != null && (appIds.trim().length() == 0 || appIds.equals("-1"))) {
        appIds = null;
    }

    if (request.getParameter("idSchemaType") != null) {
        idSchemaType = -1;
        paramIdSchemaType = request.getParameter("idSchemaType");
        if ((paramIdSchemaType.indexOf(",", 0)) < 0) {
            // 1 condition
            idSchemaType = Integer.parseInt(request.getParameter("idSchemaType"));
        } else {
            //more condition
            idSchemaTypeList = Arrays.asList(StringUtils.splitPreserveAllTokens(paramIdSchemaType, ","));
        }
    }
    String strAppId = request.getParameter("appId");
    if (strAppId != null && !strAppId.trim().isEmpty()) {
        appId = Integer.valueOf(strAppId);
        if (appId == 0)
            appId = -1;
    }
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();
    ReadList readList = null;

    if (user.getIdRole() == Roles.ADMINISTRATOR.getDbCode()) {
        if (idSchemaTypeList != null) {
            readList = schemasDao.readBySchemaTypeId(Integer.parseInt(start), Integer.parseInt(limit),
                    idSchemaTypeList, appIds);
        } else {
            readList = schemasDao.readBySchemaTypeId(Integer.parseInt(start), Integer.parseInt(limit),
                    idSchemaType, appIds);
        }
    } else {
        readList = schemasDao.read(Integer.parseInt(start), Integer.parseInt(limit), user.getIdUser());
    }

    //FIXME: Check with Mario

    @SuppressWarnings("unchecked")
    List<SchemaEntity> SchemaEntities = (List<SchemaEntity>) readList.getResults();
    if (SchemaEntities != null && SchemaEntities.size() > 0) {
        for (SchemaEntity schemaEntity : SchemaEntities) {
            ReadList readTriggersList = schemaTriggerStatusDao.findByIdSchema(schemaEntity.getIdSchema());
            if (CollectionUtils.isNotEmpty(readTriggersList.getResults())) {
                SchemaTriggerStatusEntity schemaTriggerStatusEntity = (SchemaTriggerStatusEntity) readTriggersList
                        .getResults().get(0);
                schemaEntity.setSchemaEvents(schemaTriggerStatusEntity);
            }
        }
    }

    out.write(mapper.writeValueAsBytes(readList));
    out.flush();
    out.close();
    return null;
}