Example usage for javax.servlet ServletOutputStream println

List of usage examples for javax.servlet ServletOutputStream println

Introduction

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

Prototype


public void println(double d) throws IOException 

Source Link

Document

Writes a double value to the client, followed by a carriage return-line feed (CRLF).

Usage

From source file:org.inbio.ait.web.ajax.controller.PointsController.java

private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response,
        List<Specimen> specimens) throws Exception {

    response.setCharacterEncoding("ISO-8859-1");
    response.setContentType("text/xml");
    ServletOutputStream out = response.getOutputStream();

    StringBuilder result = new StringBuilder();
    result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response><specimens>");

    for (Specimen s : specimens) {
        result.append("<specimen><scientificname>" + s.getScientificname() + "</scientificname>" + "<longitude>"
                + s.getDecimallongitude() + "</longitude>" + "<catalog>" + s.getCatalognumber() + "</catalog>"
                + "<institution>" + s.getInstitutioncode() + "</institution>" + "<latitude>"
                + s.getDecimallatitude() + "</latitude></specimen>");
    }//ww  w  . j av  a2s .  co  m
    result.append("</specimens></response>");

    out.println(result.toString());
    out.flush();
    out.close();

    return null;
}

From source file:photosharing.api.conx.ProfileDefinition.java

/**
 * retrieves a profile based on the person's userid
 * /*from   www. ja v a2s . com*/
 * @see photosharing.api.base.APIDefinition#run(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public void run(HttpServletRequest request, HttpServletResponse response) {

    /**
     * check if query is empty, send SC_PRECONDITION_FAILED - 412
     */
    String query = request.getParameter("uid");
    if (query == null || query.isEmpty()) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
    }

    /**
     * get the users bearer token
     */
    HttpSession session = request.getSession(false);

    Object oData = session.getAttribute(OAuth20Handler.CREDENTIALS);
    if (oData == null) {
        logger.warning("OAuth20Data is null");
    }

    OAuth20Data data = (OAuth20Data) oData;
    String bearer = data.getAccessToken();

    try {

        /**
         * Example URL:
         * http://localhost:9080/photoSharing/api/profile?uid=self maps to
         * https://apps.collabservnext.com/profiles/atom/profileService.do
         * 
         * and results in an id for the self user, this data is ideally cached on the client. 
         */
        if (query.compareTo("self") == 0) {
            String apiUrl = getApiUrlForServiceDoc();

            Request get = Request.Get(apiUrl);
            get.addHeader("Authorization", "Bearer " + bearer);

            Executor exec = ExecutorUtil.getExecutor();
            Response apiResponse = exec.execute(get);

            HttpResponse hr = apiResponse.returnResponse();

            /**
             * Check the status codes
             */
            int code = hr.getStatusLine().getStatusCode();

            // Session is no longer valid or access token is expired - 403
            if (code == HttpStatus.SC_FORBIDDEN) {
                response.sendRedirect("./api/logout");
            }

            // User is not authorized
            // SC_UNAUTHORIZED (401)
            else if (code == HttpStatus.SC_UNAUTHORIZED) {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            }

            // Content is returned 
            // OK (200)
            else if (code == HttpStatus.SC_OK) {
                InputStream in = hr.getEntity().getContent();

                // Converts the XML to JSON
                // Alternatively, one can parse the XML using XPATH
                String jsonString = org.apache.wink.json4j.utils.XML.toJson(in);
                logger.info("json string is " + jsonString);

                JSONObject jsonObj = new JSONObject(jsonString);
                JSONObject workspace = jsonObj.getJSONObject("service").getJSONObject("workspace")
                        .getJSONObject("collection");
                String id = workspace.getString("userid");

                query = id;
            } else {
                JSONObject obj = new JSONObject();
                obj.put("error", "unexpected content");
            }

        }

        /**
         * The query should be cleansed before passing it to the backend
         * cleansing can incorporate checking that the id is a number
         * 
         * example URL
         * http://localhost:9080/photoSharing/api/profile?uid=20131674 maps
         * to https
         * ://apps.collabservnext.com/profiles/atom/profile.do?userid
         * =20131674
         * 
         * example response {"img":
         * "https:\/\/apps.collabservnext.com\/profiles\/photo.do?key=fef1b5f3-586f-4470-ab0a-a9d4251fe1ec&lastMod=1443607729019","name":"P
         * a u l Demo","email":"demo@us.ibm.com"}
         * 
         */
        String apiUrl = getApiUrl(query);
        Request get = Request.Get(apiUrl);
        get.addHeader("Authorization", "Bearer " + bearer);

        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(get);

        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes
         */
        int code = hr.getStatusLine().getStatusCode();

        // Session is no longer valid or access token is expired
        // SC_FORBIDDEN (403)
        if (code == HttpStatus.SC_FORBIDDEN) {
            response.sendRedirect("./api/logout");
        }

        // User is not authorized
        // SC_UNAUTHORIZED (401)
        else if (code == HttpStatus.SC_UNAUTHORIZED) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

        // Content is returned OK (200)
        else if (code == HttpStatus.SC_OK) {
            InputStream in = hr.getEntity().getContent();

            // Converts the XML to JSON
            // Alternatively, one can parse the XML using XPATH
            String jsonString = org.apache.wink.json4j.utils.XML.toJson(in);
            logger.info("json string is " + jsonString);

            JSONObject jsonObj = new JSONObject(jsonString);

            JSONObject entry = jsonObj.getJSONObject("feed").getJSONObject("entry");
            logger.info("entry" + entry);

            // Check if the Entry exists for the given id
            if (entry != null) {
                // Start Building the Response
                String name = "";
                String image = "";
                String email = "";

                JSONObject contributor = entry.getJSONObject("contributor");
                name = contributor.getString("name");
                email = contributor.getString("email");

                JSONArray links = entry.getJSONArray("link");

                // Scans through the links and finds the profile image
                // XPath is much more efficient
                boolean found = false;
                int idx = 0;
                int len = links.length();
                while (!found && idx < len) {
                    JSONObject link = links.getJSONObject(idx);

                    String type = link.getString("type");
                    if (type != null && !type.isEmpty() && type.compareTo("image") == 0) {
                        found = true;
                        image = link.getString("href");
                    }

                    idx++;
                }

                // Build the json to send back
                JSONObject profile = new JSONObject();
                profile.put("name", name);
                profile.put("email", email);
                profile.put("img", image);
                profile.put("userid", query);

                // Write output streams
                ServletOutputStream out = response.getOutputStream();
                profile.write(out);

            } else {
                // There is no Entry for the user with the id.
                response.setStatus(HttpStatus.SC_NOT_FOUND);
                PrintWriter out = response.getWriter();
                out.println("User does not exist");

            }

        }

        // Unexpected status
        else {
            JSONObject obj = new JSONObject();
            obj.put("error", "unexpected content");
            //Should serialize result

            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("IOException " + e.toString());
    } catch (JSONException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("JSONException " + e.toString());
    } catch (SAXException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("SAXException  " + e.toString());
    }

}

From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java

/**
 * /*from  w  w  w. jav  a2  s  .com*/
 * @param httpServletRequest
 * @param response
 * 
 * @deprecated
 */
@SuppressWarnings("unused")
private void manageTilesInformationApache(HttpServletRequest httpServletRequest, HttpServletResponse response) {
    String imageWidth = "";
    String imageHeight = "";
    String tileWidth = "";
    String tileLength = "";

    File imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path")
            + httpServletRequest.getParameter("FIF"));

    try {
        IImageMetadata metadata = Sanselan.getMetadata(imageFile);

        TiffDirectory tiffDirectory = ((TiffImageMetadata) metadata)
                .findDirectory(TiffDirectoryConstants.DIRECTORY_TYPE_ROOT);

        imageWidth = tiffDirectory.findField(TiffTagConstants.TIFF_TAG_IMAGE_WIDTH).getValue().toString();
        imageHeight = tiffDirectory.findField(TiffTagConstants.TIFF_TAG_IMAGE_LENGTH).getValue().toString();
        tileWidth = tiffDirectory.findField(TiffTagConstants.TIFF_TAG_TILE_WIDTH).getValue().toString();
        tileLength = tiffDirectory.findField(TiffTagConstants.TIFF_TAG_TILE_LENGTH).getValue().toString();
    } catch (ImageReadException imageReadException) {
        logger.error("ImageReadException", imageReadException);
    } catch (IOException ioException) {
        logger.error("IOException", ioException);
    } finally {
        try {
            /**
             * EXAMPLE OUTPUT : IIP:1.0 Max-size:1832 2448 Tile-size:128 128
             * Resolution-number:6
             **/
            response.setContentType("text/plain");
            ServletOutputStream servletOutputStream = response.getOutputStream();
            servletOutputStream.println("IIP:1.0");
            servletOutputStream.println("Max-size:" + imageWidth + " " + imageHeight);
            servletOutputStream.println("Tile-size:" + tileWidth + " " + tileLength);
            servletOutputStream.println("Resolution-number:6");
            servletOutputStream.println("");

            response.getOutputStream().flush();
        } catch (IOException ioException) {
            logger.error("IOException", ioException);
        }
    }
}

From source file:org.etudes.component.app.melete.MeleteSecurityServiceImpl.java

/**
 * {@inheritDoc}/* w ww  .j a  v  a2s  .  c om*/
 */
public HttpAccess getHttpAccess() {
    return new HttpAccess() {
        public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref,
                Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException,
                EntityAccessOverloadException, EntityCopyrightException {
            // decide on security
            if (!checkSecurity(ref)) {
                throw new EntityPermissionException(SessionManager.getCurrentSessionUserId(), "meleteDocs",
                        ref.getReference());
            }

            boolean handled = false;
            // Find the site we are coming from
            String contextId = ref.getContext();
            // isolate the ContentHosting reference
            Reference contentHostingRef = EntityManager.newReference(ref.getId());

            // setup a security advisor
            pushAdvisor();
            try {
                // make sure we have a valid ContentHosting reference with an entity producer we can talk to
                EntityProducer service = contentHostingRef.getEntityProducer();
                if (service == null)
                    throw new EntityNotDefinedException(ref.getReference());

                if (service instanceof ContentHostingService) {
                    ContentHostingService chService = (ContentHostingService) service;
                    try {
                        ContentResource content = chService.getResource(contentHostingRef.getId());
                        if (MIME_TYPE_SLTI.equals(content.getContentType())
                                || MIME_TYPE_BLTI.equals(content.getContentType())) {
                            byte[] bytes = content.getContent();
                            ResourceProperties resprops = content.getProperties();
                            String str = new String(bytes);
                            String postData = null;
                            if (BasicLTIUtil.validateDescriptor(str) != null) {
                                try {
                                    popAdvisor();
                                    // Leave ResourceBundle off for now
                                    String[] retval = SakaiBLTIUtil.postLaunchHTML(str, contextId, ref.getId(),
                                            resprops, rb);
                                    if (retval != null)
                                        postData = retval[0];
                                } catch (Exception e) {
                                    logger.info("Exception e " + e.getMessage());
                                    e.printStackTrace();
                                } finally {
                                    pushAdvisor();
                                }
                            } else // Attempt SimpleLTI
                            {
                                Properties props = null;
                                // We must remove our advisor while we do the launch and then put it back
                                // Otherwise the launch will give the user too much power
                                try {
                                    popAdvisor();
                                    props = SakaiSimpleLTI.doLaunch(str, ref.getContext(), ref.getId());
                                } catch (Exception e) {
                                    logger.info("Exception e " + e.getMessage());
                                    e.printStackTrace();
                                } finally {
                                    pushAdvisor();
                                }
                                if (props != null) {
                                    postData = props.getProperty("htmltext");
                                }
                            }

                            if (postData == null) {
                                String msg = rb.getString("not.configured", "Not configured.");
                                postData = "<p>" + msg + "</p>\n<!--\n" + str + "-->\n";
                            }

                            if (postData != null) {
                                res.setContentType("text/html");
                                ServletOutputStream out = res.getOutputStream();
                                out.println(postData);
                                handled = true;
                            }

                        }
                    } catch (Exception e) {
                        //   logger.info("Exception e "+e.getMessage());
                        //   e.printStackTrace();
                    }
                }
                if (!handled) {
                    // get the producer's HttpAccess helper, it might not support one
                    HttpAccess access = service.getHttpAccess();
                    if (access == null)
                        throw new EntityNotDefinedException(ref.getReference());

                    // let the helper do the work
                    access.handleAccess(req, res, contentHostingRef, copyrightAcceptedRefs);
                }
            } finally {
                // clear the security advisor
                popAdvisor();
            }
        }
    };
}

From source file:org.wings.session.SessionServlet.java

/**
 * this method references to/*from  ww w .j  av a2s.c  o m*/
 * {@link #doGet(HttpServletRequest, HttpServletResponse)}
 */
public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
    //value chosen to limit denial of service
    if (req.getContentLength() > getSession().getMaxContentLength() * 1024) {
        res.setContentType("text/html");
        ServletOutputStream out = res.getOutputStream();
        out.println("<html><head><meta http-equiv=\"expires\" content=\"0\"><title>Too big</title></head>");
        out.println("<body><h1>Error - content length &gt; " + getSession().getMaxContentLength() + "k");
        out.println("</h1></body></html>");
    } else {
        doGet(req, res);
    }
    // sollte man den obigen Block nicht durch folgende Zeile ersetzen?
    //throw new RuntimeException("this method must never be called!");
    // bsc: Wieso?
}

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

/**
 * Auto generated method comment//w w w.ja va  2  s. co m
 * 
 * @param outputStream
 * @param showNames
 * @param showResult
 * @param id
 */
private void displayRowValues(ServletOutputStream outputStream, VCTClient client, Integer id) {
    try {

        boolean hasPrivilegeToViewPatientNames = Context.getAuthenticatedUser()
                .hasPrivilege("View Patient Names");
        boolean hasPrivilegeToViewClientResult = Context.getAuthenticatedUser()
                .hasPrivilege("View VCT Client result");

        DateFormat df = Context.getDateFormat();

        Person p = client.getClient();
        outputStream
                .println(df.format(client.getDateOfRegistration()) + ", " + id + ", " + client.getCodeClient()
                        + ", " + ((hasPrivilegeToViewPatientNames) ? p.getPersonName() + ", " : "")
                        + p.getGender() + ", " + df.format(p.getBirthdate()) + ", "
                        + ((client.getCounselingObs() != null)
                                ? VCTTracUtil.getMessage("vcttrac.export.column.yes", null)
                                : VCTTracUtil.getMessage("vcttrac.export.column.no", null))
                        + ", "
                        + ((client.getResultObs() != null)
                                ? VCTTracUtil.getMessage("vcttrac.export.column.yes", null)
                                : VCTTracUtil.getMessage("vcttrac.export.column.no", null))
                        + ", "
                        + ((hasPrivilegeToViewClientResult)
                                ? VCTModuleTag.convsetObsValueByConcept(client.getResultObs(),
                                        VCTConfigurationUtil.getResultOfHivTestConceptId())
                                : ""));

    } catch (Exception e) {
        log.error(
                ">>VCT>>Export>>in>>CSV>>Format>> Fail to display row values #" + id + " >> " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java

/**
 * This method return image and tile information.
 * //from   w ww.  j a  v a  2  s. co m
 * EXAMPLE OUTPUT : IIP:1.0 Max-size:1832 2448 Tile-size:128 128
 * Resolution-number:6
 * 
 * @param httpServletRequest
 * @param response
 * 
 */
private void generateInformationsTiledImage(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) {
    File imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path")
            + httpServletRequest.getParameter("FIF"));
    ImageInputStream imageInputStream = null;
    Integer imageWidth = new Integer(0);
    Integer imageHeight = new Integer(0);
    Integer tileWidth = new Integer(0);
    Integer tileHeight = new Integer(0);
    Integer resolutionNumber = new Integer(0);

    try {
        if (imageFile.canRead()) {
            // Reading complete tiff information
            imageInputStream = ImageIO.createImageInputStream(imageFile);
        } else {
            logger.error("File " + imageFile.toString() + " is not present on filesystem. ");
            imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path")
                    + ApplicationPropertyManager.getApplicationProperty("iipimage.image.notavailable"));
            if (imageFile.canRead()) {
                // Reading complete tiff information
                imageInputStream = ImageIO.createImageInputStream(imageFile);
            } else {
                logger.error("File " + imageFile.toString() + " is not present on filesystem. ");
            }
        }
        if (imageInputStream != null) {
            Iterator<ImageReader> readers = ImageIO.getImageReaders(imageInputStream);
            if (readers.hasNext()) {
                ImageReader reader = readers.next();
                reader.setInput(imageInputStream, false, true);
                tileWidth = reader.getTileWidth(0);
                tileHeight = reader.getTileHeight(0);
                imageWidth = reader.getWidth(0);
                imageHeight = reader.getHeight(0);
                // Last level is not readable, I don't know why but i remove
                // this
                resolutionNumber = reader.getNumImages(true);
            }
        }
    } catch (IOException ioException) {
        logger.debug(ioException);
    } finally {
        try {
            if (imageInputStream != null) {
                imageInputStream.close();
            }
        } catch (IOException ioException) {
        }

        try {
            httpServletResponse.setContentType("text/plain");
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            servletOutputStream.println("IIP:1.0");
            servletOutputStream.println("Max-size:" + imageWidth + " " + imageHeight);
            servletOutputStream.println("Tile-size:" + tileWidth + " " + tileHeight);
            servletOutputStream.println("Resolution-number:" + resolutionNumber);
            servletOutputStream.println("");
            httpServletResponse.getOutputStream().flush();
        } catch (IOException ioException) {
            logger.error(ioException);
        }
    }
}

From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java

/**
 * //from  ww  w  .  j  a  v a2 s  .c om
 * @param httpServletRequest
 * @param httpServletResponse
 * @deprecated
 */
@SuppressWarnings("unused")
private void manageTileImageApache(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) {
    String imageWidth = "";
    String imageHeight = "";

    File imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path")
            + httpServletRequest.getParameter("FIF"));

    try {
        IImageMetadata metadata = Sanselan.getMetadata(imageFile);

        TiffDirectory tiffDirectory = ((TiffImageMetadata) metadata)
                .findDirectory(TiffDirectoryConstants.DIRECTORY_TYPE_ROOT);
        imageWidth = tiffDirectory.findField(TiffTagConstants.TIFF_TAG_IMAGE_WIDTH).getValue().toString();
        imageHeight = tiffDirectory.findField(TiffTagConstants.TIFF_TAG_IMAGE_LENGTH).getValue().toString();

        ByteSourceFile byteSource = new ByteSourceFile(imageFile);
        List<?> elements = tiffDirectory.getTiffRawImageDataElements();
        TiffImageData.Data[] data = new TiffImageData.Data[elements.size()];
        for (int i = 0; i < elements.size(); i++) {
            TiffDirectory.ImageDataElement element = (TiffDirectory.ImageDataElement) elements.get(i);
            byte[] bytes = byteSource.getBlock(element.offset, element.length);
            data[i] = new TiffImageData.Data(element.offset, element.length, bytes);
        }

        if (tiffDirectory.imageDataInStrips()) {
            TiffField rowsPerStripField = tiffDirectory.findField(TiffTagConstants.TIFF_TAG_ROWS_PER_STRIP);
            if (null == rowsPerStripField) {
                throw new ImageReadException("Can't find rows per strip field.");
            }

            int rowsPerStrip = rowsPerStripField.getIntValue();

            // DEAD STORE!!! TiffImageData.Strips strips = new
            // TiffImageData.Strips(data, rowsPerStrip);
        } else {
            TiffField tileWidthField = tiffDirectory.findField(TiffTagConstants.TIFF_TAG_TILE_WIDTH);
            if (null == tileWidthField) {
                throw new ImageReadException("Can't find tile width field.");
            }
            int tileWidth = tileWidthField.getIntValue();

            TiffField tileLengthField = tiffDirectory.findField(TiffTagConstants.TIFF_TAG_TILE_LENGTH);
            if (null == tileLengthField) {
                throw new ImageReadException("Can't find tile length field.");
            }
            int tileLength = tileLengthField.getIntValue();
        }
    } catch (ImageReadException imageReadException) {
        logger.error("ImageReadException", imageReadException);
    } catch (IOException ioException) {
        logger.error("IOException", ioException);
    } finally {
        try {
            /**
             * EXAMPLE OUTPUT : IIP:1.0 Max-size:1832 2448 Tile-size:128 128
             * Resolution-number:6
             **/
            httpServletResponse.setContentType("text/plain");
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            servletOutputStream.println("IIP:1.0");
            servletOutputStream.println("Max-Size:" + imageWidth + " " + imageHeight);
            servletOutputStream.println("Resolution-number:6");

            httpServletResponse.getOutputStream().flush();
        } catch (IOException ioException) {
            logger.error("IOException", ioException);
        }
    }
}

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

public void exportToCSVFile2(HttpServletRequest request, HttpServletResponse response, List<Object> patientList,
        String filename, String title) throws Exception {
    ServletOutputStream outputStream = null;
    try {/*ww w  . j  av a 2  s .c  o m*/
        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, Gender, BirthDay, Enrollment Date");
        outputStream.println();

        int ids = 0;

        for (Object patient : patientList) {
            Object[] o = (Object[]) patient;
            p = ps.getPatient(Integer.parseInt(o[1].toString()));
            ids += 1;
            outputStream.println(
                    ids + "," + p.getActiveIdentifiers().get(0).getIdentifier() + "," + p.getPersonName() + ","
                            + p.getGender() + "," + sdf.format(p.getBirthdate()) + "," + o[4].toString());
        }

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

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

/**
 * Auto generated method comment//from w  w w .ja  va2 s .c o m
 * 
 * @param request
 * @param response
 * @param patientList
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportToCSVFile(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, Gender, BirthDay, Enrollment Date, HIV Status");
        outputStream.println();

        int ids = 0;

        for (Object patient : patientList) {
            Object[] o = (Object[]) patient;
            p = ps.getPatient(Integer.parseInt(o[0].toString()));
            ids += 1;
            outputStream.println(ids + "," + p.getActiveIdentifiers().get(0).getIdentifier() + ","
                    + p.getPersonName() + "," + p.getGender() + "," + sdf.format(p.getBirthdate()) + ","
                    + o[3].toString() + ","
                    + pmtctTag.lastObsValueByConceptId(p.getPatientId(), PMTCTConstants.RESULT_OF_HIV_TEST));
        }

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