Example usage for org.w3c.dom Document getFirstChild

List of usage examples for org.w3c.dom Document getFirstChild

Introduction

In this page you can find the example usage for org.w3c.dom Document getFirstChild.

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:oscar.oscarLab.ca.all.web.LabDisplayHelper.java

private static void addAcknowledgment(Document doc, ReportStatus reportStatus) {
    Node rootNode = doc.getFirstChild();

    Element child = doc.createElement("ReportStatus");
    XmlUtils.appendChild(doc, child, "providerName", reportStatus.getProviderName());
    XmlUtils.appendChild(doc, child, "providerNo", reportStatus.getProviderNo());
    XmlUtils.appendChild(doc, child, "status", reportStatus.getStatus());
    XmlUtils.appendChild(doc, child, "comment",
            reportStatus.getComment() != null ? reportStatus.getComment() : "");
    XmlUtils.appendChild(doc, child, "timestamp", reportStatus.getTimestamp());
    XmlUtils.appendChild(doc, child, "segmentId", reportStatus.getID());

    rootNode.appendChild(child);/*from w  ww  . java2 s.  com*/
}

From source file:oscar.oscarLab.ca.all.web.LabDisplayHelper.java

public static ArrayList<ReportStatus> getReportStatus(Document cachedDemographicLabResultXmlData) {
    ArrayList<ReportStatus> results = new ArrayList<ReportStatus>();

    Node rootNode = cachedDemographicLabResultXmlData.getFirstChild();

    NodeList nodeList = rootNode.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);

        if ("ReportStatus".equals(node.getNodeName())) {
            results.add(toReportStatus(node));
        }/*ww  w. ja v  a  2 s . c  om*/
    }

    return (results);
}

From source file:oscar.oscarLab.ca.all.web.LabDisplayHelper.java

public static String getMultiLabId(Document cachedDemographicLabResultXmlData) {
    Node rootNode = cachedDemographicLabResultXmlData.getFirstChild();
    return (XmlUtils.getChildNodeTextContents(rootNode, "multiLabId"));
}

From source file:oscar.oscarLab.ca.all.web.LabDisplayHelper.java

public static MessageHandler getMessageHandler(Document cachedDemographicLabResultXmlData) {
    Node rootNode = cachedDemographicLabResultXmlData.getFirstChild();
    String hl7Type = XmlUtils.getChildNodeTextContents(rootNode, "hl7TextMessageType");
    String hl7Body = XmlUtils.getChildNodeTextContents(rootNode, "hl7TextMessageBody");

    return Factory.getHandler(hl7Type, hl7Body);
}

From source file:oscar.oscarLab.ca.all.web.LabDisplayHelper.java

public static String getHl7Body(Document cachedDemographicLabResultXmlData) {
    Node rootNode = cachedDemographicLabResultXmlData.getFirstChild();
    String hl7Body = XmlUtils.getChildNodeTextContents(rootNode, "hl7TextMessageBody");

    return hl7Body;
}

From source file:oscar.oscarLab.ca.all.web.LabDisplayHelper.java

public static HashMap<String, ArrayList<Map<String, Serializable>>> getMapOfTestValues(
        Document cachedDemographicLabResultXmlData) {
    try {//from ww w . ja v a 2s . c  o m
        Node rootNode = cachedDemographicLabResultXmlData.getFirstChild();
        String serialisedEncodedBytes = XmlUtils.getChildNodeTextContents(rootNode, "mapOfTestValues");
        byte[] serialisedDecodedBytes = Base64.decodeBase64(serialisedEncodedBytes);

        @SuppressWarnings("unchecked")
        HashMap<String, ArrayList<Map<String, Serializable>>> result = (HashMap<String, ArrayList<Map<String, Serializable>>>) MiscUtils
                .deserialize(serialisedDecodedBytes);

        return result;
    } catch (Exception e) {
        logger.error("Yikes, the hack code failed, good luck...", e);

        return (null);
    }
}

From source file:pl.net.ptak.PrqPrePackageMojo.java

private void preparePrerequisiteForPackaging() throws MojoFailureException {
    try {//from  w ww. j a v  a2s . c  o m
        getLog().info(String.format("Preparing %s for packaging", prerequisite.getCanonicalPath()));
        org.codehaus.plexus.util.FileUtils.copyFileToDirectory(prerequisite, prePackageFolder);
        File targetPrqFile = new File(prePackageFolder, prerequisite.getName());

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.parse(targetPrqFile);

        Element root = (Element) doc.getFirstChild();
        NodeList filesElements = root.getElementsByTagName("files");

        if (filesElements.getLength() > 1) {
            throw new MojoFailureException("There should be at most one files element");
        }

        if (filesElements.getLength() == 1) {
            Node filesList = filesElements.item(0);

            NodeList files = filesList.getChildNodes();

            for (int i = 0; i < files.getLength(); i++) {
                Node fileNode = files.item(i);

                if (!(fileNode instanceof Element)) {
                    continue;
                }

                NamedNodeMap fileAttributes = fileNode.getAttributes();

                Attr dependencyFileAttr = (Attr) fileAttributes.getNamedItem("LocalFile");

                File dependencyFile = getFileFromPrq(dependencyFileAttr, i);

                if (!dependencyFile.exists()) {
                    String message = String.format("%s is referenced in prq file, but it does not exist",
                            dependencyFile.getAbsolutePath());
                    throw new MojoFailureException(message);
                }

                // set new relative path to dependency
                setNewRelativePathForFile(dependencyFileAttr, dependencyFile);
                // calculate new md5 checksum
                Attr checkSumAttr = (Attr) fileAttributes.getNamedItem("CheckSum");
                setNewMd5ChecksumForFile(checkSumAttr, dependencyFile);
                // calculate new size
                Attr fileSizeAttr = (Attr) fileAttributes.getNamedItem("FileSize");
                setNewSizeForFile(fileSizeAttr, dependencyFile);
            }
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(targetPrqFile);
        transformer.transform(source, result);

    } catch (IOException e) {
        String message = String.format("Failed to copy %s to %s", prerequisite, prePackageFolder);
        String shortMessage = "Failed to copy resources";
        getLog().debug(message, e);
        throw new MojoFailureException(e, shortMessage, message);
    } catch (ParserConfigurationException e) {
        String message = "Failed to create prq file parser";
        String shortMessage = "Failed to prepare prerequisite for packaging";
        getLog().debug(message, e);
        throw new MojoFailureException(e, shortMessage, message);
    } catch (SAXException e) {
        String message = "Failed to modify prq file";
        String shortMessage = "Failed to prepare prerequisite for packaging";
        getLog().debug(message, e);
        throw new MojoFailureException(e, shortMessage, message);
    } catch (TransformerConfigurationException e) {
        String message = "Failed to prepare transformer for storing prq file";
        String shortMessage = "Failed to prepare prerequisite for packaging";
        getLog().debug(message, e);
        throw new MojoFailureException(e, shortMessage, message);
    } catch (TransformerException e) {
        String message = "Failed to run transformer for storing prq file";
        String shortMessage = "Failed to prepare prerequisite for packaging";
        getLog().debug(message, e);
        throw new MojoFailureException(e, shortMessage, message);
    }
}

From source file:se.unlogic.hierarchy.core.servlets.CoreServlet.java

private void addBackgroundModuleResponses(List<BackgroundModuleResponse> backgroundModuleResponses,
        Document doc, User user, HttpServletRequest req) {

    if (backgroundModuleResponses != null) {

        Element backgroundsModuleResponsesElement = doc.createElement("backgroundsModuleResponses");
        doc.getFirstChild().appendChild(backgroundsModuleResponsesElement);

        Document debugDoc;/*from  w w  w .java 2  s  . co  m*/

        // Write xml to file if debug enabled
        if (backgroundModuleXMLDebug && !StringUtils.isEmpty(this.backgroundModuleXMLDebugFile)) {

            debugDoc = XMLUtils.createDomDocument();
            debugDoc.appendChild(debugDoc.createElement("BackgroundModuleDebug"));

        } else {

            debugDoc = null;
        }

        for (BackgroundModuleResponse moduleResponse : backgroundModuleResponses) {

            if (isValidResponse(moduleResponse)) {

                if (moduleResponse.getResponseType() == ResponseType.HTML) {

                    // Append module html response
                    Element responseElement = doc.createElement("response");
                    backgroundsModuleResponsesElement.appendChild(responseElement);

                    Element htmlElement = doc.createElement("HTML");
                    responseElement.appendChild(htmlElement);

                    htmlElement.appendChild(doc.createCDATASection(moduleResponse.getHtml()));

                    this.appendSlots(moduleResponse, doc, responseElement);

                } else if (moduleResponse.getResponseType() == ResponseType.XML_FOR_CORE_TRANSFORMATION) {

                    // Append module response
                    Element responseElement = doc.createElement("response");
                    backgroundsModuleResponsesElement.appendChild(responseElement);

                    Element xmlElement = doc.createElement("XML");
                    responseElement.appendChild(xmlElement);

                    xmlElement.appendChild(doc.adoptNode(moduleResponse.getElement()));

                    this.appendSlots(moduleResponse, doc, responseElement);

                } else if (moduleResponse.getResponseType() == ResponseType.XML_FOR_SEPARATE_TRANSFORMATION) {

                    if (moduleResponse.getTransformer() != null) {

                        //Append XML to debug document
                        if (debugDoc != null) {

                            this.log.debug("Background XML debug mode enabled, appending XML from module "
                                    + moduleResponse.getModuleDescriptor() + " to XML debug document");

                            try {
                                Element documentElement = (Element) debugDoc
                                        .importNode(moduleResponse.getDocument().getDocumentElement(), true);

                                if (moduleResponse.getModuleDescriptor() != null) {

                                    documentElement.setAttribute("moduleID",
                                            moduleResponse.getModuleDescriptor().getModuleID() + "");
                                    documentElement.setAttribute("name",
                                            moduleResponse.getModuleDescriptor().getName());
                                }

                                debugDoc.getDocumentElement().appendChild(documentElement);

                            } catch (Exception e) {

                                this.log.error("Error appending XML from module "
                                        + moduleResponse.getModuleDescriptor() + " to  XML debug document", e);
                            }
                        }

                        // Transform output
                        try {
                            StringWriter stringWriter = new StringWriter();
                            this.log.debug("Background module XML transformation starting");

                            XMLTransformer.transformToWriter(moduleResponse.getTransformer(),
                                    moduleResponse.getDocument(), stringWriter, encoding);

                            this.log.debug(
                                    "Background module XML transformation finished, appending result...");

                            // Append module response

                            Element responseElement = doc.createElement("response");
                            backgroundsModuleResponsesElement.appendChild(responseElement);

                            Element htmlElement = doc.createElement("HTML");
                            responseElement.appendChild(htmlElement);

                            htmlElement.appendChild(doc.createCDATASection(stringWriter.toString()));

                            this.appendSlots(moduleResponse, doc, responseElement);

                            this.log.debug("Result appended");
                        } catch (Exception e) {
                            this.log.error("Tranformation of background module response from module"
                                    + moduleResponse.getModuleDescriptor()
                                    + " failed while processing request from user " + user + " accessing from "
                                    + req.getRemoteAddr(), e);
                        }
                    } else {
                        this.log.error(
                                "Background module response for separate transformation without attached stylesheet returned by module "
                                        + moduleResponse.getModuleDescriptor()
                                        + " while processing request from user " + user + " accessing from "
                                        + req.getRemoteAddr());
                    }
                }
            }
        }

        //Write background module XML debug to file
        if (debugDoc != null && debugDoc.getDocumentElement().hasChildNodes()) {

            log.debug("Writing background module XML debug to file " + backgroundModuleXMLDebugFile);

            try {
                XMLUtils.writeXMLFile(debugDoc,
                        this.applicationFileSystemPath + "WEB-INF/" + backgroundModuleXMLDebugFile, true,
                        encoding);

            } catch (Exception e) {

                log.error("Error writing background module XML debug to file " + backgroundModuleXMLDebugFile,
                        e);
            }
        }
    }
}

From source file:se.unlogic.hierarchy.foregroundmodules.imagegallery.GalleryModule.java

@Override
public SimpleForegroundModuleResponse defaultMethod(HttpServletRequest req, HttpServletResponse res, User user,
        URIParser uriParser) throws Exception {

    log.info("User " + user + " listing galleries");

    ArrayList<Gallery> galleryList = this.galleryDao.getAll();

    Document doc = this.createDocument(req, uriParser, user);
    Element galleriesElement = doc.createElement("galleries");
    doc.getFirstChild().appendChild(galleriesElement);

    if (galleryList != null) {
        for (Gallery gallery : galleryList) {
            if (checkBooleanAccess(user, gallery)) {
                Node galleryNode = gallery.toXML(doc);

                // get gallery random image
                SimpleEntry<String, String> pictureEntry = getRandomImage(gallery);

                if (pictureEntry != null) {
                    galleryNode.appendChild(XMLUtils.createElement("randomFile", pictureEntry.getKey(), doc));
                    galleryNode.appendChild(XMLUtils.createElement("numPics", pictureEntry.getValue(), doc));
                } else {
                    galleryNode.appendChild(XMLUtils.createElement("numPics", "0", doc));
                }//from ww w  .j  a  va2 s.  c  o  m

                galleriesElement.appendChild(galleryNode);
            }
        }
    }

    return new SimpleForegroundModuleResponse(doc, this.moduleDescriptor.getName(),
            this.getDefaultBreadcrumb());

}

From source file:se.unlogic.hierarchy.foregroundmodules.imagegallery.GalleryModule.java

@WebPublic
public SimpleForegroundModuleResponse showGallery(HttpServletRequest req, HttpServletResponse res, User user,
        URIParser uriParser) throws IOException, SQLException, URINotFoundException, AccessDeniedException {

    Gallery gallery = null;/*w  ww  . j  av a 2 s . c  o m*/

    if (uriParser.size() < 3 || uriParser.size() > 4
            || (gallery = this.galleryDao.get(uriParser.get(2).toString())) == null) {

        throw new URINotFoundException(uriParser);

    } else {

        this.checkAccess(user, gallery);

        Integer page = 1;

        if (uriParser.size() == 4) {
            page = NumberUtils.toInt(uriParser.get(3));

            if (page == null || page <= 0) {
                throw new URINotFoundException(uriParser);
            }
        }

        log.info("User " + user + " requested page " + page + " in gallery " + gallery);

        // check if path is valid
        File dir = new File(gallery.getUrl());

        if (!dir.canRead()) {
            throw new URINotFoundException(uriParser);
        }

        // check that requested page exist
        // get all filenames, only allow images
        File[] allFiles = dir.listFiles(fileFilter);

        int num = allFiles.length;

        // find number of pages in gallery
        int pagesInGallery = num % numOfThumbsPerPage == 0 ? num / numOfThumbsPerPage
                : (num / numOfThumbsPerPage) + 1;

        if (num == 0) {

            Document doc = this.createDocument(req, uriParser, user);

            Element galleryElement = doc.createElement("showGallery");
            doc.getFirstChild().appendChild(galleryElement);

            Node gNode = gallery.toXML(doc);
            gNode.appendChild(XMLUtils.createElement("pages", "1", doc));
            gNode.appendChild(XMLUtils.createElement("currentPage", "1", doc));
            gNode.appendChild(XMLUtils.createElement("numPics", "0", doc));

            galleryElement.appendChild(XMLUtils.createElement("hasUploadAccess",
                    this.checkBooleanUploadAccess(user, gallery).toString(), doc));

            galleryElement.appendChild(gNode);

            return new SimpleForegroundModuleResponse(doc, gallery.getName(), getDefaultBreadcrumb(),
                    getGalleryBreadcrumb(gallery, req));

        } else if (page <= pagesInGallery) {

            Arrays.sort(allFiles);

            // find next and previous page
            Integer nextPage = page == pagesInGallery ? null : page + 1;
            Integer prevPage = page == 1 ? null : page - 1;

            // calculate start- and endindex
            int startIndex = (numOfThumbsPerPage * page) - numOfThumbsPerPage;
            int endIndex = startIndex + numOfThumbsPerPage;
            if (page == pagesInGallery) {
                endIndex = allFiles.length;
            }

            // create XML-document containing information about the requested gallery and images
            Document doc = this.createDocument(req, uriParser, user);

            Element galleryElement = doc.createElement("showGallery");
            doc.getFirstChild().appendChild(galleryElement);

            galleryElement.appendChild(XMLUtils.createElement("hasUploadAccess",
                    this.checkBooleanUploadAccess(user, gallery).toString(), doc));

            Element filesElement = doc.createElement("files");

            Node gNode = gallery.toXML(doc);
            gNode.appendChild(XMLUtils.createElement("pages", String.valueOf(pagesInGallery), doc));
            gNode.appendChild(XMLUtils.createElement("currentPage", String.valueOf(page), doc));
            gNode.appendChild(XMLUtils.createElement("numPics", String.valueOf(num), doc));

            if (nextPage != null) {
                gNode.appendChild(XMLUtils.createElement("nextPage", nextPage.toString(), doc));
            }
            if (prevPage != null) {
                gNode.appendChild(XMLUtils.createElement("prevPage", prevPage.toString(), doc));
            }

            // find images for requested page
            for (int i = startIndex; i < endIndex; i++) {
                Element fileElement = doc.createElement("file");
                String filename = allFiles[i].getName();
                fileElement.appendChild(XMLUtils.createElement("filename", filename, doc));

                Element commentsElement = doc.createElement("comments");

                ArrayList<Comment> comments = commentDao.getByFilenameAndGallery(filename, gallery);

                if (comments != null) {
                    for (Comment comment : comments) {
                        commentsElement.appendChild(comment.toXML(doc));
                    }
                    fileElement.appendChild(commentsElement);
                }
                filesElement.appendChild(fileElement);
            }

            gNode.appendChild(filesElement);
            galleryElement.appendChild(gNode);

            return new SimpleForegroundModuleResponse(doc, gallery.getName(), getDefaultBreadcrumb(),
                    getGalleryBreadcrumb(gallery, req));

        } else {

            throw new URINotFoundException(uriParser);
        }
    }
}