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:jp.co.opentone.bsol.framework.web.view.util.ViewHelper.java

protected void doWrite(HttpServletResponse response, byte[] content) throws IOException {
    ServletOutputStream o = response.getOutputStream();
    o.write(content);
    o.flush();// www  .  java 2 s. c  om
    o.close();
}

From source file:org.fenixedu.parking.ui.Action.ParkingManagerDispatchAction.java

public ActionForward exportToPDFParkingCard(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    String parkingPartyID = request.getParameter("parkingPartyID");

    final ParkingParty parkingParty = FenixFramework.getDomainObject(parkingPartyID);
    String parkingGroupID = request.getParameter("groupID");

    if (parkingGroupID != null) {
        String parkingRequestID = request.getParameter("code");
        if (request.getParameter("groupID") == null) {
            saveErrorMessage(request, "group", "error.invalidGroup");
            request.setAttribute("externalId", parkingRequestID);
            return showRequest(mapping, actionForm, request, response);
        }/*from w w  w  .j  a  va  2s. com*/

        if (!isValidGroup(parkingGroupID)) {
            saveErrorMessage(request, "group", "error.invalidGroup");
            request.setAttribute("externalId", parkingRequestID);
            return showRequest(mapping, actionForm, request, response);
        }
    }

    ParkingGroup parkingGroup = null;
    if (parkingGroupID != null) {
        parkingGroup = FenixFramework.getDomainObject(parkingGroupID);
    } else {
        parkingGroup = parkingParty.getParkingGroup();
    }

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("imageUrl", "images/Logo_IST_color.tiff");

    Person person = (Person) parkingParty.getParty();
    parameters.put("number", getMostSignificantNumberString(person, parkingGroup));

    List<Person> persons = new ArrayList<Person>();
    persons.add(person);

    ReportResult report = ReportsUtils.generateReport("parkingManager.parkingCard", parameters, persons);
    byte[] data = report.getData();
    response.setContentType(report.getContentType());
    response.addHeader("Content-Disposition", "attachment; filename=cartao." + report.getFileExtension());
    response.setContentLength(data.length);
    ServletOutputStream writer = response.getOutputStream();
    writer.write(data);
    writer.flush();
    writer.close();
    response.flushBuffer();

    return mapping.findForward("");
}

From source file:com.globalsight.connector.mindtouch.MindTouchCreateJobHandler.java

@ActionHandler(action = "initTree", formClass = "")
public void initTree(HttpServletRequest p_request, HttpServletResponse p_response, Object form)
        throws Exception {
    ServletOutputStream out = p_response.getOutputStream();
    try {/*ww w .j a  va2s  . co m*/
        String mtcId = p_request.getParameter("mtcId");
        MindTouchConnector mtc = MindTouchManager.getMindTouchConnectorById(Long.parseLong(mtcId));

        MindTouchHelper helper = new MindTouchHelper(mtc);
        String treeXml = helper.getTreeXml("home");
        MindTouchPage mtp = helper.parseTreeXml(treeXml);
        helper.shutdownHttpClient();

        out.write(getJSON(mtp).getBytes("UTF-8"));
    } catch (Exception e) {
        logger.error("Fail to init the sitemap tree.", e);
    } finally {
        out.close();
        pageReturn();
    }
}

From source file:org.oscarehr.fax.admin.ManageFaxes.java

public ActionForward viewFax(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {//from   ww  w .j  av  a  2 s .  c  om

    if (!securityInfoManager.hasPrivilege(LoggedInInfo.getLoggedInInfoFromSession(request), "_edoc", "r",
            null)) {
        throw new SecurityException("missing required security object (_edoc)");
    }

    try {
        String doc_no = request.getParameter("jobId");
        String pageNum = request.getParameter("curPage");
        if (pageNum == null) {
            pageNum = "0";
        }
        Integer pn = Integer.parseInt(pageNum);
        log.debug("Document No :" + doc_no);
        LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.READ,
                LogConst.CON_DOCUMENT, doc_no, request.getRemoteAddr());

        FaxJobDao faxJobDao = SpringUtils.getBean(FaxJobDao.class);
        FaxJob faxJob = faxJobDao.find(Integer.parseInt(doc_no));

        int index;
        String filename;
        if ((index = faxJob.getFile_name().lastIndexOf("/")) > -1) {
            filename = faxJob.getFile_name().substring(index + 1);
        } else {
            filename = faxJob.getFile_name();
        }

        String name = filename + "_" + pn + ".png";
        log.debug("name " + name);

        File outfile = null;

        outfile = hasCacheVersion2(faxJob, pn);
        if (outfile != null) {
            log.debug("got doc from local cache   ");
        } else {
            outfile = createCacheVersion2(faxJob, pn);
            if (outfile != null) {
                log.debug("create new doc  ");
            }
        }
        response.setContentType("image/png");
        ServletOutputStream outs = response.getOutputStream();
        response.setHeader("Content-Disposition", "attachment;filename=" + name);

        BufferedInputStream bfis = null;
        try {
            if (outfile != null) {
                bfis = new BufferedInputStream(new FileInputStream(outfile));
                int data;
                while ((data = bfis.read()) != -1) {
                    outs.write(data);
                    // outs.flush();
                }
            } else {
                log.info("Unable to retrieve content for " + faxJob
                        + ". This may indicate previous upload or save errors...");
            }
        } finally {
            if (bfis != null) {
                bfis.close();
            }
        }

        outs.flush();
        outs.close();
    } catch (java.net.SocketException se) {
        MiscUtils.getLogger().error("Error", se);
    } catch (Exception e) {
        MiscUtils.getLogger().error("Error", e);
    }
    return null;

}

From source file:com.java2s.SendFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws java.io.IOException, ServletException {

    //get the file name from the 'file' parameter
    String fileName = request.getParameter("file");
    if (fileName == null || fileName.equals(""))
        throw new ServletException("Invalid or non-existent file parameter in SendPdf component.");

    if (fileName.indexOf(".pdf") == -1)
        fileName = fileName + ".pdf";

    ServletOutputStream stream = null;
    BufferedInputStream buf = null;
    HttpServletResponse httpResp = null;
    try {/*from w ww.  j  a v  a  2s. c o  m*/

        httpResp = (HttpServletResponse) response;
        stream = httpResp.getOutputStream();
        File pdf = new File(PDF_DIR + "/" + fileName);

        //set response headers
        httpResp.setContentType(PDF_CONTENT_TYPE);
        httpResp.addHeader("Content-Disposition", "attachment; filename=" + fileName);
        httpResp.setContentLength((int) pdf.length());

        FileInputStream input = new FileInputStream(pdf);
        buf = new BufferedInputStream(input);
        int readBytes = 0;
        //read from the file; write to the ServletOutputStream
        while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);

    } catch (Exception ioe) {

        //  throw new ServletException(ioe.getMessage());
        System.out.println(ioe.getMessage());

    } finally {

        if (buf != null)
            buf.close();
        if (stream != null) {
            stream.flush();
            //stream.close();
        }

    } //end finally
    chain.doFilter(request, httpResp);
}

From source file:com.globalsight.connector.blaise.BlaiseCreateJobHandler.java

/**
 * Upload the job attachment file to server, and store it in session for
 * later use.//from  ww w  . ja  va 2  s  .com
 */
@ActionHandler(action = "checkTargetLocalesUrl", formClass = "")
public void checkTargetLocalesUrl(HttpServletRequest request, HttpServletResponse response, Object form)
        throws Exception {
    List<TranslationInboxEntryVo> selectedEntries = new ArrayList<TranslationInboxEntryVo>();
    String entryIds = request.getParameter("entryIds");
    if (entryIds != null) {
        for (String entryId : entryIds.split(",")) {
            try {
                long id = Long.parseLong(entryId);
                TranslationInboxEntryVo vo = currPageEntryMap.get(id);
                if (vo != null) {
                    selectedEntries.add(vo);
                }
            } catch (Exception e) {
                logger.error(e);
            }
        }
    }

    HashSet<Locale> l10nLocales = new HashSet<Locale>();
    String l10Nid = request.getParameter("l10Nid");
    if (StringUtils.isNotEmpty(l10Nid)) {
        L10nProfile l10nP = ServerProxy.getProjectHandler().getL10nProfile(Long.parseLong(l10Nid));
        for (Object obj : l10nP.getWorkflowTemplateInfos()) {
            WorkflowTemplateInfo wti = (WorkflowTemplateInfo) obj;
            l10nLocales.add(wti.getTargetLocale().getLocale());
        }
    }

    Iterator<TranslationInboxEntryVo> it = selectedEntries.iterator();
    while (it.hasNext()) {
        if (l10nLocales.contains(it.next().getTargetLocale())) {
            it.remove();
        }
    }

    String result = "";
    StringBuilder ids = new StringBuilder();
    if (selectedEntries.size() > 0) {
        for (TranslationInboxEntryVo vo : selectedEntries) {
            ids.append(vo.getId()).append(",");
        }
        result = ids.toString();
        result = result.substring(0, result.length() - 1);
    }

    ServletOutputStream out = response.getOutputStream();
    out.write(result.getBytes("UTF-8"));

    pageReturn();
}

From source file:com.esri.gpt.control.cart.XslBundler.java

/**
 * Processes the HTTP request./*w  w  w.j a va 2  s  . co m*/
 * @param request the HTTP request
 * @param response HTTP response
 * @param context request context
 * @throws Exception if an exception occurs
 */
@Override
public void execute(HttpServletRequest request, HttpServletResponse response, RequestContext context)
        throws Exception {
    String[] keys = this.readKeys(request, context, true);
    String sXsltPath = Val.chkStr(request.getParameter("xslt"));
    String sMimeType = Val.chkStr(request.getParameter("mimeType"));
    String sContentDisposition = Val.chkStr(request.getParameter("contentDisposition"));
    if ((keys.length > 0) && (sXsltPath.length() > 0)) {
        if (!assertWhiteList(context, "catalog.cart.xslt.whitelist", sXsltPath)) {
            throw new ServletException("Invalid xslt parameter");
        }
        XsltTemplate template = this.getCompiledTemplate(sXsltPath);
        ServletOutputStream out = response.getOutputStream();

        if (sMimeType.length() == 0) {
            sMimeType = "text/plain";
        }
        response.setContentType(StringEscapeUtils.escapeHtml4(Val.stripControls(sMimeType)) + ";charset=UTF-8");
        if (sContentDisposition.length() > 0) {
            response.addHeader("Content-Disposition",
                    StringEscapeUtils.escapeHtml4(Val.stripControls(sContentDisposition)));
        }

        try {
            for (String sKey : keys) {
                String sXml = this.readXml(request, context, sKey);
                String sResult = Val.chkStr(template.transform(sXml));
                if (sResult.length() > 0) {
                    byte[] bytes = sResult.getBytes("UTF-8");
                    out.write(bytes);
                    out.flush();
                }
            }
        } finally {
            out.flush();
            out.close();
        }
    }
}

From source file:com.alkacon.opencms.formgenerator.CmsCaptchaField.java

/**
 * Writes a Captcha JPEG image to the servlet response output stream.
 * <p>//  w  w  w  . j av  a  2 s.  c  om
 * 
 * @param cms an initialized Cms JSP action element
 * @throws IOException if something goes wrong
 */
public void writeCaptchaImage(CmsJspActionElement cms) throws IOException {

    // remove eventual session attribute containing captcha settings
    cms.getRequest().getSession().removeAttribute(SESSION_PARAM_CAPTCHASETTINGS);
    String sessionId = cms.getRequest().getSession().getId();
    Locale locale = cms.getRequestContext().getLocale();
    BufferedImage captchaImage = null;
    int maxTries = 10;
    do {
        try {
            maxTries--;
            captchaImage = ((ImageCaptchaService) CmsCaptchaServiceCache.getSharedInstance()
                    .getCaptchaService(m_captchaSettings, cms.getCmsObject())).getImageChallengeForID(sessionId,
                            locale);
        } catch (CaptchaException cex) {
            // image size is too small, increase dimensions and try it again
            if (LOG.isInfoEnabled()) {
                LOG.info(cex);
                LOG.info(Messages.get().getBundle().key(Messages.LOG_ERR_CAPTCHA_CONFIG_IMAGE_SIZE_2,
                        new Object[] { m_captchaSettings.getPresetPath(), new Integer(maxTries) }));
            }
            m_captchaSettings.setImageHeight((int) (m_captchaSettings.getImageHeight() * 1.1));
            m_captchaSettings.setImageWidth((int) (m_captchaSettings.getImageWidth() * 1.1));
            // IMPORTANT: store changed captcha settings in session, they have to be used when validating the phrase
            cms.getRequest().getSession().setAttribute(SESSION_PARAM_CAPTCHASETTINGS,
                    m_captchaSettings.clone());
        }
    } while ((captchaImage == null) && (maxTries > 0));

    ServletOutputStream out = null;
    try {
        CmsFlexController controller = CmsFlexController.getController(cms.getRequest());
        HttpServletResponse response = controller.getTopResponse();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        ByteArrayOutputStream captchaImageOutput = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "jpg", captchaImageOutput);
        out = cms.getResponse().getOutputStream();
        out.write(captchaImageOutput.toByteArray());
        out.flush();
    } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(e.getLocalizedMessage(), e);
        }
        cms.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (Throwable t) {
            // intentionally left blank
        }
    }
}

From source file:com.ewcms.plugin.vote.manager.web.ResultServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletOutputStream out = null;
    StringBuffer output = new StringBuffer();
    try {//  w w  w  . ja v a2s .c  o m
        String id = req.getParameter("id");

        if (!id.equals("") && StringUtils.isNumeric(id)) {
            Long questionnaireId = new Long(id);

            ServletContext application = getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
            VoteFacable voteFac = (VoteFacable) wac.getBean("voteFac");

            String ipAddr = req.getRemoteAddr();

            output = voteFac.getQuestionnaireResultClientToHtml(questionnaireId,
                    getServletContext().getContextPath(), ipAddr);
        }
        out = resp.getOutputStream();
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        out.write(output.toString().getBytes("UTF-8"));
        out.flush();
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}

From source file:org.oscarehr.document.web.ManageDocumentAction.java

public ActionForward display(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String temp = request.getParameter("remoteFacilityId");
    Integer remoteFacilityId = null;
    if (temp != null)
        remoteFacilityId = Integer.parseInt(temp);

    String doc_no = request.getParameter("doc_no");
    log.debug("Document No :" + doc_no);

    String docxml = null;/*  w  w w .  j  a va  2  s.c om*/
    String contentType = null;
    byte[] contentBytes = null;
    String filename = null;

    // local document
    if (remoteFacilityId == null) {
        CtlDocument ctld = documentDAO.getCtrlDocument(Integer.parseInt(doc_no));
        if (ctld.isDemographicDocument()) {
            LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.READ,
                    LogConst.CON_DOCUMENT, doc_no, request.getRemoteAddr(), "" + ctld.getModuleId());
        } else {
            LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.READ,
                    LogConst.CON_DOCUMENT, doc_no, request.getRemoteAddr());
        }

        Document d = documentDAO.getDocument(doc_no);
        log.debug("Document Name :" + d.getDocfilename());

        docxml = d.getDocxml();
        contentType = d.getContenttype();

        File file = new File(EDocUtil.getDocumentPath(d.getDocfilename()));
        filename = d.getDocfilename();

        if (file.exists())
            contentBytes = FileUtils.readFileToByteArray(file);

    } else // remote document
    {
        FacilityIdIntegerCompositePk remotePk = new FacilityIdIntegerCompositePk();
        remotePk.setIntegratorFacilityId(remoteFacilityId);
        remotePk.setCaisiItemId(Integer.parseInt(doc_no));

        LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get();

        CachedDemographicDocument remoteDocument = null;
        CachedDemographicDocumentContents remoteDocumentContents = null;

        try {
            if (!CaisiIntegratorManager.isIntegratorOffline()) {
                DemographicWs demographicWs = CaisiIntegratorManager.getDemographicWs();
                remoteDocument = demographicWs.getCachedDemographicDocument(remotePk);
                remoteDocumentContents = demographicWs.getCachedDemographicDocumentContents(remotePk);
            }
        } catch (Exception e) {
            MiscUtils.getLogger().error("Unexpected error.", e);
            CaisiIntegratorManager.checkForConnectionError(e);
        }

        if (CaisiIntegratorManager.isIntegratorOffline()) {
            Integer demographicId = IntegratorFallBackManager.getDemographicNoFromRemoteDocument(remotePk);
            MiscUtils.getLogger().debug("got demographic no from remote document " + demographicId);
            List<CachedDemographicDocument> remoteDocuments = IntegratorFallBackManager
                    .getRemoteDocuments(demographicId);
            for (CachedDemographicDocument demographicDocument : remoteDocuments) {
                if (demographicDocument.getFacilityIntegerPk().getIntegratorFacilityId() == remotePk
                        .getIntegratorFacilityId()
                        && demographicDocument.getFacilityIntegerPk().getCaisiItemId() == remotePk
                                .getCaisiItemId()) {
                    remoteDocument = demographicDocument;
                    remoteDocumentContents = IntegratorFallBackManager.getRemoteDocument(demographicId,
                            remotePk);
                    break;
                }
                MiscUtils.getLogger().error("End of the loop and didn't find the remoteDocument");
            }
        }

        docxml = remoteDocument.getDocXml();
        contentType = remoteDocument.getContentType();
        filename = remoteDocument.getDocFilename();
        contentBytes = remoteDocumentContents.getFileContents();
    }

    if (docxml != null && !docxml.trim().equals("")) {
        ServletOutputStream outs = response.getOutputStream();
        outs.write(docxml.getBytes());
        outs.flush();
        outs.close();
        return null;
    }

    // TODO: Right now this assumes it's a pdf which it shouldn't
    if (contentType == null) {
        contentType = "application/pdf";
    }

    response.setContentType(contentType);
    response.setContentLength(contentBytes.length);
    response.setHeader("Content-Disposition", "inline; filename=" + filename);
    log.debug("about to Print to stream");
    ServletOutputStream outs = response.getOutputStream();
    outs.write(contentBytes);
    outs.flush();
    outs.close();
    return null;
}