Example usage for org.w3c.dom Element getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java

/**
 * Pull data files (pdb and images) for a given experiment
 * @param fileTreeXmlPath Path to XML file representing the project file tree
 * @param workflowXmlPath Path to XML file representing the experiment workflow
 * @param dataDirPath Path to directory used to store data files
 * @throws SAXException/*from w w  w.java  2  s  .  co  m*/
 * @throws IOException
 * @throws XPathExpressionException 
 * @throws ParserConfigurationException 
 * @throws TransformerException 
 */
private void pullDataFilesForExperiment(String fileTreeXmlPath, String workflowXmlPath, String dataDirPath)
        throws SAXException, IOException, XPathExpressionException, ParserConfigurationException,
        TransformerException {

    if (outputToConsole)
        System.out.println("Copying analysis data files...");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document fileTreeDoc = docBuilder.parse(fileTreeXmlPath);
    fileTreeDoc = Utils.normalizeXmlDoc(fileTreeDoc);

    Element fileTreeRootElt = (Element) fileTreeDoc.getDocumentElement().getChildNodes().item(0);
    String dirPath = fileTreeRootElt.getAttribute("absolutePath");

    XPathReader xreader = new XPathReader(fileTreeDoc);

    //load XML representation of experiment workflow
    Document docWorkflow = docBuilder.parse(workflowXmlPath);
    docWorkflow = Utils.normalizeXmlDoc(docWorkflow);
    Element workflowRootElt = (Element) docWorkflow.getDocumentElement();

    //find main structure for display in Jmol
    Element jmolElt = pullJmolFile(fileTreeDoc, fileTreeRootElt, xreader, dataDirPath, dirPath);
    if (jmolElt != null)
        workflowRootElt.appendChild(docWorkflow.importNode(jmolElt, true));

    //find analysis data
    NodeList matchingFiles = (NodeList) xreader.read("//file[AVUs/AVU[@id='" + FileMetadata.FILE_CLASS
            + "' and text()='" + FileMetadata.FILE_CLASS_ANALYSIS.toUpperCase() + "']]",
            XPathConstants.NODESET);

    //add publication information
    //Element dirNode = (Element)fileTreeDoc.getDocumentElement().getFirstChild();
    //dirNode.setAttribute("publisher", workflowRootElt.getAttribute("publisher"));
    //dirNode.setAttribute("publicationDate", workflowRootElt.getAttribute("publicationDate"));

    //analysis data
    if (matchingFiles != null && matchingFiles.getLength() > 0) {
        Element dataElt = docWorkflow.createElement("analysis");
        workflowRootElt.appendChild(dataElt);

        Element imgElt = docWorkflow.createElement("images");
        Element pdbElt = docWorkflow.createElement("structures");
        Element csvElts = docWorkflow.createElement("spreadsheets");
        Element otherDataElts = docWorkflow.createElement("unknowns");

        dataElt.appendChild(imgElt);
        dataElt.appendChild(csvElts);
        dataElt.appendChild(pdbElt);
        dataElt.appendChild(otherDataElts);

        PlotGenerator plotTool = new PlotGenerator();

        for (int f = 0; f < matchingFiles.getLength(); f++) {
            Element fileNode = (Element) matchingFiles.item(f);
            String dataFilePath = fileNode.getAttribute("absolutePath");
            //copy file
            String dataFileNewName = dataFilePath.substring(dirPath.length() + 1)
                    .replaceAll(PATH_FOLDER_SEPARATOR_REGEX, "_");
            String dataFileDestPath = dataDirPath + PATH_FOLDER_SEPARATOR + dataFileNewName;
            Files.copy(Paths.get(dataFilePath), Paths.get(dataFileDestPath),
                    StandardCopyOption.REPLACE_EXISTING);
            //set read permissions
            if (!Utils.isWindows()) {
                HashSet<PosixFilePermission> permissions = new HashSet<PosixFilePermission>();
                permissions.add(PosixFilePermission.OWNER_READ);
                permissions.add(PosixFilePermission.OWNER_WRITE);
                permissions.add(PosixFilePermission.OWNER_EXECUTE);
                permissions.add(PosixFilePermission.GROUP_READ);
                permissions.add(PosixFilePermission.OTHERS_READ);
                Files.setPosixFilePermissions(Paths.get(dataFileDestPath), permissions);
            }
            //read file AVUs
            NodeList avuNodes = (NodeList) xreader.read("//file[@absolutePath='" + dataFilePath + "']/AVUs/AVU",
                    XPathConstants.NODESET);
            MetadataAVUList avuList = new MetadataAVUList();
            if (avuNodes != null) {
                for (int a = 0; a < avuNodes.getLength(); a++) {
                    Element avuNode = (Element) avuNodes.item(a);
                    avuList.add(new MetadataAVU(avuNode.getAttribute("id").toUpperCase(),
                            avuNode.getFirstChild().getNodeValue()));
                }
            }

            //add reference in XML doc
            String description = avuList.getValue(FileMetadata.FILE_DESCRIPTION);
            String format = fileNode.getAttribute("format");
            if (IBIOMESFileGroup.isJmolFile(format)) {
                Element jmolFileElt = docWorkflow.createElement("structure");
                jmolFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    jmolFileElt.setAttribute("description", description);
                pdbElt.appendChild(jmolFileElt);
            } else if (format.equals(LocalFile.FORMAT_CSV)) {
                Element csvElt = docWorkflow.createElement("spreadsheet");
                csvElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    csvElt.setAttribute("description", description);
                csvElts.appendChild(csvElt);
                //try to generate plot and save image
                try {
                    String imgPath = dataFileNewName + "_plot.png";
                    String plotType = generatePlotForCSV(plotTool, dataFileDestPath, avuList,
                            dataFileDestPath + "_plot", "png");
                    csvElt.setAttribute("plotPath", imgPath);
                    if (outputToConsole) {
                        if (plotType == null)
                            plotType = "";
                        else
                            plotType += " ";
                        System.out.println("\t" + plotType + "plot generated for " + dataFileNewName);
                    }

                } catch (Exception e) {
                    if (outputToConsole)
                        System.out.println(
                                "Warning: Plot for '" + dataFileDestPath + "' could not be generated.");
                    try {
                        if (IBIOMESConfiguration.getInstance().isOutputErrorStackToConsole())
                            e.printStackTrace();
                    } catch (Exception e1) {
                    }
                }
            } else if (IBIOMESFileGroup.isImageFile(format)) {
                Element imgFileElt = docWorkflow.createElement("image");
                imgFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    imgFileElt.setAttribute("description", description);
                imgElt.appendChild(imgFileElt);
            } else {
                Element otherFileElt = docWorkflow.createElement("unknown");
                otherFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    otherFileElt.setAttribute("description", description);
                imgElt.appendChild(otherDataElts);
            }
        }
    }

    //update XML files
    File outputXmlAvusFile = new File(fileTreeXmlPath);
    if (outputXmlAvusFile.exists())
        outputXmlAvusFile.delete();

    File outputXmlWorkflowFile = new File(workflowXmlPath);
    if (outputXmlWorkflowFile.exists())
        outputXmlWorkflowFile.delete();

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    DOMSource source = new DOMSource(fileTreeDoc);
    StreamResult result = null;
    result = new StreamResult(fileTreeXmlPath);
    transformer.transform(source, result);

    source = new DOMSource(docWorkflow);
    result = null;
    result = new StreamResult(outputXmlWorkflowFile);
    transformer.transform(source, result);
}

From source file:com.amalto.workbench.actions.XSDPasteConceptAction.java

public Map<String, List<String>> cloneXSDAnnotation(XSDAnnotation oldAnn) {
    XSDAnnotation xsdannotation = XSDFactory.eINSTANCE.createXSDAnnotation();
    Map<String, List<String>> infor = new HashMap<String, List<String>>();
    try {// w  ww .ja v  a2  s.  co  m
        /*
         * Element oldAnnElem =oldAnn.getElement(); Element newAnnElem = (Element)oldAnnElem.cloneNode(true);
         * xsdannotation.setElement(newAnnElem);
         */

        /*
         * List<Element> listAppInfo = new ArrayList<Element>(); List<Element> listUserInfo = new
         * ArrayList<Element>(); List<Attr> listAttri = new ArrayList<Attr>();
         */
        if (oldAnn != null) {
            for (int i = 0; i < oldAnn.getApplicationInformation().size(); i++) {
                Element oldElem = oldAnn.getApplicationInformation().get(i);
                // System.out.println(oldElem.getAttributes().getNamedItem(
                // "source").getNodeValue());
                String type = oldElem.getAttributes().getNamedItem(Messages.XSDPasteConceptAction_Source)
                        .getNodeValue();
                /*
                 * Element newElem = (Element) oldElem.cloneNode(true);
                 * listAppInfo.add(oldAnn.getApplicationInformation().get(i));
                 */
                if (!infor.containsKey(type)) {
                    List<String> typeList = new ArrayList<String>();
                    typeList.add(oldElem.getFirstChild().getNodeValue());
                    infor.put(type, typeList);
                } else {
                    infor.get(type).add(oldElem.getFirstChild().getNodeValue());
                }
            }
            /*
             * xsdannotation.getApplicationInformation().addAll(listAppInfo);
             *
             * for (int i = 0; i < oldAnn.getUserInformation().size(); i++) { Element oldElemUserInfo =
             * oldAnn.getUserInformation() .get(i); Element newElemUserInfo = (Element) oldElemUserInfo
             * .cloneNode(true); listUserInfo.add(newElemUserInfo);
             *
             * } xsdannotation.getUserInformation().addAll(listUserInfo);
             *
             * for (int i = 0; i < oldAnn.getAttributes().size(); i++) { Attr oldAttri =
             * oldAnn.getAttributes().get(i); Attr newAtri = (Attr) oldAttri.cloneNode(true);
             * listAttri.add(newAtri); } xsdannotation.getAttributes().addAll(listAttri);
             */
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(this.page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages.XSDPasteConceptAction_ErrorMsg2, e.getLocalizedMessage()));
    }
    return infor;
}

From source file:it.iit.genomics.cru.structures.bridges.uniprot.UniprotkbUtils.java

private Collection<MoleculeEntry> getUniprotEntriesXML(String location, boolean waitAndRetryOnFailure)
        throws BridgesRemoteAccessException {

    String url = location + "&format=xml";

    ArrayList<MoleculeEntry> uniprotEntries = new ArrayList<>();
    try {/*from ww  w  .  j a v  a 2 s  .  c  om*/
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
        HttpGet request = new HttpGet(url);

        // add request header
        request.addHeader("User-Agent", USER_AGENT);

        HttpResponse response = client.execute(request);

        if (response.getEntity().getContentLength() == 0) {
            // No result
            return uniprotEntries;
        }

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(response.getEntity().getContent()));

        // optional, but recommended
        // read this -
        // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        // interaction structure
        NodeList entryList = doc.getElementsByTagName("entry");

        for (int i = 0; i < entryList.getLength(); i++) {

            Element entryElement = (Element) entryList.item(i);

            String dataset = entryElement.getAttribute("dataset");

            String ac = entryElement.getElementsByTagName("accession").item(0).getFirstChild().getNodeValue();

            MoleculeEntry uniprotEntry = new MoleculeEntry(ac);

            uniprotEntry.setDataset(dataset);

            // Taxid
            Element organism = (Element) entryElement.getElementsByTagName("organism").item(0);

            String organismCommonName = null;
            String organismScientificName = null;
            String organismOtherName = null;

            NodeList organismNames = organism.getElementsByTagName("name");

            for (int j = 0; j < organismNames.getLength(); j++) {

                Element reference = (Element) organismNames.item(j);
                switch (reference.getAttribute("type")) {
                case "scientific":
                    organismScientificName = reference.getTextContent();
                    break;
                case "common":
                    organismCommonName = reference.getTextContent();
                    break;
                default:
                    organismOtherName = reference.getTextContent();
                    break;
                }
            }

            if (null != organismCommonName) {
                uniprotEntry.setOrganism(organismCommonName);
            } else if (null != organismScientificName) {
                uniprotEntry.setOrganism(organismScientificName);
            } else if (null != organismOtherName) {
                uniprotEntry.setOrganism(organismOtherName);
            }

            NodeList organismReferences = organism.getElementsByTagName("dbReference");

            for (int j = 0; j < organismReferences.getLength(); j++) {
                Element reference = (Element) organismReferences.item(j);
                if (reference.hasAttribute("type") && "NCBI Taxonomy".equals(reference.getAttribute("type"))) {
                    String proteinTaxid = reference.getAttribute("id");
                    uniprotEntry.setTaxid(proteinTaxid);
                }
            }

            // GENE
            NodeList geneNames = entryElement.getElementsByTagName("gene");

            for (int j = 0; j < geneNames.getLength(); j++) {
                Element gene = (Element) geneNames.item(j);

                NodeList nameList = gene.getElementsByTagName("name");

                for (int k = 0; k < nameList.getLength(); k++) {
                    Element name = (Element) nameList.item(k);
                    uniprotEntry.addGeneName(name.getFirstChild().getNodeValue());
                }
            }

            // modified residues
            HashMap<String, ModifiedResidue> modifiedResidues = new HashMap<>();

            NodeList features = entryElement.getElementsByTagName("feature");
            for (int j = 0; j < features.getLength(); j++) {
                Element feature = (Element) features.item(j);

                if (false == entryElement.equals(feature.getParentNode())) {
                    continue;
                }

                // ensembl
                if (feature.hasAttribute("type") && "modified residue".equals(feature.getAttribute("type"))) {

                    String description = feature.getAttribute("description").split(";")[0];

                    if (false == modifiedResidues.containsKey(description)) {
                        modifiedResidues.put(description, new ModifiedResidue(description));
                    }

                    NodeList locations = feature.getElementsByTagName("location");
                    for (int k = 0; k < locations.getLength(); k++) {
                        Element loc = (Element) locations.item(k);
                        NodeList positions = loc.getElementsByTagName("position");
                        for (int l = 0; l < positions.getLength(); l++) {
                            Element position = (Element) positions.item(l);
                            modifiedResidues.get(description).addPosition(
                                    new UniprotPosition(Integer.parseInt(position.getAttribute("position"))));
                        }

                    }
                }
            }

            uniprotEntry.getModifications().addAll(modifiedResidues.values());

            // Xrefs:
            NodeList dbReferences = entryElement.getElementsByTagName("dbReference");
            for (int j = 0; j < dbReferences.getLength(); j++) {
                Element dbReference = (Element) dbReferences.item(j);

                if (false == entryElement.equals(dbReference.getParentNode())) {
                    continue;
                }

                NodeList molecules = dbReference.getElementsByTagName("molecule");

                // ensembl
                if (dbReference.hasAttribute("type") && "Ensembl".equals(dbReference.getAttribute("type"))) {

                    // transcript ID
                    String id = dbReference.getAttribute("id");

                    for (int iMolecule = 0; iMolecule < molecules.getLength(); iMolecule++) {
                        Element molecule = (Element) molecules.item(iMolecule);
                        uniprotEntry.addXrefToVarSplice(id, molecule.getAttribute("id"));
                    }

                    uniprotEntry.addEnsemblGene(id);

                    NodeList properties = dbReference.getElementsByTagName("property");

                    for (int k = 0; k < properties.getLength(); k++) {
                        Element property = (Element) properties.item(k);

                        if (property.hasAttribute("type") && "gene ID".equals(property.getAttribute("type"))) {
                            uniprotEntry.addEnsemblGene(property.getAttribute("value"));
                        }
                    }
                }

                // refseq
                if (dbReference.hasAttribute("type") && "RefSeq".equals(dbReference.getAttribute("type"))) {
                    NodeList properties = dbReference.getElementsByTagName("property");
                    for (int k = 0; k < properties.getLength(); k++) {
                        Element property = (Element) properties.item(k);
                        if (property.hasAttribute("type")
                                && "nucleotide sequence ID".equals(property.getAttribute("type"))) {

                            String id = property.getAttribute("value");
                            if (molecules.getLength() > 0) {
                                for (int iMolecule = 0; iMolecule < molecules.getLength(); iMolecule++) {
                                    Element molecule = (Element) molecules.item(iMolecule);

                                    // If refseq, add also without the version                                       
                                    uniprotEntry.addXrefToVarSplice(id, molecule.getAttribute("id"));
                                    uniprotEntry.addXrefToVarSplice(id.split("\\.")[0],
                                            molecule.getAttribute("id"));

                                }
                            } else {
                                // If refseq, add also without the version                                       
                                uniprotEntry.addXrefToVarSplice(id, ac);
                                uniprotEntry.addXrefToVarSplice(id.split("\\.")[0], ac);
                            }

                            uniprotEntry.addRefseq(id);

                        }
                    }
                }

                /* PDB chains will be imported from the webservice */
                // PDB
                if (dbReference.hasAttribute("type") && "PDB".equals(dbReference.getAttribute("type"))) {
                    NodeList properties = dbReference.getElementsByTagName("property");
                    String method = null;
                    String chains = null;

                    for (int k = 0; k < properties.getLength(); k++) {
                        Element property = (Element) properties.item(k);
                        if (property.hasAttribute("type") && "method".equals(property.getAttribute("type"))) {
                            method = property.getAttribute("value");
                        } else if (property.hasAttribute("type")
                                && "chains".equals(property.getAttribute("type"))) {
                            chains = property.getAttribute("value");
                        }
                    }

                    if (method != null && "Model".equals(method)) {
                        continue;
                    }

                    if (chains == null) {
                        continue;
                    }

                    String pdb = dbReference.getAttribute("id");

                    uniprotEntry.addPDB(pdb, method);

                    for (String chainElement : chains.split(",")) {
                        try {
                            String chainNames = chainElement.split("=")[0];
                            int start = Integer.parseInt(chainElement.split("=")[1].trim().split("-")[0]);
                            int end = Integer
                                    .parseInt(chainElement.split("=")[1].trim().split("-")[1].replace(".", ""));
                            for (String chainName : chainNames.split("/")) {
                                uniprotEntry.addChain(pdb, new ChainMapping(pdb, chainName.trim(), start, end),
                                        method);
                            }
                        } catch (ArrayIndexOutOfBoundsException aiobe) {
                            // IGBLogger.getInstance().warning(
                            // "Cannot parse chain: " + chainElement
                            // + ", skip");
                        }
                    }
                }

            }

            // Sequence
            NodeList sequenceElements = entryElement.getElementsByTagName("sequence");

            for (int j = 0; j < sequenceElements.getLength(); j++) {
                Element sequenceElement = (Element) sequenceElements.item(j);

                if (false == sequenceElement.getParentNode().equals(entryElement)) {
                    continue;
                }
                String sequence = sequenceElement.getFirstChild().getNodeValue().replaceAll("\n", "");
                uniprotEntry.setSequence(sequence);
            }

            // Diseases
            NodeList diseases = entryElement.getElementsByTagName("disease");

            for (int j = 0; j < diseases.getLength(); j++) {
                Element disease = (Element) diseases.item(j);

                NodeList nameList = disease.getElementsByTagName("name");

                for (int k = 0; k < nameList.getLength(); k++) {
                    Element name = (Element) nameList.item(k);
                    uniprotEntry.addDisease(name.getFirstChild().getNodeValue());
                }
            }

            // Get fasta for all varsplice
            String fastaQuery = "http://www.uniprot.org/uniprot/" + uniprotEntry.getUniprotAc()
                    + ".fasta?include=yes";

            try {
                //HttpClient fastaClient = new DefaultHttpClient();

                client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
                HttpGet fastaRequest = new HttpGet(fastaQuery);

                // add request header
                request.addHeader("User-Agent", USER_AGENT);

                HttpResponse fastaResponse = client.execute(fastaRequest);

                if (fastaResponse.getEntity().getContentLength() == 0) {
                    continue;
                }

                InputStream is = fastaResponse.getEntity().getContent();

                try {
                    LinkedHashMap<String, ProteinSequence> fasta = FastaReaderHelper
                            .readFastaProteinSequence(is);

                    boolean mainSequence = true;

                    for (ProteinSequence seq : fasta.values()) {
                        //                            logger.info("Add sequence: " + seq.getAccession().getID() + " : " + seq.getSequenceAsString());
                        uniprotEntry.addSequence(seq.getAccession().getID(), seq.getSequenceAsString());
                        if (mainSequence) {
                            uniprotEntry.setMainIsoform(seq.getAccession().getID());
                            mainSequence = false;
                        }
                    }
                } catch (Exception e) {
                    logger.error("Cannot retrieve fasta for : " + uniprotEntry.getUniprotAc());
                }
            } catch (IOException | IllegalStateException ex) {
                logger.error(null, ex);
            }

            uniprotEntries.add(uniprotEntry);

        }

    } catch (SAXParseException se) {
        // Nothing was return
        // IGBLogger.getInstance()
        // .error("Uniprot returns empty result: " + url);
    } catch (IOException | ParserConfigurationException | IllegalStateException | SAXException | DOMException
            | NumberFormatException e) {
        if (waitAndRetryOnFailure && allowedUniprotFailures > 0) {
            try {
                allowedUniprotFailures--;
                Thread.sleep(5000);
                return getUniprotEntriesXML(location, false);
            } catch (InterruptedException e1) {
                logger.error("Fail to retrieve data from " + location);
                throw new BridgesRemoteAccessException("Fail to retrieve data from Uniprot " + location);
            }
        } else {
            logger.error("Problem with Uniprot: " + url);
            throw new BridgesRemoteAccessException("Fail to retrieve data from Uniprot " + location);
        }
    }

    for (MoleculeEntry entry : uniprotEntries) {
        addToCache(entry);
    }

    return uniprotEntries;
}

From source file:com.icesoft.faces.context.BridgeFacesContext.java

protected void applyBrowserFormChanges(Map parameters, Document document, Element form) {
    NodeList inputElements = form.getElementsByTagName("input");
    int inputElementsLength = inputElements.getLength();
    for (int i = 0; i < inputElementsLength; i++) {
        Element inputElement = (Element) inputElements.item(i);
        String id = inputElement.getAttribute("id");
        if (!"".equals(id)) {
            String name = null;//from  ww w .j  a va2 s  .co m
            if (parameters.containsKey(id)) {
                String value = ((String[]) parameters.get(id))[0];
                //empty string is implied (default) when 'value' attribute is missing
                if (!"".equals(value)) {
                    if (inputElement.hasAttribute("value")) {
                        inputElement.setAttribute("value", value);
                    } else if (inputElement.getAttribute("type").equals("checkbox")) {
                        inputElement.setAttribute("checked", "checked");
                    }
                } else {
                    inputElement.setAttribute("value", "");
                }
            } else if (!"".equals(name = inputElement.getAttribute("name")) && parameters.containsKey(name)) {
                String type = inputElement.getAttribute("type");
                if (type != null && type.equals("checkbox") || type.equals("radio")) {
                    String currValue = inputElement.getAttribute("value");
                    if (!"".equals(currValue)) {
                        boolean found = false;
                        // For multiple checkboxes, values can have length > 1,
                        // but for multiple radios, values would have at most length=1
                        String[] values = (String[]) parameters.get(name);
                        if (values != null) {
                            for (int v = 0; v < values.length; v++) {
                                if (currValue.equals(values[v])) {
                                    found = true;
                                    break;
                                }
                            }
                        }
                        if (found) {
                            // For some reason, our multiple checkbox 
                            // components use checked="true", while
                            // our single checkbox components use
                            // checked="checked". The latter complying
                            // with the HTML specification.
                            // Also, radios use checked="checked"
                            if (type.equals("checkbox")) {
                                inputElement.setAttribute("checked", "true");
                            } else if (type.equals("radio")) {
                                inputElement.setAttribute("checked", "checked");
                            }
                        } else {
                            inputElement.removeAttribute("checked");
                        }
                    }
                }
            } else {
                if (inputElement.getAttribute("type").equals("checkbox")) {
                    ////inputElement.setAttribute("checked", "");
                    inputElement.removeAttribute("checked");
                }
            }
        }
    }

    NodeList textareaElements = form.getElementsByTagName("textarea");
    int textareaElementsLength = textareaElements.getLength();
    for (int i = 0; i < textareaElementsLength; i++) {
        Element textareaElement = (Element) textareaElements.item(i);
        String id = textareaElement.getAttribute("id");
        if (!"".equals(id) && parameters.containsKey(id)) {
            String value = ((String[]) parameters.get(id))[0];
            Node firstChild = textareaElement.getFirstChild();
            if (null != firstChild) {
                //set value on the Text node
                firstChild.setNodeValue(value);
            } else {
                //DOM brought back from compression may have no
                //child for empty TextArea
                if (value != null && value.length() > 0) {
                    textareaElement.appendChild(document.createTextNode(value));
                }
            }
        }
    }

    NodeList selectElements = form.getElementsByTagName("select");
    int selectElementsLength = selectElements.getLength();
    for (int i = 0; i < selectElementsLength; i++) {
        Element selectElement = (Element) selectElements.item(i);
        String id = selectElement.getAttribute("id");
        if (!"".equals(id) && parameters.containsKey(id)) {
            List values = Arrays.asList((String[]) parameters.get(id));

            NodeList optionElements = selectElement.getElementsByTagName("option");
            int optionElementsLength = optionElements.getLength();
            for (int j = 0; j < optionElementsLength; j++) {
                Element optionElement = (Element) optionElements.item(j);
                if (values.contains(optionElement.getAttribute("value"))) {
                    optionElement.setAttribute("selected", "selected");
                } else {
                    optionElement.removeAttribute("selected");
                }
            }
        }
    }
}

From source file:it.ciroppina.idol.generic.tunnel.IdolOEMTunnel.java

/**
 * Method that returns a List<Map> where every map contains hit's fields 
 *  and the autn:content text, BUT it do not contains <DOCUMENT> structure !
 *  <br/>//  w  ww.  j av  a2s  .com
 *  Notice that: this method M^UST be invoked only for a print=indexText query !
 *  
 * @return ArrayList<Hit> list of Hit, each containing a Map (of dreFields)
 * 
 */
@WebMethod(operationName = "getQueryHitsNoDocumentMap")
public ArrayList<Hit> getQueryHitsNoDocumentMap(String xml) {
    ArrayList<Hit> result = new ArrayList<Hit>();
    Document document = getDocumentFrom(xml);

    NodeList temp = null;
    temp = document.getElementsByTagName("response");
    String response = (temp.getLength() > 0)
            ? document.getElementsByTagName("response").item(0).getTextContent()
            : "FAILURE";
    temp = document.getElementsByTagName("autn:numhits");
    String numHits = (temp.getLength() > 0)
            ? document.getElementsByTagName("autn:numhits").item(0).getTextContent()
            : "0";
    temp = document.getElementsByTagName("autn:totalhits");
    String totalHits = (temp.getLength() > 0)
            ? document.getElementsByTagName("autn:totalhits").item(0).getTextContent()
            : "0";

    NodeList hits = document.getElementsByTagName("autn:hit");

    for (int i = 0; i < hits.getLength(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        Node nodo = hits.item(i);
        NodeList hitChilds = nodo.getChildNodes();

        for (int j = 0; j < hitChilds.getLength(); j++) {
            Node n = hitChilds.item(j);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                Element e2 = (Element) n;
                if (!e2.getNodeName().equals("autn:content")) {
                    String value = "";
                    if (map.containsKey(e2.getNodeName())) {
                        value = map.get(e2.getNodeName()) + "," + e2.getTextContent();
                        map.put(e2.getNodeName(), value);
                    } else {
                        map.put(e2.getNodeName(), e2.getTextContent());
                    }

                } else {
                    if (e2.getNodeType() == Node.ELEMENT_NODE) {
                        String nodeValue = e2.getFirstChild().getTextContent();
                        //Element el = (Element) content;
                        String value = "";
                        if (map.containsKey(e2.getNodeName())) {
                            value = map.get(e2.getNodeName()) + "," + nodeValue;
                            map.put(e2.getNodeName(), value);
                        } else {
                            map.put(e2.getNodeName(), nodeValue);
                        }
                    }
                }
            }
        }
        Hit hit = new Hit(map);
        hit.getDreFields().put("response", response);
        hit.getDreFields().put("numhits", numHits);
        hit.getDreFields().put("totalhits", totalHits);

        result.add(hit);
    }
    return result;
}

From source file:com.hp.hpl.inkml.InkMLDOMParser.java

/**
 * Method to bind AnnotationXML element//from w w w .j  ava2s.  c o m
 * 
 * @param element the AnnotationXML element
 * @return AnnotationXML data object
 * @throws InkMLException
 */
protected AnnotationXML getAnnotationXML(final Element element) throws InkMLException {
    final AnnotationXML aXml = new AnnotationXML();
    final NamedNodeMap attributesMap = element.getAttributes();
    final int length = attributesMap.getLength();
    for (int index = 0; index < length; index++) {
        final Attr attribute = (Attr) attributesMap.item(index);
        final String attributeName = attribute.getName();
        if ("type".equals(attributeName)) {
            aXml.setType(attribute.getValue());
        } else if ("encoding".equals(attributeName)) {
            aXml.setEncoding(attribute.getValue());
        } else {
            aXml.addToOtherAttributesMap(attributeName, attribute.getValue());
        }
    }
    InkMLDOMParser.LOG.finest("annotationXML received: " + element.toString());
    final NodeList list = element.getChildNodes();
    final int nChildren = list.getLength();
    if (nChildren > 0) {
        for (int i = 0; i < nChildren; i++) {
            final Node node = list.item(i);
            if (!(node instanceof Element)) {
                continue;
            }
            final Element childElement = (Element) node;
            // get the tagName to use as Key in the valueMap
            final String tagName = childElement.getLocalName();
            // String key = this.parentXPath+"/"+tagName;
            final String value = childElement.getFirstChild().getNodeValue();
            // propertyElementsMap.put(key, childElement);
            // propertyElementsMap.put(key, value);
            aXml.addToPropertyElementsMap(tagName, value);
            InkMLDOMParser.LOG
                    .finer("The property with name = " + tagName + " is added to the propertyElementsMap.");
        }
    }
    return aXml;
}

From source file:javax.microedition.ims.core.xdm.XDMServiceImpl.java

private URIListData handleListNode(Node listNode) {

    URIListDataBean retValue;/*from  w ww. j  a v  a 2s . com*/

    if (listNode != null) {

        if (!LIST_NODE_NAME.equalsIgnoreCase(listNode.getLocalName())) {
            throw new IllegalArgumentException("Must be 'list' listNode");
        }

        if (listNode.getNodeType() == Node.ELEMENT_NODE) {
            Element listElement = (Element) listNode;

            NodeList displayNameNode = listElement.getElementsByTagNameNS("*", "display-name");
            String displayName = /* "" */null;

            for (int entrIndex = 0; entrIndex < displayNameNode.getLength(); entrIndex++) {
                if (displayNameNode.item(entrIndex).getNodeType() == Node.ELEMENT_NODE) {

                    Element entryElement = (Element) displayNameNode.item(entrIndex);
                    if (LIST_NODE_NAME.equalsIgnoreCase(entryElement.getParentNode().getLocalName())) {

                        final Node firstChildNode = entryElement.getFirstChild();
                        if (firstChildNode != null) {
                            displayName = firstChildNode.getNodeValue();
                        }
                        break;
                    }
                }
            }

            String name = listElement.getAttribute("name");

            List<ListEntryData> listEntryData = new ArrayList<ListEntryData>();

            // extracts single user URI
            {
                NodeList entryNode = listElement.getElementsByTagNameNS("*", "entry");
                for (int entrIndex = 0; entrIndex < entryNode.getLength(); entrIndex++) {
                    if (entryNode.item(entrIndex).getNodeType() == Node.ELEMENT_NODE) {
                        Element entryElement = (Element) entryNode.item(entrIndex);
                        if (LIST_NODE_NAME.equalsIgnoreCase(entryElement.getParentNode().getLocalName())) {
                            String entryURI = entryElement.getAttribute("uri");
                            NodeList entryDisplayNameNode = entryElement.getElementsByTagNameNS("*",
                                    "display-name");
                            String entryDisplayName = null/* "" */;
                            if (entryDisplayNameNode.getLength() > 0) {
                                Node node = entryDisplayNameNode.item(0);
                                final Node firstChildNode = node.getFirstChild();
                                if (firstChildNode != null) {
                                    entryDisplayName = firstChildNode.getNodeValue();
                                }
                            }

                            listEntryData.add(
                                    new ListEntryDataBean(ListEntryData.URI_ENTRY, entryDisplayName, entryURI));
                        }
                    }
                }
            }

            // extracts references to an already existing URI list
            {
                NodeList externalsNode = listElement.getElementsByTagNameNS("*", "external");
                for (int entrIndex = 0; entrIndex < externalsNode.getLength(); entrIndex++) {
                    if (externalsNode.item(entrIndex).getNodeType() == Node.ELEMENT_NODE) {
                        Element externalElement = (Element) externalsNode.item(entrIndex);
                        if (LIST_NODE_NAME.equalsIgnoreCase(externalElement.getParentNode().getLocalName())) {
                            String anchorURI = externalElement.getAttribute("anchor");
                            NodeList anchorDisplayNameNode = externalElement.getElementsByTagNameNS("*",
                                    "display-name");
                            String anchorDisplayName = null/* "" */;
                            if (anchorDisplayNameNode.getLength() > 0) {
                                Node node = anchorDisplayNameNode.item(0);
                                final Node firstChildNode = node.getFirstChild();
                                if (firstChildNode != null) {
                                    anchorDisplayName = firstChildNode.getNodeValue();
                                }
                            }

                            listEntryData.add(new ListEntryDataBean(ListEntryData.URI_LIST_ENTRY,
                                    anchorDisplayName, anchorURI));
                        }
                    }
                }
            }

            retValue = new URIListDataBean(displayName, name, listEntryData);

        } else {
            throw new IllegalArgumentException(
                    "only " + Node.ELEMENT_NODE + " is allowed as parameter. Passed " + listNode.getNodeType());
        }
    } else {
        throw new NullPointerException("listNode is null. Null is not allowed here.");
    }

    return retValue;
}

From source file:com.draagon.meta.loader.xml.XMLFileMetaDataLoader.java

/** 
 * Parse the MetaAttribute Value //  www.j  ava 2 s .c  om
 */
protected void parseMetaAttributeValue(MetaAttribute attr, Element el) {

    ///////////////////////////////////////////////////
    // Get the Node value

    // Get the first node
    Node nv = el.getFirstChild();

    // Loop through and ignore the comments
    while (nv != null && nv.getNodeType() == Node.COMMENT_NODE) {
        nv.getNextSibling();
    }

    // If a valid node exists, then get the data
    if (nv != null) {
        switch (nv.getNodeType()) {
        // If CDATA just set the whole thing
        case Node.CDATA_SECTION_NODE:
            attr.setValueAsString(((CharacterData) nv).getData());
            break;

        // If an Element just pass it in for parsing
        case Node.ELEMENT_NODE:
            attr.setValue(nv);
            break;

        // If just text, then pass it in
        case Node.TEXT_NODE:
            attr.setValueAsString(nv.getNodeValue());
            break;

        default:
            log.warn("Unsupported Node Type for node [" + nv + "]");
        }
    }
}

From source file:com.amalto.workbench.utils.XSDAnnotationsStructure.java

private LinkedHashMap<String, String> getAppInfos(String regex) {
    LinkedHashMap<String, String> appInfos = new LinkedHashMap<String, String>();
    ArrayList<Element> list = new ArrayList<Element>();
    // list.addAll(annotation.getUserInformation());
    list.addAll(annotation.getApplicationInformation());
    int i = 0;/*from w ww .  ja  va2 s . co  m*/
    for (Iterator<Element> iter = list.iterator(); iter.hasNext();) {
        Element ann = iter.next();
        String name = ann.getLocalName();
        if ("appinfo".equals(name.toLowerCase())) {//$NON-NLS-1$
            name = ann.getAttribute("source");//$NON-NLS-1$
            if (name.equals(regex)) {
                appInfos.put(name + "_" + i, ann.getFirstChild().getNodeValue());//$NON-NLS-1$
                i++;
            } else if (name.matches(regex)) {
                appInfos.put(name, ann.getFirstChild().getNodeValue());
            }
        }
    }
    return appInfos;
}

From source file:eionet.gdem.conversion.odf.ODFSpreadsheetAnalyzer.java

/**
 * Get the content from p:text node or officde:value attribute - cell value
 *
 * @param cellElement/*from w  w w.ja  va  2 s  . c  om*/
 *            the first element of <code>&lt;table:table-cell&gt;</code> element.
 *
 * @return content inside text:p tag
 */
protected String processCell(Element cellElement) {
    String cellValue = null;
    if (cellElement.hasAttribute(officeNamespace + "value-type")) {
        String valueType = cellElement.getAttribute(officeNamespace + "value-type");
        if ("date".equals(valueType)) {
            if (cellElement.hasAttribute(officeNamespace + "date-value")) {
                cellValue = cellElement.getAttribute(officeNamespace + "date-value");
            }
        } else if ("time".equals(valueType)) {
            if (cellElement.hasAttribute(officeNamespace + "time-value")) {
                cellValue = cellElement.getAttribute(officeNamespace + "time-value");
            }
        } else {
            if (cellElement.hasAttribute(officeNamespace + "value")) {
                cellValue = cellElement.getAttribute(officeNamespace + "value");
            }
        }
    }
    // get value from p:text
    if (Utils.isNullStr(cellValue) && cellElement.hasChildNodes()) {
        Element ptext = (Element) cellElement.getFirstChild();
        if (ptext != null && ptext.hasChildNodes()) {
            cellValue = ptext.getFirstChild().getNodeValue();
        }
    }
    return cellValue;
}