Example usage for javax.servlet ServletOutputStream close

List of usage examples for javax.servlet ServletOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:net.urosk.reportEngine.ReportsServlet.java

public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String reportDesign = request.getParameter("__report");
    String type = request.getParameter("__format");
    String outputFilename = request.getParameter("__filename");
    String attachment = request.getParameter("attachment");

    //check parameters
    StringBuffer msg = new StringBuffer();

    // checkers//from  w  w  w  .j  a  v  a 2s  .  c o  m
    if (isEmpty(reportDesign)) {
        msg.append("<BR>__report can not be empty");
    }

    OutputType outputType = null;

    try {
        outputType = OutputType.valueOf(type.toUpperCase());
    } catch (Exception e) {
        msg.append("Undefined report __format: " + type + ". Set __format=" + OutputType.values());
    }

    // checkers
    if (isEmpty(outputFilename)) {
        msg.append("<BR>__filename can not be empty");
    }

    try {

        ServletOutputStream out = response.getOutputStream();
        ServletContext context = request.getSession().getServletContext();

        // output error
        if (StringUtils.isNotEmpty(msg.toString())) {
            out.print(msg.toString());
            return;
        }

        ReportDef def = new ReportDef();
        def.setDesignFileName(reportDesign);
        def.setOutputType(outputType);

        @SuppressWarnings("unchecked")
        Map<String, String[]> params = request.getParameterMap();
        Iterator<String> i = params.keySet().iterator();

        while (i.hasNext()) {
            String key = i.next();
            String value = params.get(key)[0];
            def.getParameters().put(key, value);
        }

        try {

            String createdFile = birtReportEngine.createReport(def);

            File file = new File(createdFile);

            String mimetype = context.getMimeType(file.getAbsolutePath());

            String inlineOrAttachment = (attachment != null) ? "attachment" : "inline";

            response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition",
                    inlineOrAttachment + "; filename=\"" + outputFilename + "\"");

            DataInputStream in = new DataInputStream(new FileInputStream(file));

            byte[] bbuf = new byte[1024];
            int length;
            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                out.write(bbuf, 0, length);
            }

            in.close();

        } catch (Exception e) {

            logger.error(e, e);
            out.print(e.getMessage());
        } finally {
            out.flush();
            out.close();
        }

        logger.info("Free memory: " + (Runtime.getRuntime().freeMemory() / 1024L * 1024L));

    } catch (Exception e) {
        logger.error(e, e);

    } finally {

    }

}

From source file:org.openmrs.module.pmtct.util.FileExporter.java

/**
 * Auto generated method comment//  w w w  .ja  v a 2 s.co m
 * 
 * @param request
 * @param response
 * @param patientList
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportExpectedPatientInMaternityToCSVFile(HttpServletRequest request, HttpServletResponse response,
        List<Object> patientList, String filename, String title) throws Exception {
    ServletOutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        Patient p;
        PatientService ps = Context.getPatientService();

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        outputStream.println("" + title);
        outputStream.println("Number of Patients: " + patientList.size());
        outputStream.println();
        outputStream.println("No. ,Identifier, Names, Enrollment Date, DPA, HIV Status, HIV Status of Partner");
        outputStream.println();

        int ids = 0;

        Encounter cpnEnc;

        for (Object patient : patientList) {
            Object[] o = (Object[]) patient;

            p = ps.getPatient(Integer.parseInt(o[0].toString()));
            cpnEnc = pmtctTag.getCPNEncounterInfo(p.getPatientId());

            ids += 1;
            outputStream.println(ids + "," + p.getActiveIdentifiers().get(0).getIdentifier() + ","
                    + p.getPersonName() + "," + o[3].toString() + ","
                    + pmtctTag.observationValueByConcept(cpnEnc, PMTCTConstants.PREGNANT_DUE_DATE) + ","
                    + pmtctTag.lastObsValueByConceptId(p.getPatientId(), PMTCTConstants.RESULT_OF_HIV_TEST)
                    + ","
                    + pmtctTag.observationValueByConcept(cpnEnc, PMTCTConstants.TESTING_STATUS_OF_PARTNER));
        }

        outputStream.flush();
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}

From source file:org.structr.web.servlet.HtmlServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) {

    final Authenticator auth = getConfig().getAuthenticator();
    List<Page> pages = null;
    boolean requestUriContainsUuids = false;

    SecurityContext securityContext;/*from   www . j av a 2 s.co  m*/
    final App app;

    try {
        final String path = request.getPathInfo();

        // check for registration (has its own tx because of write access
        if (checkRegistration(auth, request, response, path)) {

            return;
        }

        // check for registration (has its own tx because of write access
        if (checkResetPassword(auth, request, response, path)) {

            return;
        }

        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            securityContext = auth.initializeAndExamineRequest(request, response);
            tx.success();
        }

        app = StructrApp.getInstance(securityContext);

        try (final Tx tx = app.tx()) {

            // Ensure access mode is frontend
            securityContext.setAccessMode(AccessMode.Frontend);

            request.setCharacterEncoding("UTF-8");

            // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
            response.setCharacterEncoding("UTF-8");

            boolean dontCache = false;

            logger.log(Level.FINE, "Path info {0}", path);

            // don't continue on redirects
            if (response.getStatus() == 302) {

                tx.success();
                return;
            }

            final Principal user = securityContext.getUser(false);
            if (user != null) {

                // Don't cache if a user is logged in
                dontCache = true;

            }

            final RenderContext renderContext = RenderContext.getInstance(securityContext, request, response);

            renderContext.setResourceProvider(config.getResourceProvider());

            final EditMode edit = renderContext.getEditMode(user);

            DOMNode rootElement = null;
            AbstractNode dataNode = null;

            final String[] uriParts = PathHelper.getParts(path);
            if ((uriParts == null) || (uriParts.length == 0)) {

                // find a visible page
                rootElement = findIndexPage(securityContext, pages, edit);

                logger.log(Level.FINE, "No path supplied, trying to find index page");

            } else {

                if (rootElement == null) {

                    rootElement = findPage(securityContext, pages, path, edit);

                } else {
                    dontCache = true;
                }
            }

            if (rootElement == null) { // No page found

                // Look for a file
                final File file = findFile(securityContext, request, path);
                if (file != null) {

                    streamFile(securityContext, file, request, response, edit);
                    tx.success();
                    return;

                }

                // store remaining path parts in request
                final Matcher matcher = threadLocalUUIDMatcher.get();

                for (int i = 0; i < uriParts.length; i++) {

                    request.setAttribute(uriParts[i], i);
                    matcher.reset(uriParts[i]);

                    // set to "true" if part matches UUID pattern
                    requestUriContainsUuids |= matcher.matches();

                }

                if (!requestUriContainsUuids) {

                    // Try to find a data node by name
                    dataNode = findFirstNodeByName(securityContext, request, path);

                } else {

                    dataNode = findNodeByUuid(securityContext, PathHelper.getName(path));

                }

                //if (dataNode != null && !(dataNode instanceof Linkable)) {
                if (dataNode != null) {

                    // Last path part matches a data node
                    // Remove last path part and try again searching for a page
                    // clear possible entry points
                    request.removeAttribute(POSSIBLE_ENTRY_POINTS_KEY);

                    rootElement = findPage(securityContext, pages,
                            StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP), edit);

                    renderContext.setDetailsDataObject(dataNode);

                    // Start rendering on data node
                    if (rootElement == null && dataNode instanceof DOMNode) {

                        rootElement = ((DOMNode) dataNode);
                    }
                }
            }

            // look for pages with HTTP Basic Authentication (must be done as superuser)
            if (rootElement == null) {

                final HttpBasicAuthResult authResult = checkHttpBasicAuth(request, response, path);

                switch (authResult.authState()) {

                // Element with Basic Auth found and authentication succeeded
                case Authenticated:
                    final Linkable result = authResult.getRootElement();
                    if (result instanceof Page) {

                        rootElement = (DOMNode) result;
                        securityContext = authResult.getSecurityContext();
                        renderContext.pushSecurityContext(securityContext);

                    } else if (result instanceof File) {

                        streamFile(authResult.getSecurityContext(), (File) result, request, response,
                                EditMode.NONE);
                        tx.success();
                        return;

                    }
                    break;

                // Page with Basic Auth found but not yet authenticated
                case MustAuthenticate:
                    tx.success();
                    return;

                // no Basic Auth for given path, go on
                case NoBasicAuth:
                    break;
                }

            }

            // Still nothing found, do error handling
            if (rootElement == null) {
                rootElement = notFound(response, securityContext);
            }

            if (rootElement == null) {
                tx.success();
                return;
            }

            // check dont cache flag on page (if root element is a page)
            // but don't modify true to false
            dontCache |= rootElement.getProperty(Page.dontCache);

            if (EditMode.WIDGET.equals(edit) || dontCache) {

                setNoCacheHeaders(response);

            }

            if (!securityContext.isVisible(rootElement)) {

                rootElement = notFound(response, securityContext);
                if (rootElement == null) {

                    tx.success();
                    return;
                }

            } else {

                if (!EditMode.WIDGET.equals(edit) && !dontCache
                        && notModifiedSince(request, response, rootElement, dontCache)) {

                    ServletOutputStream out = response.getOutputStream();
                    out.flush();
                    //response.flushBuffer();
                    out.close();

                } else {

                    // prepare response
                    response.setCharacterEncoding("UTF-8");

                    String contentType = rootElement.getProperty(Page.contentType);

                    if (contentType == null) {

                        // Default
                        contentType = "text/html;charset=UTF-8";
                    }

                    if (contentType.equals("text/html")) {
                        contentType = contentType.concat(";charset=UTF-8");
                    }

                    response.setContentType(contentType);

                    setCustomResponseHeaders(response);

                    final boolean createsRawData = rootElement.getProperty(Page.pageCreatesRawData);

                    // async or not?
                    if (isAsync && !createsRawData) {

                        final AsyncContext async = request.startAsync();
                        final ServletOutputStream out = async.getResponse().getOutputStream();
                        final AtomicBoolean finished = new AtomicBoolean(false);
                        final DOMNode rootNode = rootElement;

                        threadPool.submit(new Runnable() {

                            @Override
                            public void run() {

                                try (final Tx tx = app.tx()) {

                                    //final long start = System.currentTimeMillis();
                                    // render
                                    rootNode.render(renderContext, 0);
                                    finished.set(true);

                                    //final long end = System.currentTimeMillis();
                                    //System.out.println("Done in " + (end-start) + " ms");
                                    tx.success();

                                } catch (Throwable t) {
                                    t.printStackTrace();
                                    final String errorMsg = t.getMessage();
                                    try {
                                        //response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                                errorMsg);
                                        finished.set(true);
                                    } catch (IOException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                            }

                        });

                        // start output write listener
                        out.setWriteListener(new WriteListener() {

                            @Override
                            public void onWritePossible() throws IOException {

                                try {

                                    final Queue<String> queue = renderContext.getBuffer().getQueue();
                                    while (out.isReady()) {

                                        String buffer = null;

                                        synchronized (queue) {
                                            buffer = queue.poll();
                                        }

                                        if (buffer != null) {

                                            out.print(buffer);

                                        } else {

                                            if (finished.get()) {

                                                async.complete();
                                                response.setStatus(HttpServletResponse.SC_OK);

                                                // prevent this block from being called again
                                                break;
                                            }

                                            Thread.sleep(1);
                                        }
                                    }

                                } catch (Throwable t) {
                                    t.printStackTrace();
                                }
                            }

                            @Override
                            public void onError(Throwable t) {
                                t.printStackTrace();
                            }
                        });

                    } else {

                        final StringRenderBuffer buffer = new StringRenderBuffer();
                        renderContext.setBuffer(buffer);

                        // render
                        rootElement.render(renderContext, 0);

                        try {

                            response.getOutputStream().write(buffer.getBuffer().toString().getBytes("utf-8"));
                            response.getOutputStream().flush();
                            response.getOutputStream().close();

                        } catch (IOException ioex) {
                            ioex.printStackTrace();
                        }
                    }
                }
            }

            tx.success();

        } catch (FrameworkException fex) {
            fex.printStackTrace();
            logger.log(Level.SEVERE, "Exception while processing request", fex);
        }

    } catch (IOException | FrameworkException t) {

        t.printStackTrace();
        logger.log(Level.SEVERE, "Exception while processing request", t);
        UiAuthenticator.writeInternalServerError(response);
    }
}

From source file:org.wso2.carbon.bpel.ui.bpel2svg.SVGGenerateServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * Handles the HTTP process request which creates the SVG graph for a bpel process
 *
 * @param request  servlet request//from w  w w  . jav a 2 s . c  om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Log log = LogFactory.getLog(SVGGenerateServlet.class);
    HttpSession session = request.getSession(true);
    //Get the bpel process id
    String pid = CharacterEncoder.getSafeText(request.getParameter("pid"));
    ServletConfig config = getServletConfig();
    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
    ConfigurationContext configContext = (ConfigurationContext) config.getServletContext()
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    String processDef = null;
    ProcessManagementServiceClient client = null;
    SVGInterface svg = null;
    String svgStr = null;
    ServletOutputStream sos = null;
    sos = response.getOutputStream();
    try {
        client = new ProcessManagementServiceClient(cookie, backendServerURL, configContext,
                request.getLocale());
        //Gets the bpel process definition needed to create the SVG from the processId
        processDef = client.getProcessInfo(QName.valueOf(pid)).getDefinitionInfo().getDefinition()
                .getExtraElement().toString();

        BPELInterface bpel = new BPELImpl();
        //Converts the bpel process definition to an omElement which is how the AXIS2 Object Model (AXIOM)
        // represents an XML document
        OMElement bpelStr = bpel.load(processDef);

        /**
         * Process the OmElement containing the bpel process definition
         * Process the subactivites of the bpel process by iterating through the omElement
         * */
        bpel.processBpelString(bpelStr);

        //Create a new instance of the LayoutManager for the bpel process
        LayoutManager layoutManager = BPEL2SVGFactory.getInstance().getLayoutManager();
        //Set the layout of the SVG to vertical
        layoutManager.setVerticalLayout(true);
        //Get the root activity i.e. the Process Activity
        layoutManager.layoutSVG(bpel.getRootActivity());

        svg = new SVGImpl();
        //Set the root activity of the SVG i.e. the Process Activity
        svg.setRootActivity(bpel.getRootActivity());
        //Set the content type of the HTTP response as "image/svg+xml"
        response.setContentType("image/svg+xml");
        //Get the SVG graph created for the process as a SVG string
        svgStr = svg.generateSVGString();
        //Checks whether the SVG string generated contains a value
        if (svgStr != null) {
            // stream to write binary data into the response
            sos.write(svgStr.getBytes(Charset.defaultCharset()));
            sos.flush();
            sos.close();
        }
    } catch (ProcessManagementException e) {
        log.error("SVG Generation Error", e);
        String errorSVG = "<svg version=\"1.1\"\n"
                + "     xmlns=\"http://www.w3.org/2000/svg\"><text y=\"50\">Could not display SVG</text></svg>";
        sos.write(errorSVG.getBytes(Charset.defaultCharset()));
        sos.flush();
        sos.close();
    }

}

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

protected void processMethodRequest(org.apache.axis.MessageContext msgContext, HttpServletRequest req,
        HttpServletResponse resp) throws org.apache.axis.AxisFault, IOException {
    SRWSoapBindingImpl soapBinding = new SRWSoapBindingImpl();
    long startTime = System.currentTimeMillis();
    servletLog.debug("enter processMethodRequest");
    //        log.info("at start: totalMemory="+rt.totalMemory()+", freeMemory="+rt.freeMemory());
    servletLog.info(req.getQueryString());
    if (!srwInfo.setSRWStuff(req, resp, msgContext)) {
        servletLog.error("srwInfo.setSRWStuff failed!");
        return;//from  w w w  .j  a  va 2s .co  m
    }
    if (servletLog.isDebugEnabled()) {
        Enumeration enumer = req.getParameterNames();
        String name;
        while (enumer.hasMoreElements()) {
            name = (String) enumer.nextElement();
            servletLog.debug(name + "=\"" + req.getParameter(name) + "\"");
        }
    }
    String operation = req.getParameter("operation"), query = req.getParameter("query"),
            scanClause = req.getParameter("scanClause");
    servletLog.debug("in processMethodRequest: operation=" + operation);
    if (query != null) {
        servletLog.debug(
                "in processMethodRequest: query:\n" + Utilities.byteArrayToString(query.getBytes("UTF8")));
    }
    if (scanClause != null)
        servletLog.debug("in processMethodRequest: scanClause:\n"
                + Utilities.byteArrayToString(scanClause.getBytes("UTF8")));

    if ((operation != null && operation.equals("searchRetrieve")) || query != null) { // searchRetrieveRequest
        int i;
        StringBuffer sb = new StringBuffer();

        // utf-8 bytes seem to have been incorrectly loaded as characters
        // lets load them back into bytes and then rebuild the string
        //            byte[] qb=new byte[query.length()];
        //            for(i=0; i<query.length(); i++)
        //                qb[i]=(byte)query.charAt(i);
        //            query=new String(qb, "utf-8");
        // MIH: avoid NullPointerException//////////////
        if (query != null) {
            query = query.replaceAll("\\s+", " ");
            //                byte[] qb = new byte[query.length()];
            //                for (i = 0; i < query.length(); i++)
            //                    qb[i] = (byte) query.charAt(i);
            //                query = new String(qb, "utf-8");
        }
        ///////////////////////////////////////////////
        de.escidoc.core.domain.sru.SearchRetrieveRequestType request = new de.escidoc.core.domain.sru.SearchRetrieveRequestType();
        request.setQuery(query);

        Enumeration parms = req.getParameterNames();
        String extension, namespace, parm, t;
        while (parms.hasMoreElements()) {
            parm = (String) parms.nextElement();
            if (parm.equals("sortKeys")) {
                t = req.getParameter(parm);
                if (t != null)
                    request.setSortKeys(t);
            } else if (parm.equals("startRecord")) {
                t = req.getParameter(parm);
                if (t != null) {
                    try {
                        i = Integer.parseInt(t);
                        if (i < 1)
                            i = Integer.MAX_VALUE;
                    } catch (NumberFormatException e) {
                        i = Integer.MAX_VALUE;
                    }
                    request.setStartRecord(new PositiveInteger(String.valueOf(i)));
                }
            } else if (parm.equals("maximumRecords")) {
                t = req.getParameter(parm);
                if (t != null) {
                    try {
                        i = Integer.parseInt(t);
                        if (i < 0)
                            i = Integer.MAX_VALUE;
                    } catch (NumberFormatException e) {
                        i = Integer.MAX_VALUE;
                    }

                    request.setMaximumRecords(new NonNegativeInteger(String.valueOf(i)));
                }
            } else if (parm.equals("recordSchema")) {
                t = req.getParameter(parm);
                if (t != null)
                    request.setRecordSchema(t);
            } else if (parm.equals("recordPacking")) {
                t = req.getParameter(parm);
                if (t != null)
                    request.setRecordPacking(t);
            } else if (parm.equals("resultSetTTL")) {
                t = req.getParameter(parm);
                if (t != null) {
                    try {
                        i = Integer.parseInt(t);
                        if (i < 0)
                            i = Integer.MAX_VALUE;
                        request.setResultSetTTL(new NonNegativeInteger(String.valueOf(i)));
                    } catch (NumberFormatException e) {
                        servletLog.error("resultSetTTL=" + t);
                    }
                }
            }
        }
        if (request.getRecordPacking() == null) {
            //Default for sru
            request.setRecordPacking("xml");
        }
        parms = req.getParameterNames(); // walk through them again
        de.escidoc.core.domain.sru.ExtraDataType extraDataType = new de.escidoc.core.domain.sru.ExtraDataType();
        boolean hasExtraRequestData = false;
        while (parms.hasMoreElements()) {
            parm = (String) parms.nextElement();
            servletLog.debug("parm=" + parm);
            extension = srwInfo.getExtension(parm);
            servletLog.debug("extension=" + extension);
            if (extension != null) {
                t = req.getParameter(parm);
                if (t != null && t.length() > 0) {
                    MessageElement message = new MessageElement();
                    message.setName(extension);
                    message.setValue(t);
                    message.setNamespaceURI(srwInfo.getNamespace(parm));
                    try {
                        extraDataType.getAny().add(message.getAsDOM());
                        hasExtraRequestData = true;
                    } catch (Exception e) {
                        throw new IOException(e);
                    }
                }
            }
        }
        if (hasExtraRequestData) {
            request.setExtraRequestData(extraDataType);
        }
        Stream response = null;
        try {
            response = soapBinding.searchRetrieveOperation(request, msgContext, getHandle(req));
        } catch (Exception e) {
            servletLog.error(e, e);
        }
        if (response != null) {
            ServletOutputStream out = null;
            try {
                resp.setContentType("text/xml");
                resp.setCharacterEncoding("UTF-8");
                out = resp.getOutputStream();
                IOUtils.copyAndCloseInput(response.getInputStream(), out);
            } catch (Exception e) {
                throw new IOException(e);
            } finally {
                try {
                    out.close();
                } catch (Exception e) {
                }
            }
        } else {
            resp.setContentType("text/html");
            PrintWriter writer = resp.getWriter();
            writer.println("<p>" + Messages.getMessage("noResponse01") + "</p>");
            servletLog.error("request generated no response!");
            writer.close();
        }
        //            log.info("at exit: totalMemory="+rt.totalMemory()+", freeMemory="+rt.freeMemory());
        servletLog.debug("exit processMethodRequest");
        return;
    }

    if ((operation != null && operation.equals("scan")) || scanClause != null) { // scanRequest
        int i;
        String t;
        StringBuffer sb = new StringBuffer();
        sb.append("<soap:Envelope ").append("xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" ")
                .append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ")
                .append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">").append("<soap:Header>")
                .append("<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" soap:mustUnderstand=\"1\">")
                .append("<wsse:UsernameToken>").append("<wsse:Username>eSciDocUser</wsse:Username>")
                .append("<wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">")
                .append(getHandle(req)).append("</wsse:Password>").append("</wsse:UsernameToken>")
                .append("</wsse:Security>").append("</soap:Header>").append("<soap:Body>")
                .append("<srw:scanRequest ").append("xmlns:srw=\"http://www.loc.gov/zing/srw/\">")
                .append("<srw:scanClause>");
        if (scanClause != null) {
            sb.append(encode(scanClause));
        } else
            sb.append("\"\"");
        sb.append("</srw:scanClause>");

        t = req.getParameter("responsePosition");
        if (t != null) {
            try {
                i = Integer.parseInt(t);
                if (i < 0)
                    i = Integer.MAX_VALUE;
            } catch (NumberFormatException e) {
                i = Integer.MAX_VALUE;
            }

            sb.append("<srw:responsePosition>").append(i).append("</srw:responsePosition>");
        }

        t = req.getParameter("maximumTerms");
        if (t != null) {
            try {
                i = Integer.parseInt(t);
                if (i < 1)
                    i = Integer.MAX_VALUE;
            } catch (NumberFormatException e) {
                i = Integer.MAX_VALUE;
            }

            sb.append("<srw:maximumTerms>").append(i).append("</srw:maximumTerms>");
        }

        sb.append("</srw:scanRequest></soap:Body></soap:Envelope>");
        if (servletLog.isDebugEnabled())
            servletLog.debug(sb.toString());
        msgContext.setProperty("sru", "");
        msgContext.setTargetService("SRW");
        AxisEngine engine = getEngine();
        if (servletLog.isDebugEnabled())
            servletLog.debug("request=" + sb.toString());
        ByteArrayInputStream bais = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
        Message msg = new Message(bais, false);
        msgContext.setRequestMessage(msg);
        try {
            engine.invoke(msgContext);
        } catch (Exception e) {
            servletLog.error(e, e);
        }
        Message respMsg = msgContext.getResponseMessage();
        if (respMsg != null) {
            resp.setContentType("text/xml");
            resp.setCharacterEncoding("UTF-8");
            PrintWriter writer = resp.getWriter();
            // code to strip SOAP stuff out.  Hope this can go away some day
            String soapResponse = respMsg.getSOAPPartAsString();
            int start = soapResponse.indexOf("<scanResponse");
            if (start >= 0) {
                int stop = soapResponse.indexOf("</scanResponse>");
                soapResponse = cleanup(soapResponse.substring(start, stop + 15).toCharArray());
                SRWDatabase db = (SRWDatabase) msgContext.getProperty("db");
                srwInfo.writeXmlHeader(writer, msgContext, req, db.scanStyleSheet);
            }
            writer.println(soapResponse);
            writer.close();
        } else {
            resp.setContentType("text/html");
            PrintWriter writer = resp.getWriter();
            writer.println("<p>" + Messages.getMessage("noResponse01") + "</p>");
            servletLog.error("request generated no response!");
            writer.close();
        }
        if (servletLog.isDebugEnabled()) {
            servletLog.debug("elapsed time: " + (System.currentTimeMillis() - startTime) + "ms");
            servletLog.debug("exit processMethodRequest");
        }
        return;
    }
    servletLog.error("fell through processMethodRequest!");
    servletLog.error("operation=" + operation + ", query=" + query + ", scanClause=" + scanClause);
}

From source file:ro.cs.om.web.servlet.LogoServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger.debug("doPost - START -");
    ServletOutputStream sos = null;
    logger.debug("-----------------------------------------");

    try {//from   ww w  .j av  a 2  s.c o  m
        //Servlet's OutputStream
        sos = resp.getOutputStream();
        Integer organisationId = null;
        if (req.getParameter(ORGANISATION) != null) {
            organisationId = Integer.valueOf(req.getParameter(ORGANISATION));
        } else {
            organisationId = ControllerUtils.getInstance().getOrganisationIdFromSession(req);
        }

        logger.debug("organisationId = " + organisationId);

        Logo logo = getLogo(organisationId);

        if (logo == null) {
            logo = new Logo();

            //Setting the One Pixel Picture extension
            logo.setExtension(ONE_PIXEL_PIC_EXTENSION);

            //Setting the One Pixel Picture as the picture of this logo
            String themeCode = ((UserAuth) SecurityContextHolder.getContext().getAuthentication()
                    .getPrincipal()).getThemeCode();
            String onePixelPicLocation = ONE_PIXEL_PIC_LOCATION.replace(REPLACE_THEME, themeCode);
            onePixelPicLocation = FileUtils.getInstance().getRealPathForResource(onePixelPicLocation);
            logo.setPicture(FileUtils.getInstance().getBytesFromFile(new File(onePixelPicLocation)));
        }

        //Setting response's content type after picture's extension 
        resp.setContentType(getMime(logo.getExtension()));

        logger.debug("extenstion = " + logo.getExtension());
        logger.debug("mime = " + getMime(logo.getExtension()));

        //Setting response's length (in bytes)
        resp.setContentLength(logo.getPicture().length);

        logger.debug("length = " + logo.getPicture().length);

        //Writing the picture
        dumpFile(logo, sos);

    } catch (Exception ex) {
        logger.error("", ex);
    } finally {
        //Flushing and Closing OutputStream
        sos.flush();
        sos.close();
    }
    logger.debug("doPost - END -");
}

From source file:org.openmrs.module.pmtct.util.FileExporter.java

/**
 * Auto generated method comment//w w  w  .  j a  v a 2s .c o m
 * 
 * @param request
 * @param response
 * @param patientList
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportPatientTestedInDeliveryRoomToCSVFile(HttpServletRequest request, HttpServletResponse response,
        List<Object> patientList, String filename, String title) throws Exception {
    ServletOutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        Patient p;
        PatientService ps = Context.getPatientService();

        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        outputStream.println("" + title);
        outputStream.println("Number of Patients: " + patientList.size());
        outputStream.println();
        outputStream.println(
                "No. ,Identifier, Names, Enrollment Date, DPA, Delivery Date, Result of HIV in Delivery room");
        outputStream.println();

        int ids = 0;

        Encounter cpnEnc, matEnc;

        for (Object patient : patientList) {
            Object[] o = (Object[]) patient;

            p = ps.getPatient(Integer.parseInt(o[0].toString()));
            cpnEnc = pmtctTag.getCPNEncounterInfo(p.getPatientId());
            matEnc = pmtctTag.getMaternityEncounterInfo(p.getPatientId());

            ids += 1;
            outputStream.println(ids + "," + p.getActiveIdentifiers().get(0).getIdentifier() + ","
                    + p.getPersonName() + "," + o[3].toString() + ","
                    + pmtctTag.observationValueByConcept(cpnEnc, PMTCTConstants.PREGNANT_DUE_DATE) + ","
                    + pmtctTag.observationValueByConcept(matEnc, PMTCTConstants.DATE_OF_CONFINEMENT) + ","
                    + pmtctTag.observationValueByConcept(matEnc, PMTCTConstants.RESULT_OF_HIV_TEST));
        }

        outputStream.flush();
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
}

From source file:ro.cs.om.web.servlet.ImageServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    //Picture's Id
    int pictureId = -1;
    //Picture's name
    String pictureName = null;//from   w w w. j a va 2  s .c om
    //Picture ID as a request parameter
    if (req.getParameter(PICTURE) != null) {
        try {
            pictureId = Integer.parseInt(req.getParameter(PICTURE));
        } catch (NumberFormatException nfex) {

        }

        if (pictureId == -1) {
            pictureName = req.getParameter(PICTURE);
        }
    }

    ServletOutputStream sos = null;

    try {

        //Servlet's OutputStream
        sos = resp.getOutputStream();
        Picture picture = null;

        if (pictureId > 0) {
            //Getting picture from database
            picture = getPicture(pictureId);
        } else if (pictureName != null) {
            picture = getPicture(pictureName);

            logger.debug("picture = " + picture);

            if (picture == null) {
                picture = new Picture();

                //Setting the One Pixel Picture extension
                picture.setExtension(ONE_PIXEL_PIC_EXTENSION);

                //Setting the One Pixel Picture as the picture of this logo
                String themeCode = ((UserAuth) SecurityContextHolder.getContext().getAuthentication()
                        .getPrincipal()).getThemeCode();
                String onePixelPicLocation = ONE_PIXEL_PIC_LOCATION.replace(REPLACE_THEME, themeCode);
                onePixelPicLocation = FileUtils.getInstance().getRealPathForResource(onePixelPicLocation);
                picture.setPicture(FileUtils.getInstance().getBytesFromFile(new File(onePixelPicLocation)));
            }
        }

        if (picture != null) {
            //Setting response's content type after picture's extension 
            resp.setContentType(getMime(picture.getExtension()));

            logger.debug("extenstion = " + picture.getExtension());
            logger.debug("mime = " + getMime(picture.getExtension()));

            //Setting response's length (in bytes)
            resp.setContentLength(picture.getPicture().length);

            logger.debug("length = " + picture.getPicture().length);

            //Writing the picture
            dumpFile(picture, sos);
        }

    } catch (Exception ex) {
        logger.error("", ex);
    } finally {
        //Flushing and Closing OutputStream
        sos.flush();
        sos.close();
    }
}

From source file:org.opencms.frontend.templateone.form.CmsCaptchaField.java

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

    ByteArrayOutputStream captchaImageOutput = new ByteArrayOutputStream();
    ServletOutputStream out = null;
    BufferedImage captchaImage = null;
    int maxTries = 10;
    do {
        try {

            maxTries--;
            String sessionId = cms.getRequest().getSession().getId();
            Locale locale = cms.getRequestContext().getLocale();

            captchaImage = CmsCaptchaServiceCache.getSharedInstance()
                    .getCaptchaService(m_captchaSettings, cms.getCmsObject())
                    .getImageChallengeForID(sessionId, locale);
        } catch (CaptchaException cex) {
            if (LOG.isErrorEnabled()) {
                LOG.error(cex);
                LOG.error(Messages.get().getBundle().key(Messages.LOG_ERR_CAPTCHA_CONFIG_IMAGE_SIZE_2,
                        new Object[] { m_captchaSettings.getPresetPath(), new Integer(maxTries) }));
            }
            m_captchaSettings.setImageHeight(m_captchaSettings.getImageHeight() + 40);
            m_captchaSettings.setImageWidth(m_captchaSettings.getImageWidth() + 80);
        }
    } while (captchaImage == null && maxTries > 0);
    try {

        ImageIO.write(captchaImage, "jpg", captchaImageOutput);
        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");

        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:pt.ist.expenditureTrackingSystem.presentationTier.actions.organization.OrganizationAction.java

public final ActionForward downloadUnitResponsibles(final ActionMapping mapping, final ActionForm form,
        final HttpServletRequest request, final HttpServletResponse response) throws IOException, SQLException {

    response.setContentType("application/xls ");
    response.setHeader("Content-disposition", "attachment; filename=ResponsaveisUnidades.xls");

    final ServletOutputStream outputStream = response.getOutputStream();
    final HSSFWorkbook workbook = new HSSFWorkbook();
    final ExcelStyle excelStyle = new ExcelStyle(workbook);

    final HSSFSheet sheet = workbook.createSheet("Responsaveis");
    sheet.setDefaultColumnWidth(20);/*from   w  ww.j  ava2s .  c o  m*/

    final HSSFRow row = sheet.createRow(sheet.getLastRowNum());
    createHeaderCell(excelStyle, row, 0, "Centro de Custo");
    createHeaderCell(excelStyle, row, 1, "Unidade");
    createHeaderCell(excelStyle, row, 2, "Responsvel Aprovao");
    createHeaderCell(excelStyle, row, 4, "Responsvel Despesa");

    sheet.addMergedRegion(new CellRangeAddress(0, 0, 2, 3));
    sheet.addMergedRegion(new CellRangeAddress(0, 0, 4, 5));

    for (final Unit unit : ExpenditureTrackingSystem.getInstance().getTopLevelUnitsSet()) {
        writeUnitResponsibleInfo(excelStyle, sheet, unit);
    }

    workbook.write(outputStream);

    outputStream.flush();
    outputStream.close();

    return null;
}