Example usage for javax.servlet.http HttpServletResponse reset

List of usage examples for javax.servlet.http HttpServletResponse reset

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse reset.

Prototype

public void reset();

Source Link

Document

Clears any data that exists in the buffer as well as the status code, headers.

Usage

From source file:hu.api.SivaPlayerVideoServlet.java

private void doAction(HttpServletRequest request, HttpServletResponse response, String requestType)
        throws ServletException, IOException {

    // Check if it's an AJAX request
    this.isAJAXRequest = (request.getParameter("ajax") != null && request.getParameter("ajax").equals("true"));

    // Allow Cross-Origin-Requests
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
    response.setHeader("Access-Control-Max-Age", "1000");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");

    // URL pattern: /videoId
    // Get request parameter from URL and check if it has been set.
    // Show 400 if less or more parameters than allowed.
    String requestedVideo = request.getPathInfo();
    if (requestedVideo == null || requestedVideo.split("/").length < 2
            || requestedVideo.split("/")[1].equals("")) {
        this.sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                "The video folder has to be specified for using this web service.");
        return;//  w ww  .  j  a v a 2  s  .  c o  m
    }

    this.persistenceProvider = (IPersistenceProvider) getServletContext().getAttribute("PersistenceProvider");
    this.mailService = (MailService) getServletContext().getAttribute("mailService");
    this.brandingConfiguration = (BrandingConfiguration) getServletContext()
            .getAttribute("brandingConfiguration");

    // Check if it's a watching request
    if (request.getPathInfo().endsWith("/watch.html")) {
        this.providePlayer(request, response);
        return;
    }

    // Check if it's a log request and perform logging if so
    if (request.getPathInfo().endsWith("/log") && requestType.equals("POST")) {
        this.doLogging(request, response);
        return;
    }

    // Check if it's a checkSession request and provide session status if so
    if (requestedVideo.endsWith("/getStats.js")) {
        this.getStats(request, response);
        return;
    }

    // Check if user requests user secret and perform login
    if (request.getPathInfo().endsWith("/getSecret.js") && requestType.equals("POST")) {
        this.provideUserSecret(request, response, requestType);
        return;
    }

    // Check if current session exists and if it is allowed to access this
    // video, stop further execution, if so.
    boolean result = handleAccess(request, response, requestType);
    if (!result) {
        return;
    }

    // Check if it's collaboration request and provide data
    if (request.getPathInfo().endsWith("/getCollaboration.js")) {
        this.provideCollaboration(request, response);
        return;
    }

    // Check if it's a thread creation request
    if (request.getPathInfo().endsWith("/createCollaborationThread.js")) {
        this.createCollaborationThread(request, response);
        return;
    }

    // Check if it's a post creation request
    if (request.getPathInfo().endsWith("/createCollaborationPost.js")) {
        this.createCollaborationPost(request, response);
        return;
    }

    // Check if it's a post activation request
    if (request.getPathInfo().endsWith("/activateCollaborationPost.js")) {
        this.activateCollaborationPost(request, response);
        return;
    }

    // Check if it's a post creation request
    if (request.getPathInfo().endsWith("/deleteCollaborationThread.js")) {
        this.deleteCollaborationThread(request, response);
        return;
    }

    // Check if it's a post creation request
    if (request.getPathInfo().endsWith("/deleteCollaborationPost.js")) {
        this.deleteCollaborationPost(request, response);
        return;
    }

    // Check if it's a checkSession request and provide session status if so
    if (requestedVideo.endsWith("/checkSession.js")) {
        this.provideSessionStatus(request, response);
        return;
    }

    // Decode the file name from the URL and check if file actually exists
    // in
    // file system, send 404 if not
    File file = new File(videoPath, URLDecoder.decode(requestedVideo, "UTF-8"));
    if (!file.exists()) {
        this.sendError(response, HttpServletResponse.SC_NOT_FOUND, "File not found");
        return;
    }

    // Create log entry for file request
    this.logFileRequest(requestedVideo);

    // Check if configuration is requested and do needed preparing and
    // stop standard file preparation
    if (file.getName().equals("export.js")) {
        this.provideConfigFile(request, response, file);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;
    long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;

    // Validate request headers for caching
    // ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return
    // 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1
        // week.
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so,
    // then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1
        // week.
        return;
    }

    // Validate request headers for resume
    // ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If
    // not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range
    // -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not,
        // then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required
            // in
            // 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        // If-Range header should either match ETag or be greater then
        // LastModified. If not,
        // then return full file.
        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(eTag)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws
                // IAE
                // if
                // invalid.
                if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte
        // range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following
                // examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20
                // (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then
                // return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required
                    // in
                    // 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response
    // --------------------------------------------------------

    // Get content type by file name and set default GZIP support and
    // content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see:
    // http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // If content type is text, then determine whether GZIP content encoding
    // is supported by
    // the browser and expand content type with the one and right character
    // encoding.
    if (contentType.startsWith("text")) {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    }

    // Else, expect for images, determine content disposition. If content
    // type is supported by
    // the browser, then set to inline, else attachment which will pop a
    // 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", expires);

    // Send requested file (part(s)) to client
    // ------------------------------------------------

    // Prepare streams.
    RandomAccessFile input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new RandomAccessFile(file, "r");
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

            if (requestType.equals("GET")) {
                if (acceptsGzip) {
                    // The browser accepts GZIP, so GZIP the content.
                    response.setHeader("Content-Encoding", "gzip");
                    output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
                } else {
                    // Content length is not directly predictable in case of
                    // GZIP.
                    // So only add it if there is no means of GZIP, else
                    // browser will hang.
                    response.setHeader("Content-Length", String.valueOf(r.length));
                }

                // Copy full range.
                copy(input, output, r.start, r.length);
            }

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (requestType.equals("GET")) {
                // Copy single part range.
                copy(input, output, r.start, r.length);
            }

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (requestType.equals("GET")) {
                // Cast back to ServletOutputStream to get the easy println
                // methods.
                ServletOutputStream sos = (ServletOutputStream) output;

                // Copy multi part range.
                for (Range r : ranges) {
                    // Add multipart boundary and header fields for every
                    // range.
                    sos.println();
                    sos.println("--" + MULTIPART_BOUNDARY);
                    sos.println("Content-Type: " + contentType);
                    sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                    // Copy single part range of multi part range.
                    copy(input, output, r.start, r.length);
                }

                // End with multipart boundary.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY + "--");
            }
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

From source file:com.portfolio.data.attachment.XSLService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    /**//  w w  w  .  ja  v  a  2  s .  c om
     * Format demand:
     * <convert>
     *   <portfolioid>{uuid}</portfolioid>
     *   <portfolioid>{uuid}</portfolioid>
     *   <nodeid>{uuid}</nodeid>
     *   <nodeid>{uuid}</nodeid>
     *   <documentid>{uuid}</documentid>
     *   <xsl>{rpertoire}{fichier}</xsl>
     *   <format>[pdf rtf xml ...]</format>
     *   <parameters>
     *     <maVar1>lala</maVar1>
     *     ...
     *   </parameters>
     * </convert>
     */
    try {
        //On initialise le dataProvider
        Connection c = null;
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String origin = request.getRequestURL().toString();

    /// Variable stuff
    int userId = 0;
    int groupId = 0;
    String user = "";
    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    /// TODO: A voire si un form get ne ferait pas l'affaire aussi

    /// On lis le xml
    /*
    BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while( (line = rd.readLine()) != null )
       sb.append(line);
            
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    Document doc=null;
    try
    {
       documentBuilder = documentBuilderFactory.newDocumentBuilder();
       doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
            
    /// On lit les paramtres
    NodeList portfolioNode = doc.getElementsByTagName("portfolioid");
    NodeList nodeNode = doc.getElementsByTagName("nodeid");
    NodeList documentNode = doc.getElementsByTagName("documentid");
    NodeList xslNode = doc.getElementsByTagName("xsl");
    NodeList formatNode = doc.getElementsByTagName("format");
    NodeList parametersNode = doc.getElementsByTagName("parameters");
    //*/
    //      String xslfile = xslNode.item(0).getTextContent();
    String xslfile = request.getParameter("xsl");
    String format = request.getParameter("format");
    //      String format = formatNode.item(0).getTextContent();
    String parameters = request.getParameter("parameters");
    String documentid = request.getParameter("documentid");
    String portfolios = request.getParameter("portfolioids");
    String[] portfolioid = null;
    if (portfolios != null)
        portfolioid = portfolios.split(";");
    String nodes = request.getParameter("nodeids");
    String[] nodeid = null;
    if (nodes != null)
        nodeid = nodes.split(";");

    System.out.println("PARAMETERS: ");
    System.out.println("xsl: " + xslfile);
    System.out.println("format: " + format);
    System.out.println("user: " + userId);
    System.out.println("portfolioids: " + portfolios);
    System.out.println("nodeids: " + nodes);
    System.out.println("parameters: " + parameters);

    boolean redirectDoc = false;
    if (documentid != null) {
        redirectDoc = true;
        System.out.println("documentid @ " + documentid);
    }

    boolean usefop = false;
    String ext = "";
    if (MimeConstants.MIME_PDF.equals(format)) {
        usefop = true;
        ext = ".pdf";
    } else if (MimeConstants.MIME_RTF.equals(format)) {
        usefop = true;
        ext = ".rtf";
    }
    //// Paramtre portfolio-uuid et file-xsl
    //      String uuid = request.getParameter("uuid");
    //      String xslfile = request.getParameter("xsl");

    StringBuilder aggregate = new StringBuilder();
    try {
        int portcount = 0;
        int nodecount = 0;
        // On aggrge les donnes
        if (portfolioid != null) {
            portcount = portfolioid.length;
            for (int i = 0; i < portfolioid.length; ++i) {
                String p = portfolioid[i];
                String portfolioxml = dataProvider
                        .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0)
                        .toString();
                aggregate.append(portfolioxml);
            }
        }

        if (nodeid != null) {
            nodecount = nodeid.length;
            for (int i = 0; i < nodeid.length; ++i) {
                String n = nodeid[i];
                String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "")
                        .toString();
                aggregate.append(nodexml);
            }
        }

        // Est-ce qu'on a eu besoin d'aggrger les donnes?
        String input = aggregate.toString();
        String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration

        input = input.replaceAll(pattern, "");

        input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet ["
                + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir
                + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \""
                + servletDir + "xhtml-symbol.ent\">"
                + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir
                + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters
                "<root>" + input + "</root>";

        //         System.out.println("INPUT WITH PROXY:"+ input);

        /// Rsolution des proxys
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(input));
        Document doc = documentBuilder.parse(is);

        /// Proxy stuff
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//asmResource[@xsi_type='Proxy']";
        String filterCode = "./code/text()";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        XPathExpression codeFilter = xPath.compile(filterCode);

        for (int i = 0; i < nodelist.getLength(); ++i) {
            Node res = nodelist.item(i);
            Node gp = res.getParentNode(); // resource -> context -> container
            Node ggp = gp.getParentNode();
            Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE);

            /// Fetch node we want to replace
            String returnValue = dataProvider
                    .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "")
                    .toString();

            Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue)));
            Element repNode = rep.getDocumentElement();
            Node proxyNode = repNode.getFirstChild();
            proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned
            //            doc.replaceChild(proxyNode, gp);
            ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work.
            ggp.removeChild(gp);
        }

        try // Convert XML document to string
        {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            writer.flush();
            input = writer.toString();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }

        //         System.out.println("INPUT DATA:"+ input);

        // Setup a buffer to obtain the content length
        ByteArrayOutputStream stageout = new ByteArrayOutputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //// Setup Transformer (1st stage)
        /// Base path
        String basepath = xslfile.substring(0, xslfile.indexOf(File.separator));
        String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator
                + "xsl" + File.separator + "html2xml.xsl";
        System.out.println("FIRST: " + firstStage);
        Source xsltSrc1 = new StreamSource(new File(firstStage));
        Transformer transformer1 = transFactory.newTransformer(xsltSrc1);
        StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes()));
        Result stageRes = new StreamResult(stageout);
        transformer1.transform(stageSource, stageRes);

        // Setup Transformer (2nd stage)
        String secondStage = baseDir + File.separator + xslfile;
        Source xsltSrc2 = new StreamSource(new File(secondStage));
        Transformer transformer2 = transFactory.newTransformer(xsltSrc2);

        // Configure parameter from xml
        String[] table = parameters.split(";");
        for (int i = 0; i < table.length; ++i) {
            String line = table[i];
            int var = line.indexOf(":");
            String par = line.substring(0, var);
            String val = line.substring(var + 1);
            transformer2.setParameter(par, val);
        }

        // Setup input
        StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes()));
        //         StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") );

        Result res = null;
        if (usefop) {
            /// FIXME: Might need to include the entity for html stuff?
            //Setup FOP
            //Make sure the XSL transformation's result is piped through to FOP
            Fop fop = fopFactory.newFop(format, out);

            res = new SAXResult(fop.getDefaultHandler());

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        } else {
            res = new StreamResult(out);

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        }

        if (redirectDoc) {

            // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]
            String urlTarget = "http://" + server + "/resources/resource/file/" + documentid;
            System.out.println("Redirect @ " + urlTarget);

            HttpClientBuilder clientbuilder = HttpClientBuilder.create();
            CloseableHttpClient client = clientbuilder.build();

            HttpPost post = new HttpPost(urlTarget);
            post.addHeader("referer", origin);
            String sessionid = request.getSession().getId();
            System.out.println("Session: " + sessionid);
            post.addHeader("Cookie", "JSESSIONID=" + sessionid);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext);

            builder.addPart("uploadfile", body);

            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse ret = client.execute(post);
            String stringret = new BasicResponseHandler().handleResponse(ret);

            int code = ret.getStatusLine().getStatusCode();
            response.setStatus(code);
            ServletOutputStream output = response.getOutputStream();
            output.write(stringret.getBytes(), 0, stringret.length());
            output.close();
            client.close();

            /*
            HttpURLConnection connection = CreateConnection( urlTarget, request );
                    
            /// Helping construct Json
            connection.setRequestProperty("referer", origin);
                    
            /// Send post data
            ServletInputStream inputData = request.getInputStream();
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
                    
            byte[] buffer = new byte[1024];
            int dataSize;
            while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
            {
               writer.write(buffer, 0, dataSize);
            }
            inputData.close();
            writer.close();
                    
            RetrieveAnswer(connection, response, origin);
            //*/
        } else {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=generated" + ext);
            response.setContentType(format);
            response.setContentLength(out.size());
            response.getOutputStream().write(out.toByteArray());
            response.getOutputStream().flush();
        }
    } catch (Exception e) {
        String message = e.getMessage();
        response.setStatus(500);
        response.getOutputStream().write(message.getBytes());
        response.getOutputStream().close();

        e.printStackTrace();
    } finally {
        dataProvider.disconnect();
    }
}

From source file:com.liferay.lms.servlet.SCORMFileServerServlet.java

/**
 * Procesa los metodos HTTP GET y POST.<br>
 * Busca en la ruta que se le ha pedido el comienzo del directorio
 * "contenidos" y sirve el fichero.//from  w  w  w .ja  v a2 s  .c om
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws ServletException, java.io.IOException {
    String mime_type;
    String charset;
    String patharchivo;
    String uri;

    try {
        User user = PortalUtil.getUser(request);

        if (user == null) {
            String userId = null;
            String companyId = null;
            Cookie[] cookies = ((HttpServletRequest) request).getCookies();
            if (Validator.isNotNull(cookies)) {
                for (Cookie c : cookies) {
                    if ("COMPANY_ID".equals(c.getName())) {
                        companyId = c.getValue();
                    } else if ("ID".equals(c.getName())) {
                        userId = hexStringToStringByAscii(c.getValue());
                    }
                }
            }

            if (userId != null && companyId != null) {
                try {
                    Company company = CompanyLocalServiceUtil.getCompany(Long.parseLong(companyId));
                    Key key = company.getKeyObj();

                    String userIdPlain = Encryptor.decrypt(key, userId);

                    user = UserLocalServiceUtil.getUser(Long.valueOf(userIdPlain));

                    // Now you can set the liferayUser into a thread local
                    // for later use or
                    // something like that.

                } catch (Exception pException) {
                    throw new RuntimeException(pException);
                }
            }
        }

        String rutaDatos = SCORMContentLocalServiceUtil.getBaseDir();

        // Se comprueba que el usuario tiene permisos para acceder.
        // Damos acceso a todo el mundo al directorio "personalizacion",
        // para permitir mostrar a todos la pantalla de identificacion.
        uri = URLDecoder.decode(request.getRequestURI(), "UTF-8");
        uri = uri.substring(uri.indexOf("scorm/") + "scorm/".length());
        patharchivo = rutaDatos + "/" + uri;

        String[] params = uri.split("/");
        long groupId = GetterUtil.getLong(params[1]);
        String uuid = params[2];
        SCORMContent scormContent = SCORMContentLocalServiceUtil.getSCORMContentByUuidAndGroupId(uuid, groupId);

        boolean allowed = false;
        if (user == null) {
            user = UserLocalServiceUtil.getDefaultUser(PortalUtil.getDefaultCompanyId());
        }
        PermissionChecker pc = PermissionCheckerFactoryUtil.create(user);
        allowed = pc.hasPermission(groupId, SCORMContent.class.getName(), scormContent.getScormId(),
                ActionKeys.VIEW);
        if (!allowed) {
            AssetEntry scormAsset = AssetEntryLocalServiceUtil.getEntry(SCORMContent.class.getName(),
                    scormContent.getPrimaryKey());
            long scormAssetId = scormAsset.getEntryId();
            int typeId = new Long((new SCORMLearningActivityType()).getTypeId()).intValue();
            long[] groupIds = user.getGroupIds();
            for (long gId : groupIds) {
                List<LearningActivity> acts = LearningActivityLocalServiceUtil
                        .getLearningActivitiesOfGroupAndType(gId, typeId);
                for (LearningActivity act : acts) {
                    String entryId = LearningActivityLocalServiceUtil.getExtraContentValue(act.getActId(),
                            "assetEntry");
                    if (Validator.isNotNull(entryId) && Long.valueOf(entryId) == scormAssetId) {
                        allowed = pc.hasPermission(gId, LearningActivity.class.getName(), act.getActId(),
                                ActionKeys.VIEW);
                        if (allowed) {
                            break;
                        }
                    }
                }
                if (allowed) {
                    break;
                }
            }

        }
        if (allowed) {

            File archivo = new File(patharchivo);

            // Si el archivo existe y no es un directorio se sirve. Si no,
            // no se hace nada.
            if (archivo.exists() && archivo.isFile()) {

                // El content type siempre antes del printwriter
                mime_type = MimeTypesUtil.getContentType(archivo);
                charset = "";
                if (archivo.getName().toLowerCase().endsWith(".html")
                        || archivo.getName().toLowerCase().endsWith(".htm")) {
                    mime_type = "text/html";
                    if (isISO(FileUtils.readFileToString(archivo))) {
                        charset = "ISO-8859-1";
                    }
                }
                if (archivo.getName().toLowerCase().endsWith(".swf")) {
                    mime_type = "application/x-shockwave-flash";
                }
                if (archivo.getName().toLowerCase().endsWith(".mp4")) {
                    mime_type = "video/mp4";
                }
                if (archivo.getName().toLowerCase().endsWith(".flv")) {
                    mime_type = "video/x-flv";
                }
                response.setContentType(mime_type);
                if (Validator.isNotNull(charset)) {
                    response.setCharacterEncoding(charset);

                }
                response.addHeader("Content-Type",
                        mime_type + (Validator.isNotNull(charset) ? "; " + charset : ""));
                /*if (archivo.getName().toLowerCase().endsWith(".swf")
                      || archivo.getName().toLowerCase().endsWith(".flv")) {
                   response.addHeader("Content-Length",
                String.valueOf(archivo.length()));
                }
                */
                if (archivo.getName().toLowerCase().endsWith("imsmanifest.xml")) {
                    FileInputStream fis = new FileInputStream(patharchivo);

                    String sco = ParamUtil.get(request, "scoshow", "");
                    Document manifest = SAXReaderUtil.read(fis);
                    if (sco.length() > 0) {

                        Element organizatEl = manifest.getRootElement().element("organizations")
                                .element("organization");
                        Element selectedItem = selectItem(organizatEl, sco);
                        if (selectedItem != null) {
                            selectedItem.detach();
                            java.util.List<Element> items = organizatEl.elements("item");
                            for (Element item : items) {

                                organizatEl.remove(item);
                            }
                            organizatEl.add(selectedItem);
                        }
                    }
                    //clean unused resources.
                    Element resources = manifest.getRootElement().element("resources");
                    java.util.List<Element> theResources = resources.elements("resource");
                    Element organizatEl = manifest.getRootElement().element("organizations")
                            .element("organization");
                    java.util.List<String> identifiers = getIdentifierRefs(organizatEl);
                    for (Element resource : theResources) {
                        String identifier = resource.attributeValue("identifier");
                        if (!identifiers.contains(identifier)) {
                            resources.remove(resource);
                        }
                    }
                    response.getWriter().print(manifest.asXML());
                    fis.close();
                    return;

                }

                if (mime_type.startsWith("text") || mime_type.endsWith("javascript")
                        || mime_type.equals("application/xml")) {

                    java.io.OutputStream out = response.getOutputStream();
                    FileInputStream fis = new FileInputStream(patharchivo);

                    byte[] buffer = new byte[512];
                    int i = 0;

                    while (fis.available() > 0) {
                        i = fis.read(buffer);
                        if (i == 512)
                            out.write(buffer);
                        else
                            out.write(buffer, 0, i);

                    }

                    fis.close();
                    out.flush();
                    out.close();
                    return;
                }
                //If not manifest
                String fileName = archivo.getName();
                long length = archivo.length();
                long lastModified = archivo.lastModified();
                String eTag = fileName + "_" + length + "_" + lastModified;
                long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;
                String ifNoneMatch = request.getHeader("If-None-Match");
                if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("ETag", eTag); // Required in 304.
                    response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
                    return;
                }
                long ifModifiedSince = request.getDateHeader("If-Modified-Since");
                if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.setHeader("ETag", eTag); // Required in 304.
                    response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
                    return;
                }

                // If-Match header should contain "*" or ETag. If not, then return 412.
                String ifMatch = request.getHeader("If-Match");
                if (ifMatch != null && !matches(ifMatch, eTag)) {
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                    return;
                }

                // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
                long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
                if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                    return;
                }

                // Validate and process range -------------------------------------------------------------

                // Prepare some variables. The full Range represents the complete file.
                Range full = new Range(0, length - 1, length);
                List<Range> ranges = new ArrayList<Range>();

                // Validate and process Range and If-Range headers.
                String range = request.getHeader("Range");
                if (range != null) {

                    // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
                    if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
                        response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                        return;
                    }

                    // If-Range header should either match ETag or be greater then LastModified. If not,
                    // then return full file.
                    String ifRange = request.getHeader("If-Range");
                    if (ifRange != null && !ifRange.equals(eTag)) {
                        try {
                            long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                            if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                                ranges.add(full);
                            }
                        } catch (IllegalArgumentException ignore) {
                            ranges.add(full);
                        }
                    }

                    // If any valid If-Range header, then process each part of byte range.
                    if (ranges.isEmpty()) {
                        for (String part : range.substring(6).split(",")) {
                            // Assuming a file with length of 100, the following examples returns bytes at:
                            // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                            long start = sublong(part, 0, part.indexOf("-"));
                            long end = sublong(part, part.indexOf("-") + 1, part.length());

                            if (start == -1) {
                                start = length - end;
                                end = length - 1;
                            } else if (end == -1 || end > length - 1) {
                                end = length - 1;
                            }

                            // Check if Range is syntactically valid. If not, then return 416.
                            if (start > end) {
                                response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                                return;
                            }

                            // Add range.
                            ranges.add(new Range(start, end, length));
                        }
                    }
                }
                boolean acceptsGzip = false;
                String disposition = "inline";

                if (mime_type.startsWith("text")) {
                    //String acceptEncoding = request.getHeader("Accept-Encoding");
                    // acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
                    // mime_type += ";charset=UTF-8";
                }

                // Else, expect for images, determine content disposition. If content type is supported by
                // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
                else if (!mime_type.startsWith("image")) {
                    String accept = request.getHeader("Accept");
                    disposition = accept != null && accepts(accept, mime_type) ? "inline" : "attachment";
                }

                // Initialize response.
                response.reset();
                response.setBufferSize(DEFAULT_BUFFER_SIZE);
                response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
                response.setHeader("Accept-Ranges", "bytes");
                response.setHeader("ETag", eTag);
                response.setDateHeader("Last-Modified", lastModified);
                response.setDateHeader("Expires", expires);

                // Send requested file (part(s)) to client ------------------------------------------------

                // Prepare streams.
                RandomAccessFile input = null;
                OutputStream output = null;

                try {
                    // Open streams.
                    input = new RandomAccessFile(archivo, "r");
                    output = response.getOutputStream();

                    if (ranges.isEmpty() || ranges.get(0) == full) {

                        // Return full file.
                        Range r = full;
                        response.setContentType(mime_type);
                        response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

                        if (content) {

                            // Content length is not directly predictable in case of GZIP.
                            // So only add it if there is no means of GZIP, else browser will hang.
                            response.setHeader("Content-Length", String.valueOf(r.length));

                            // Copy full range.
                            copy(input, output, r.start, r.length);
                        }

                    } else if (ranges.size() == 1) {

                        // Return single part of file.
                        Range r = ranges.get(0);
                        response.setContentType(mime_type);
                        response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
                        response.setHeader("Content-Length", String.valueOf(r.length));
                        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

                        if (content) {
                            // Copy single part range.
                            copy(input, output, r.start, r.length);
                        }

                    } else {

                        // Return multiple parts of file.
                        response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
                        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

                        if (content) {
                            // Cast back to ServletOutputStream to get the easy println methods.
                            ServletOutputStream sos = (ServletOutputStream) output;

                            // Copy multi part range.
                            for (Range r : ranges) {
                                // Add multipart boundary and header fields for every range.
                                sos.println();
                                sos.println("--" + MULTIPART_BOUNDARY);
                                sos.println("Content-Type: " + mime_type);
                                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                                // Copy single part range of multi part range.
                                copy(input, output, r.start, r.length);
                            }

                            // End with multipart boundary.
                            sos.println();
                            sos.println("--" + MULTIPART_BOUNDARY + "--");
                        }
                    }
                } finally {
                    // Gently close streams.
                    close(output);
                    close(input);
                }
            } else {
                //java.io.OutputStream out = response.getOutputStream();
                response.sendError(404);
                //out.write(uri.getBytes());
            }
        } else {
            response.sendError(401);
        }
    } catch (Exception e) {
        System.out.println("Error en el processRequest() de ServidorArchivos: " + e.getMessage());
    }
}

From source file:us.mn.state.health.lims.reports.send.sample.action.influenza.InfluenzaSampleXMLBySampleProcessAction.java

protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String forward = FWD_SUCCESS;
    BaseActionForm dynaForm = (BaseActionForm) form;
    ActionMessages errors = null;//from   w w  w  .  ja va2  s.co m

    request.setAttribute(ALLOW_EDITS_KEY, "false");
    request.setAttribute(PREVIOUS_DISABLED, "true");
    request.setAttribute(NEXT_DISABLED, "true");

    // get transmission resources properties
    ResourceLocator rl = ResourceLocator.getInstance();
    // Now load a java.util.Properties object with the
    // properties
    transmissionMap = new Properties();
    try {
        propertyStream = rl.getNamedResourceAsInputStream(ResourceLocator.XMIT_PROPERTIES);

        transmissionMap.load(propertyStream);
    } catch (IOException e) {
        //bugzilla 2154
        LogEvent.logError("InfluenzaSampleXMLBySampleProcessAction", "performAction()", e.toString());
        throw new LIMSRuntimeException("Unable to load transmission resource mappings.", e);
    } finally {
        if (null != propertyStream) {
            try {
                propertyStream.close();
                propertyStream = null;
            } catch (Exception e) {
                //bugzilla 2154
                LogEvent.logError("InfluenzaSampleXMLBySampleProcessAction", "performAction()", e.toString());
            }
        }
    }

    String byDateRange = (String) dynaForm.get("byDateRange");
    String bySampleRange = (String) dynaForm.get("bySampleRange");
    String bySample = (String) dynaForm.get("bySample");

    String fromAccessionNumber = "";
    String toAccessionNumber = "";

    String accessionNumber1 = "";
    String accessionNumber2 = "";
    String accessionNumber3 = "";
    String accessionNumber4 = "";
    String accessionNumber5 = "";
    String accessionNumber6 = "";
    String accessionNumber7 = "";
    String accessionNumber8 = "";
    String accessionNumber9 = "";

    String fromReleasedDateForDisplay = "";
    String toReleasedDateForDisplay = "";

    String formName = dynaForm.getDynaClass().getName().toString();

    SampleDAO sampleDAO = new SampleDAOImpl();
    SampleItemDAO sampleItemDAO = new SampleItemDAOImpl();
    AnalysisDAO analysisDAO = new AnalysisDAOImpl();
    String humanDomain = SystemConfiguration.getInstance().getHumanDomain();
    List sampleStatuses = new ArrayList();

    List samplesUnfiltered = new ArrayList();
    List samples = new ArrayList();
    boolean eligibleForReporting = false;
    List analyses = null;

    Map testLevelCriteriaMap = null;

    // server-side validation (validation.xml)
    //this should take care of released date validation
    //only do this if released date range download is selected since nothing else is validated
    //through validation.xml
    errors = dynaForm.validate(mapping, request);
    if (errors != null && errors.size() > 0) {
        saveErrors(request, errors);
        return mapping.findForward(FWD_FAIL);
    }

    //BY DATE RANGE - get samples that meet selection criteria
    if (byDateRange.equals(TRUE)) {

        fromReleasedDateForDisplay = (String) dynaForm.getString("fromReleasedDateForDisplay");
        toReleasedDateForDisplay = (String) dynaForm.getString("toReleasedDateForDisplay");

        String messageKey = "error.sample.xml.by.sample.flu.begindate.lessthan.enddate";
        if (StringUtil.isNullorNill(fromReleasedDateForDisplay)
                || StringUtil.isNullorNill(toReleasedDateForDisplay)) {
            ActionError error = new ActionError("error.sample.xml.by.sample.flu.begindate.lessthan.enddate",
                    null, null);
            errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        }

        String locale = SystemConfiguration.getInstance().getDefaultLocale().toString();
        java.sql.Date convertedFromReleasedDate = DateUtil
                .convertStringDateToSqlDate(fromReleasedDateForDisplay, locale);
        java.sql.Date convertedToReleasedDate = DateUtil.convertStringDateToSqlDate(toReleasedDateForDisplay,
                locale);

        sampleStatuses.add(SystemConfiguration.getInstance().getSampleStatusEntry2Complete());
        sampleStatuses.add(SystemConfiguration.getInstance().getSampleStatusReleased());
        samplesUnfiltered = sampleDAO.getSamplesByStatusAndDomain(sampleStatuses, humanDomain);

        analyses = null;

        for (int j = 0; j < samplesUnfiltered.size(); j++) {
            Sample sample = (Sample) samplesUnfiltered.get(j);
            SampleItem sampleItem = new SampleItem();
            sampleItem.setSample(sample);
            sampleItemDAO.getDataBySample(sampleItem);
            analyses = analysisDAO.getMaxRevisionAnalysesBySample(sampleItem);

            eligibleForReporting = false;
            //find at least one eligible test to report on
            for (int i = 0; i < analyses.size(); i++) {
                Analysis analysis = (Analysis) analyses.get(i);

                //only process influenza type samples
                if (!TestService.getLocalizedAugmentedTestName(analysis.getTest()).toLowerCase()
                        .startsWith(HL7_INFLUENZA_TEST_DESCRIPTION)
                        && !TestService.getLocalizedTestName(analysis.getTest())
                                .equals(HL7_INFLUENZA_TEST_NAME)) {
                    continue;
                }

                //analysis must be released
                if (!analysis.getStatus()
                        .equals(SystemConfiguration.getInstance().getAnalysisStatusReleased())) {
                    continue;
                }
                //NOW FILTER ON ANALYSIS RELEASED DATE
                if (!analysis.getReleasedDate().before(convertedFromReleasedDate)
                        && !analysis.getReleasedDate().after(convertedToReleasedDate)) {
                    eligibleForReporting = true;
                }
            }
            if (eligibleForReporting)
                samples.add(sample);
        }
        testLevelCriteriaMap = new HashMap();
        testLevelCriteriaMap.put("fromReleasedDate", convertedFromReleasedDate);
        testLevelCriteriaMap.put("toReleasedDate", convertedToReleasedDate);

    }

    //BY SAMPLE RANGE - get samples that meet selection criteria
    if (bySampleRange.equals(TRUE)) {
        fromAccessionNumber = (String) dynaForm.get("fromAccessionNumber");
        toAccessionNumber = (String) dynaForm.get("toAccessionNumber");

        if (!StringUtil.isNullorNill(fromAccessionNumber)) {
            errors = validateAccessionNumber(request, errors, fromAccessionNumber, formName);
        }
        if (!StringUtil.isNullorNill(toAccessionNumber)) {
            errors = validateAccessionNumber(request, errors, fromAccessionNumber, formName);
        }

        String messageKey = "sample.accessionNumber";
        if (!StringUtil.isNullorNill(fromAccessionNumber) && !StringUtil.isNullorNill(toAccessionNumber)) {
            int fromInt = Integer.parseInt(fromAccessionNumber);
            int thruInt = Integer.parseInt(toAccessionNumber);

            if (fromInt > thruInt) {
                ActionError error = new ActionError("errors.range.accessionnumber.from.less.to",
                        getMessageForKey(messageKey), null);
                errors.add(ActionMessages.GLOBAL_MESSAGE, error);
            }
        } else {
            ActionError error = new ActionError("errors.invalid", getMessageForKey(messageKey), null);
            errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        }

        if (errors != null && errors.size() > 0) {
            saveErrors(request, errors);
            request.setAttribute(ALLOW_EDITS_KEY, "false");

            return mapping.findForward(FWD_FAIL);
        }

        List accessionNumbers = populateAccessionNumberList(fromAccessionNumber, toAccessionNumber);
        samplesUnfiltered = createSampleObjectsFromAccessionNumbers(accessionNumbers);

        analyses = null;

        for (int j = 0; j < samplesUnfiltered.size(); j++) {
            Sample sample = (Sample) samplesUnfiltered.get(j);
            sampleDAO.getSampleByAccessionNumber(sample);
            if (sample.getDomain().equals(humanDomain)
                    && sample.getStatus()
                            .equals(SystemConfiguration.getInstance().getSampleStatusEntry2Complete())
                    || sample.getStatus().equals(SystemConfiguration.getInstance().getSampleStatusReleased())) {
                SampleItem sampleItem = new SampleItem();
                sampleItem.setSample(sample);
                sampleItemDAO.getDataBySample(sampleItem);
                analyses = analysisDAO.getMaxRevisionAnalysesBySample(sampleItem);

                eligibleForReporting = false;
                //find at least one eligible test to report on
                for (int i = 0; i < analyses.size(); i++) {
                    Analysis analysis = (Analysis) analyses.get(i);

                    //only process influenza type samples
                    if (!TestService.getLocalizedAugmentedTestName(analysis.getTest()).toLowerCase()
                            .startsWith(HL7_INFLUENZA_TEST_DESCRIPTION)
                            && !TestService.getLocalizedTestName(analysis.getTest())
                                    .equals(HL7_INFLUENZA_TEST_NAME)) {
                        continue;
                    }

                    //analysis must be released
                    if (!analysis.getStatus()
                            .equals(SystemConfiguration.getInstance().getAnalysisStatusReleased())) {
                        continue;
                    }
                    eligibleForReporting = true;
                }
            }
            if (eligibleForReporting)
                samples.add(sample);
        }

    }

    //BY SAMPLE - get samples that meet selection criteria
    if (bySample.equals(TRUE)) {
        accessionNumber1 = (String) dynaForm.get("accessionNumber1");
        accessionNumber2 = (String) dynaForm.get("accessionNumber2");
        accessionNumber3 = (String) dynaForm.get("accessionNumber3");
        accessionNumber4 = (String) dynaForm.get("accessionNumber4");
        accessionNumber5 = (String) dynaForm.get("accessionNumber5");
        accessionNumber6 = (String) dynaForm.get("accessionNumber6");
        accessionNumber7 = (String) dynaForm.get("accessionNumber7");
        accessionNumber8 = (String) dynaForm.get("accessionNumber8");
        accessionNumber9 = (String) dynaForm.get("accessionNumber9");

        List accessionNumbers = new ArrayList();
        if (!StringUtil.isNullorNill(accessionNumber1)) {
            errors = validateAccessionNumber(request, errors, accessionNumber1, formName);
            accessionNumbers.add(accessionNumber1);
        }
        if (!StringUtil.isNullorNill(accessionNumber2)) {
            errors = validateAccessionNumber(request, errors, accessionNumber2, formName);
            accessionNumbers.add(accessionNumber2);
        }
        if (!StringUtil.isNullorNill(accessionNumber3)) {
            errors = validateAccessionNumber(request, errors, accessionNumber3, formName);
            accessionNumbers.add(accessionNumber3);
        }
        if (!StringUtil.isNullorNill(accessionNumber4)) {
            errors = validateAccessionNumber(request, errors, accessionNumber4, formName);
            accessionNumbers.add(accessionNumber4);
        }
        if (!StringUtil.isNullorNill(accessionNumber5)) {
            errors = validateAccessionNumber(request, errors, accessionNumber5, formName);
            accessionNumbers.add(accessionNumber5);
        }
        if (!StringUtil.isNullorNill(accessionNumber6)) {
            errors = validateAccessionNumber(request, errors, accessionNumber6, formName);
            accessionNumbers.add(accessionNumber6);
        }
        if (!StringUtil.isNullorNill(accessionNumber7)) {
            errors = validateAccessionNumber(request, errors, accessionNumber7, formName);
            accessionNumbers.add(accessionNumber7);
        }
        if (!StringUtil.isNullorNill(accessionNumber8)) {
            errors = validateAccessionNumber(request, errors, accessionNumber8, formName);
            accessionNumbers.add(accessionNumber8);
        }
        if (!StringUtil.isNullorNill(accessionNumber9)) {
            errors = validateAccessionNumber(request, errors, accessionNumber9, formName);
            accessionNumbers.add(accessionNumber9);
        }

        if (errors != null && errors.size() > 0) {
            saveErrors(request, errors);
            request.setAttribute(ALLOW_EDITS_KEY, "false");

            return mapping.findForward(FWD_FAIL);
        }
        samplesUnfiltered = createSampleObjectsFromAccessionNumbers(accessionNumbers);

        analyses = null;

        for (int j = 0; j < samplesUnfiltered.size(); j++) {
            Sample sample = (Sample) samplesUnfiltered.get(j);
            sampleDAO.getSampleByAccessionNumber(sample);
            if (sample.getDomain().equals(humanDomain)
                    && sample.getStatus()
                            .equals(SystemConfiguration.getInstance().getSampleStatusEntry2Complete())
                    || sample.getStatus().equals(SystemConfiguration.getInstance().getSampleStatusReleased())) {
                SampleItem sampleItem = new SampleItem();
                sampleItem.setSample(sample);
                sampleItemDAO.getDataBySample(sampleItem);
                analyses = analysisDAO.getMaxRevisionAnalysesBySample(sampleItem);

                eligibleForReporting = false;
                //find at least one eligible test to report on
                for (int i = 0; i < analyses.size(); i++) {
                    Analysis analysis = (Analysis) analyses.get(i);

                    //only process influenza type samples
                    if (!TestService.getLocalizedAugmentedTestName(analysis.getTest()).toLowerCase()
                            .startsWith(HL7_INFLUENZA_TEST_DESCRIPTION)
                            && !TestService.getLocalizedTestName(analysis.getTest())
                                    .equals(HL7_INFLUENZA_TEST_NAME)) {
                        continue;
                    }

                    //analysis must be released
                    if (!analysis.getStatus()
                            .equals(SystemConfiguration.getInstance().getAnalysisStatusReleased())) {
                        continue;
                    }
                    eligibleForReporting = true;
                }
            }
            if (eligibleForReporting)
                samples.add(sample);
        }

    }

    // initialize the form
    dynaForm.initialize(mapping);

    // 1926 get sysUserId from login module
    UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA);
    String sysUserId = String.valueOf(usd.getSystemUserId());

    org.hibernate.Transaction tx = HibernateUtil.getSession().beginTransaction();

    try {

        // marshall to XML
        Mapping castorMapping = new Mapping();

        String castorMappingName = transmissionMap.getProperty("SampleToXmlInfluenzaMapping");

        InputSource source = getSource(castorMappingName);

        InfluenzaSampleXMLBySampleHelper helper = new InfluenzaSampleXMLBySampleHelper();
        List messages = new ArrayList();
        BatchMessageXmit batchMessage = new BatchMessageXmit();
        for (int i = 0; i < samples.size(); i++) {
            Sample sample = (Sample) samples.get(i);
            MessageXmit message = helper.getXMLMessage(sample, testLevelCriteriaMap);
            if (message != null) {
                messages.add(message);
            }
        }

        if (messages != null && messages.size() > 1) {
            batchMessage.setMessages((ArrayList) messages);
        } else {
            batchMessage = null;
        }

        //if there is no message or batchmessage then create Exception
        if (batchMessage == null && (messages == null || messages.size() == 0 || (messages.get(0) == null))) {
            Exception e = new LIMSCannotCreateXMLException("Cannot generate XML for selection");

            throw new LIMSRuntimeException("Error in InfluenzaSampleXMLBySampleProcessAction ", e);

        }
        // castorMapping.loadMapping(url);
        castorMapping.loadMapping(source);

        // Marshaller marshaller = new Marshaller(
        // new OutputStreamWriter(System.out));
        String fileName = "";
        if (batchMessage != null) {
            if (byDateRange.equals(TRUE)) {
                fileName = FILENAME_PREFIX + fromReleasedDateForDisplay.replaceAll("/", "") + "_"
                        + toReleasedDateForDisplay.replaceAll("/", "") + ".xml";
            } else if (bySample.equals(TRUE)) {
                fileName = FILENAME_PREFIX + "multiple_samples" + ".xml";
            } else if (bySampleRange.equals(TRUE)) {
                fileName = FILENAME_PREFIX + fromAccessionNumber + "_" + toAccessionNumber + ".xml";
            }
        } else {
            MessageXmit msg = (MessageXmit) messages.get(0);
            Sample samp = msg.getSample().getSample();
            String accessionNumber = samp.getAccessionNumber();
            fileName = FILENAME_PREFIX + accessionNumber + ".xml";
        }
        Marshaller marshaller = new Marshaller();
        marshaller.setMapping(castorMapping);
        Writer writer = new StringWriter();
        marshaller.setWriter(writer);
        if (batchMessage != null) {
            marshaller.marshal(batchMessage);
        } else {
            if (messages != null && messages.size() > 0) {
                marshaller.marshal((MessageXmit) messages.get(0));
            }
        }
        xmlString = writer.toString();

        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //response.setContentType("application/xml");
        response.setContentType("multipart/xml");
        response.setContentLength((int) xmlString.length());

        OutputStream os = response.getOutputStream();
        byte[] xmlBytes = xmlString.getBytes();
        ByteArrayInputStream bais = new ByteArrayInputStream(xmlBytes);
        InputStream is = (InputStream) bais;
        int count;
        byte buf[] = new byte[4096];
        while ((count = is.read(buf)) > -1)
            os.write(buf, 0, count);
        is.close();
        os.close();

        xmlString = "";

        tx.commit();
    } catch (LIMSRuntimeException lre) {
        LogEvent.logError("InfluenzaSampleXMLBySampleProcessAction", "performAction()", lre.toString());
        tx.rollback();

        errors = new ActionMessages();
        ActionError error = null;

        if (lre.getException() instanceof LIMSCannotCreateXMLException) {
            error = new ActionError("errors.CannotCreateXMLException", null, null);

        } else {
            error = new ActionError("errors.GetException", null, null);

        }

        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        saveErrors(request, errors);
        request.setAttribute(Globals.ERROR_KEY, errors);
        request.setAttribute(ALLOW_EDITS_KEY, "false");
        return mapping.findForward(FWD_FAIL);

    } catch (Exception e) {
        LogEvent.logError("InfluenzaSampleXMLBySampleProcessAction", "performAction()", e.toString());
        tx.rollback();

        errors = new ActionMessages();
        ActionError error = null;

        error = new ActionError("errors.CannotCreateXMLException", null, null);
        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        saveErrors(request, errors);
        request.setAttribute(Globals.ERROR_KEY, errors);
        request.setAttribute(ALLOW_EDITS_KEY, "false");
        return mapping.findForward(FWD_FAIL);
    } finally {
        HibernateUtil.closeSession();
    }

    PropertyUtils.setProperty(dynaForm, "fromAccessionNumber", fromAccessionNumber);
    PropertyUtils.setProperty(dynaForm, "toAccessionNumber", toAccessionNumber);

    PropertyUtils.setProperty(dynaForm, "accessionNumber1", accessionNumber1);
    PropertyUtils.setProperty(dynaForm, "accessionNumber2", accessionNumber2);
    PropertyUtils.setProperty(dynaForm, "accessionNumber3", accessionNumber3);
    PropertyUtils.setProperty(dynaForm, "accessionNumber4", accessionNumber4);
    PropertyUtils.setProperty(dynaForm, "accessionNumber5", accessionNumber5);
    PropertyUtils.setProperty(dynaForm, "accessionNumber6", accessionNumber6);
    PropertyUtils.setProperty(dynaForm, "accessionNumber7", accessionNumber7);
    PropertyUtils.setProperty(dynaForm, "accessionNumber8", accessionNumber8);
    PropertyUtils.setProperty(dynaForm, "accessionNumber9", accessionNumber9);

    PropertyUtils.setProperty(dynaForm, "fromReleasedDateForDisplay", fromReleasedDateForDisplay);
    PropertyUtils.setProperty(dynaForm, "toReleasedDateForDisplay", toReleasedDateForDisplay);

    return mapping.findForward(forward);
}

From source file:us.mn.state.health.lims.reports.send.sample.action.SampleXMLBySampleProcessAction.java

License:asdf

protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String forward = FWD_SUCCESS;
    BaseActionForm dynaForm = (BaseActionForm) form;
    ActionMessages errors = null;//ww  w  .  j  a va2  s .  com

    request.setAttribute(ALLOW_EDITS_KEY, "false");
    request.setAttribute(PREVIOUS_DISABLED, "true");
    request.setAttribute(NEXT_DISABLED, "true");

    // CHANGED

    String xmlString = null;
    // get transmission resources properties
    ResourceLocator rl = ResourceLocator.getInstance();
    // Now load a java.util.Properties object with the
    // properties
    transmissionMap = new Properties();
    try {
        propertyStream = rl.getNamedResourceAsInputStream(ResourceLocator.XMIT_PROPERTIES);

        transmissionMap.load(propertyStream);
    } catch (IOException e) {
        //bugzilla 2154
        LogEvent.logError("SampleXMLBySampleProcessAction", "performAction()", e.toString());
        throw new LIMSRuntimeException("Unable to load transmission resource mappings.", e);
    } finally {
        if (null != propertyStream) {
            try {
                propertyStream.close();
                propertyStream = null;
            } catch (Exception e) {
                //bugzilla 2154
                LogEvent.logError("SampleXMLBySampleProcessAction", "performAction()", e.toString());
            }
        }
    }

    String accessionNumber = (String) dynaForm.get("accessionNumber");

    // PROCESS

    String humanDomain = SystemConfiguration.getInstance().getHumanDomain();
    String animalDomain = SystemConfiguration.getInstance().getAnimalDomain();

    try {

        PatientDAO patientDAO = new PatientDAOImpl();
        PersonDAO personDAO = new PersonDAOImpl();
        ProviderDAO providerDAO = new ProviderDAOImpl();
        SampleDAO sampleDAO = new SampleDAOImpl();
        SampleItemDAO sampleItemDAO = new SampleItemDAOImpl();
        SampleHumanDAO sampleHumanDAO = new SampleHumanDAOImpl();
        SampleOrganizationDAO sampleOrganizationDAO = new SampleOrganizationDAOImpl();
        AnalysisDAO analysisDAO = new AnalysisDAOImpl();
        ResultDAO resultDAO = new ResultDAOImpl();
        TypeOfSampleDAO typeOfSampleDAO = new TypeOfSampleDAOImpl();
        SourceOfSampleDAO sourceOfSampleDAO = new SourceOfSampleDAOImpl();
        OrganizationDAO organizationDAO = new OrganizationDAOImpl();
        TestTrailerDAO testTrailerDAO = new TestTrailerDAOImpl();
        TypeOfTestResultDAO typeOfTestResultDAO = new TypeOfTestResultDAOImpl();

        // for overall message portion of message
        MessageXmit message = new MessageXmit();

        // for UHL portion of message
        UHLXmit uhl = new UHLXmit();
        Organization organization = new Organization();
        TestingFacilityXmit uhlFacility = new TestingFacilityXmit();
        //bugzilla 2069
        organization.setOrganizationLocalAbbreviation(
                SystemConfiguration.getInstance().getMdhOrganizationIdForXMLTransmission());
        organization = organizationDAO.getOrganizationByLocalAbbreviation(organization, true);

        StringBuffer orgName = new StringBuffer();
        orgName.append(organization.getOrganizationName());
        orgName.append(SystemConfiguration.getInstance().getDefaultTransmissionTextSeparator());
        orgName.append(organization.getStreetAddress());
        orgName.append(SystemConfiguration.getInstance().getDefaultTransmissionTextSeparator());
        orgName.append(organization.getCity());
        orgName.append(SystemConfiguration.getInstance().getDefaultTransmissionTextSeparator());
        orgName.append(organization.getState());
        orgName.append(SystemConfiguration.getInstance().getDefaultTransmissionTextSeparator());
        orgName.append(organization.getZipCode());
        orgName.append(SystemConfiguration.getInstance().getDefaultTransmissionTextSeparator());
        orgName.append(SystemConfiguration.getInstance().getMdhPhoneNumberForXMLTransmission());

        uhl.setId(SystemConfiguration.getInstance().getMdhUhlIdForXMLTransmission());
        uhlFacility.setOrganizationName(orgName.toString());
        uhlFacility.setUniversalId(SystemConfiguration.getInstance().getMdhUniversalIdForXMLTransmission());
        uhlFacility.setUniversalIdType(
                SystemConfiguration.getInstance().getMdhUniversalIdTypeForXMLTransmission());

        uhl.setFacility(uhlFacility);
        uhl.setApplicationName(SystemConfiguration.getInstance().getDefaultApplicationName());
        uhl.setMessageTime((new Timestamp(System.currentTimeMillis())).toString());
        uhl.setProcessingId(SystemConfiguration.getInstance().getDefaultProcessingIdForXMLTransmission());
        uhl.setTransportMethod(SystemConfiguration.getInstance().getDefaultTransportMethodForXMLTransmission());

        PatientXmit patient = new PatientXmit();
        Person person = new Person();
        ProviderXmit provider = new ProviderXmit();
        FacilityXmit facility = new FacilityXmit();
        Person providerPerson = new Person();
        SampleHuman sampleHuman = new SampleHuman();
        SampleOrganization sampleOrganization = new SampleOrganization();
        List analyses = null;
        SourceOfSample sourceOfSample = new SourceOfSample();
        TypeOfSample typeOfSample = new TypeOfSample();

        Sample sample = new Sample();
        SampleItem sampleItem = new SampleItem();
        sample.setAccessionNumber(accessionNumber);
        sampleDAO.getSampleByAccessionNumber(sample);

        sampleHuman.setSampleId(sample.getId());
        sampleHumanDAO.getDataBySample(sampleHuman);
        sampleOrganization.setSampleId(sample.getId());
        sampleOrganizationDAO.getDataBySample(sampleOrganization);
        //bugzilla 1773 need to store sample not sampleId for use in sorting
        sampleItem.setSample(sample);
        sampleItemDAO.getDataBySample(sampleItem);
        patient.setId(sampleHuman.getPatientId());
        patientDAO.getData(patient);
        person = patient.getPerson();
        personDAO.getData(person);

        provider.setId(sampleHuman.getProviderId());
        providerDAO.getData(provider);
        providerPerson = provider.getPerson();
        personDAO.getData(providerPerson);
        //bugzilla 2227
        analyses = analysisDAO.getMaxRevisionAnalysesBySample(sampleItem);

        for (int i = 0; i < analyses.size(); i++) {
            Analysis analysis = (Analysis) analyses.get(i);
            sampleItemDAO.getData(sampleItem);
            sourceOfSample.setId(sampleItem.getSourceOfSampleId());
            if (!StringUtil.isNullorNill(sourceOfSample.getId())) {
                sourceOfSampleDAO.getData(sourceOfSample);
            }
            typeOfSample.setId(sampleItem.getTypeOfSampleId());
            if (!StringUtil.isNullorNill(typeOfSample.getId())) {
                typeOfSampleDAO.getData(typeOfSample);
            }

            // System.out.println("This is sampleItem " + sampleItem);
            if (sampleItem != null) {
                //bugzilla 1773 need to store sample not sampleId for use in sorting
                String sampleId = sampleItem.getSample().getId();
                SampleXmit sampleXmit = new SampleXmit();

                sampleXmit.setId(sampleId);
                sampleDAO.getData(sampleXmit);

                // marshall to XML
                Mapping castorMapping = new Mapping();

                String castorMappingName = transmissionMap.getProperty("SampleToXmlMapping");

                InputSource source = getSource(castorMappingName);

                // bugzilla #1346 add ability to hover over accession
                // number and
                // view patient/person information (first and last name
                // and external id)

                String domain = sampleXmit.getDomain();

                if (domain != null && domain.equals(humanDomain)) {
                    // go to human view

                    // bugzilla #1346 add ability to hover over
                    // accession number and
                    // view patient/person information (first and last
                    // name and external id)

                    if (!StringUtil.isNullorNill(sampleXmit.getId())) {

                        sampleHuman.setSampleId(sampleXmit.getId());
                        sampleHumanDAO.getDataBySample(sampleHuman);
                        sampleOrganization.setSampleId(sampleXmit.getId());
                        sampleOrganizationDAO.getDataBySample(sampleOrganization);
                        //bugzilla 1827 set id = external id AFTER getting data
                        patient.setId(sampleHuman.getPatientId());
                        patientDAO.getData(patient);
                        // per Nancy 01/12/2007
                        // this should be external id (if none just patient
                        // id because we can't send null
                        if (!StringUtil.isNullorNill(patient.getExternalId())) {
                            patient.setId(patient.getExternalId());
                        } else {
                            patient.setId(sampleHuman.getPatientId());
                        }
                        person.setId(patient.getPerson().getId());
                        personDAO.getData(person);

                        // do we need to set id on patient to be externalId?
                        patient.setLastName(person.getLastName());
                        patient.setFirstName(person.getFirstName());
                        patient.setStreetAddress(person.getState());
                        patient.setCity(person.getCity());
                        patient.setState(person.getState());
                        patient.setZipCode(person.getZipCode());
                        patient.setHomePhone(person.getHomePhone());

                        provider.setId(sampleHuman.getProviderId());
                        providerDAO.getData(provider);
                        providerPerson = provider.getPerson();
                        personDAO.getData(providerPerson);
                        Organization o = sampleOrganization.getOrganization();
                        if (o != null) {
                            PropertyUtils.copyProperties(facility, provider);
                            // per Nancy 01/12/2007
                            // have added null check
                            if (!StringUtil.isNullorNill(o.getCliaNum())) {
                                facility.setId(o.getCliaNum());
                            }
                            facility.setOrganizationName(o.getOrganizationName());
                            facility.setDepartment(o.getOrganizationName());
                            facility.setStreetAddress(o.getStreetAddress());
                            facility.setCity(o.getCity());
                            facility.setState(o.getState());
                            facility.setZipCode(o.getZipCode());
                        }

                        provider.setWorkPhone(providerPerson.getWorkPhone());
                        provider.setLastName(providerPerson.getLastName());
                        provider.setFirstName(providerPerson.getFirstName());

                        if (StringUtil.isNullorNill(sampleXmit.getRevision())) {
                            sampleXmit.setRevision("0");
                        }
                        sampleXmit.setExternalId(patient.getExternalId());
                        if (StringUtil.isNullorNill(sampleXmit.getStatus())) {
                            sampleXmit.setStatus("THIS IS SAMPLE STATUS - IF BLANK SHOULD WE SEND DEFAULT");
                        }
                        sampleXmit.setPatient(patient);
                        sampleXmit.setProvider(provider);
                        sampleXmit.setFacility(facility);

                        // get all tests for this sample
                        //bugzilla 2227
                        analyses = analysisDAO.getMaxRevisionAnalysesBySample(sampleItem);
                        ArrayList sampleTests = new ArrayList();
                        // assemble Test Elements
                        for (int j = 0; j < analyses.size(); j++) {
                            TestXmit sampleTest = new TestXmit();
                            Analysis a = (Analysis) analyses.get(j);
                            Test t = a.getTest();
                            sampleTest.setMethod(t.getMethodName());
                            sampleTest.setReleasedDate(a.getReleasedDate());

                            if (sourceOfSample != null
                                    && !StringUtil.isNullorNill(sourceOfSample.getDescription())) {
                                sampleTest.setSourceOfSample(sourceOfSample.getDescription());
                            }
                            if (typeOfSample != null
                                    && !StringUtil.isNullorNill(typeOfSample.getDescription())) {
                                sampleTest.setTypeOfSample(typeOfSample.getDescription());
                            }
                            CodeElementXmit testName = new CodeElementXmit();
                            // do we need go to receiver_xref to get
                            // their test name? identifier, codesystem
                            // type,
                            testName.setIdentifier(TestService.getLocalizedTestName(a.getTest()));
                            testName.setCodeSystemType("L");
                            testName.setText("This is some kind of text");
                            sampleTest.setName(testName);

                            TestTrailer testTrailer = t.getTestTrailer();

                            CommentXmit testComment = new CommentXmit();
                            if (testTrailer != null) {
                                testComment.setComment(testTrailer.getText());
                                testComment.setCommentSource("");
                            }
                            sampleTest.setComment(testComment);

                            sampleTest.setStatus("This could be analysis status");

                            // NOW GET THE RESULTS FOR THIS TEST
                            TestResultDAO testResultDAO = new TestResultDAOImpl();
                            DictionaryDAO dictDAO = new DictionaryDAOImpl();

                            // load collection of
                            // TestAnalyte_TestResults for the
                            // test
                            TestAnalyteDAO testAnalyteDAO = new TestAnalyteDAOImpl();
                            List testAnalytes = testAnalyteDAO.getAllTestAnalytesPerTest(t);
                            ArrayList testResults = new ArrayList();

                            for (int k = 0; k < testAnalytes.size(); k++) {
                                TestAnalyte testAnalyte = (TestAnalyte) testAnalytes.get(k);
                                Result result = new Result();

                                resultDAO.getResultByAnalysisAndAnalyte(result, analysis, testAnalyte);
                                ResultXmit resultXmit = new ResultXmit();
                                if (result != null && !StringUtil.isNullorNill(result.getId())) {

                                    // we have at least one result so
                                    // add this
                                    TestResult testResult = result.getTestResult();
                                    String value = null;
                                    if (testResult.getTestResultType()
                                            .equals(SystemConfiguration.getInstance().getDictionaryType())) {
                                        // get from dictionary
                                        Dictionary dictionary = new Dictionary();
                                        dictionary.setId(testResult.getValue());
                                        dictDAO.getData(dictionary);
                                        // System.out.println("setting
                                        // dictEntry "
                                        // + dictionary.getDictEntry());
                                        value = dictionary.getDictEntry();
                                    } else {
                                        value = testResult.getValue();
                                    }

                                    // now create other objects
                                    // within the result
                                    ObservationXmit observationXmit = new ObservationXmit();
                                    CodeElementXmit observationIdentifier = new CodeElementXmit();
                                    Analyte analyte = testAnalyte.getAnalyte();
                                    if (!StringUtil.isNullorNill(analyte.getExternalId())) {
                                        observationIdentifier.setIdentifier(analyte.getExternalId());
                                    } else {
                                        observationIdentifier.setIdentifier(analyte.getId());
                                    }
                                    observationIdentifier.setText(analyte.getAnalyteName());
                                    observationIdentifier.setCodeSystemType(SystemConfiguration.getInstance()
                                            .getDefaultTransmissionCodeSystemType());
                                    observationXmit.setIdentifier(observationIdentifier);
                                    observationXmit.setValue(value);
                                    //bugzilla 1866
                                    TypeOfTestResult totr = new TypeOfTestResult();
                                    totr.setTestResultType(testResult.getTestResultType());
                                    totr = typeOfTestResultDAO.getTypeOfTestResultByType(totr);
                                    observationXmit.setValueType(totr.getHl7Value());
                                    //end bugzilla 1866
                                    resultXmit.setObservation(observationXmit);

                                    //bugzilla 1867 remove empty tags
                                    //resultXmit.setReferenceRange("UNKNOWN");
                                    resultXmit.setReferenceRange(null);
                                    /*CodeElementXmit unitCodeElement = new CodeElementXmit();
                                    unitCodeElement
                                          .setIdentifier("UNKNOWN");
                                    unitCodeElement.setText("UNKNOWN");
                                    unitCodeElement
                                          .setCodeSystemType(SystemConfiguration
                                                .getInstance()
                                                .getDefaultTransmissionCodeSystemType());*/
                                    //resultXmit.setUnit(unitCodeElement);
                                    resultXmit.setUnit(null);
                                    //end bugzilla 1867

                                }
                                testResults.add(resultXmit);

                            }

                            // END RESULTS FOR TEST

                            sampleTest.setResults(testResults);
                            sampleTest.setReleasedDate(analysis.getReleasedDate());

                            // there is a requirement that there is at least
                            // one result for a test
                            if (testResults.size() > 0) {
                                sampleTests.add(sampleTest);
                            }

                        }
                        sampleXmit.setTests(sampleTests);

                        message.setSample(sampleXmit);
                        message.setUhl(uhl);
                        try {
                            // castorMapping.loadMapping(url);
                            castorMapping.loadMapping(source);

                            // Marshaller marshaller = new Marshaller(
                            // new OutputStreamWriter(System.out));
                            //bugzilla 2393
                            String fileName = FILENAME_PREFIX + accessionNumber + ".xml";
                            Marshaller marshaller = new Marshaller();
                            marshaller.setMapping(castorMapping);
                            Writer writer = new StringWriter();
                            marshaller.setWriter(writer);
                            marshaller.marshal(message);
                            xmlString = writer.toString();

                            //bugzilla 2393 allow for download of file
                            response.reset();
                            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                            //response.setContentType("application/xml");
                            response.setContentType("multipart/xml");
                            response.setContentLength((int) xmlString.length());

                            try {
                                OutputStream os = response.getOutputStream();
                                byte[] xmlBytes = xmlString.getBytes();
                                ByteArrayInputStream bais = new ByteArrayInputStream(xmlBytes);
                                InputStream is = (InputStream) bais;
                                int count;
                                byte buf[] = new byte[4096];
                                while ((count = is.read(buf)) > -1)
                                    os.write(buf, 0, count);
                                is.close();
                                os.close();
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            } //end try/catch

                            //no need to display xml - we are saving a file instead
                            xmlString = "";
                            //xmlString = convertToDisplayableXML(xmlString);
                        } catch (Exception e) {
                            //bugzilla 2154
                            LogEvent.logError("SampleXMLBySampleProcessAction", "performAction()",
                                    e.toString());
                        }

                        // this writes a default mapping to oc4j's
                        // j2ee/home directory
                        /*
                         * try { MappingTool tool = new MappingTool();
                         * tool.setForceIntrospection(false);
                         * tool.addClass("us.mn.state.health.lims.patient.valueholder.Patient");
                         * tool.write(new FileWriter("XMLTestMapping.xml")); }
                         * catch(MappingException ex){
                         * System.out.println("Error" +
                         * ex.getLocalizedMessage());} catch(IOException
                         * ex){ System.out.println("Error" +
                         * ex.getLocalizedMessage());}
                         */

                    }

                } else if (domain != null && domain.equals(animalDomain)) {
                    // go to animal view
                    // System.out.println("Going to animal view");
                } else {
                    // go toother view
                }
            }
        }
    } catch (LIMSRuntimeException lre) {
        // if error then forward to fail and don't update to blank
        // page
        // = false

        //bugzilla 2154
        LogEvent.logError("SampleXMLBySampleProcessAction", "performAction()", lre.toString());
        errors = new ActionMessages();
        ActionError error = null;
        error = new ActionError("errors.GetException", null, null);
        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        saveErrors(request, errors);
        request.setAttribute(Globals.ERROR_KEY, errors);
        request.setAttribute(ALLOW_EDITS_KEY, "false");
        return mapping.findForward(FWD_FAIL);

    }

    // END PROCESS
    // initialize the form
    dynaForm.initialize(mapping);

    PropertyUtils.setProperty(dynaForm, "accessionNumber", accessionNumber);
    // PropertyUtils.setProperty(dynaForm, "xmlString",
    // "&lt;ajdf&gt;asdfasdf&lt;/ajdf&gt;");
    PropertyUtils.setProperty(dynaForm, "xmlString", xmlString);

    return mapping.findForward(forward);
}