Example usage for org.w3c.dom Document hasChildNodes

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

Introduction

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

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:org.etudes.ambrosia.impl.UiServiceImpl.java

/**
 * {@inheritDoc}/*from   w w  w.  jav  a 2  s.  c o m*/
 */
public Interface newInterface(InputStream in) {
    UiInterface iface = null;
    Document doc = Xml.readDocumentFromStream(in);
    if ((doc == null) || (!doc.hasChildNodes()))
        return iface;

    // allowing for comments, use the first element node that is our interface
    NodeList nodes = doc.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() != Node.ELEMENT_NODE)
            continue;
        if (!(((Element) node).getTagName().equals("interface")))
            continue;

        // build the interface from this element
        iface = new UiInterface(this, (Element) node);
        break;
    }

    // else we have an invalid
    if (iface == null) {
        M_log.warn("newInterface: element \"interface\" not found in stream xml");
        iface = new UiInterface();
    }

    return iface;
}

From source file:org.etudes.mneme.impl.ImportQti2ServiceImpl.java

/**
 * {@inheritDoc}//from  ww  w.j a v a2 s.c  o  m
 */
public void importPool(Document doc, String context, String unzipBackUpLocation)
        throws AssessmentPermissionException {
    if ((doc == null) || (!doc.hasChildNodes()))
        return;

    // get a name for the pool
    Average pointsAverage = new Average();
    HashMap<String, Question> allQuestions = new HashMap<String, Question>();
    HashMap<String, String> allQuestionPoints = new HashMap<String, String>();
    HashMap<String, Pool> allPools = new HashMap<String, Pool>();

    // 1. Create one defaultPool for all questions
    Pool pool = this.poolService.newPool(context);
    pool.setTitle(findPoolTitle(context, "", doc));

    String poolDescription = findPoolDescription(doc);
    pool.setDescription(poolDescription);
    allPools.put("defaultPool", pool);

    // 2. Read questions of type item from manifest file
    try {
        // if etudes export package has pool resources
        XPath poolPath = new DOMXPath("//resources/resource[starts-with(@identifier,'POOL')]");

        List<Element> poolItems = poolPath.selectNodes(doc);
        for (Element poolItem : poolItems) {
            String pId = poolItem.getAttribute("identifier");
            pId = pId.replace("POOL", "");

            if (!allPools.containsKey(pId)) {
                Pool p = this.poolService.newPool(context);
                p.setTitle(findPoolTitle(context, poolItem.getAttribute("title"), doc));
                allPools.put(pId, p);
            }
        }

        XPath itemPath = new DOMXPath("//*[contains(local-name(),'resource')]");
        List<Element> items = itemPath.selectNodes(doc);

        for (Element item : items) {
            String type = item.getAttribute("type");
            if (type == null || !type.startsWith("imsqti_item_"))
                continue;

            // read href value
            String fileLocation = item.getAttribute("href");
            if ("".equals(fileLocation))
                continue;

            // read Xml file and create question
            Question question = null;
            try {
                String baseName = "";
                fileLocation = fileLocation.replace("\\", "/");
                if (fileLocation.lastIndexOf("/") != -1)
                    baseName = "/" + fileLocation.substring(0, fileLocation.lastIndexOf("/"));

                question = processQuestionItemFile(allPools, allQuestions, context, doc, item,
                        allQuestionPoints, pointsAverage, unzipBackUpLocation, fileLocation, baseName);
            } catch (Exception e) {
                M_log.debug(e.getMessage());
                continue;
            }
        }

        // 3. save pool
        // pool.setPointsEdit(pointsAverage.getAverage());
        Iterator<String> poolIterator = allPools.keySet().iterator();
        while (poolIterator.hasNext()) {
            String poolId = poolIterator.next();
            Pool p = allPools.get(poolId);
            if (p.getNumQuestions().intValue() == 0)
                continue;
            this.poolService.savePool(p);
        }

        // 4. then later read assessments and integrate with gradebook and save
        String rights = findRightsInformation(doc);
        int testCount = 0;
        for (Element testItem : items) {
            String type = testItem.getAttribute("type");
            if (type == null || !type.startsWith("imsqti_test_"))
                continue;

            // read href value
            String fileLocation = testItem.getAttribute("href");
            if ("".equals(fileLocation))
                continue;

            String baseName = "";
            fileLocation = fileLocation.replace("\\", "/");
            if (fileLocation.lastIndexOf("/") != -1)
                baseName = "/" + fileLocation.substring(0, fileLocation.lastIndexOf("/"));

            processAssessmentFiles(context, testItem, unzipBackUpLocation, fileLocation, baseName, rights,
                    allQuestions, allQuestionPoints, allPools);
            testCount++;
        }

        // create one default test for the pool just created if manifest has no resource of imsqi_test type.
        if (testCount == 0)
            createDefaultAssessment(context, allPools, allQuestions, allQuestionPoints);

    } catch (JaxenException e) {
        M_log.warn(e.toString());
    } catch (Exception e) {
        M_log.warn(e.toString());
    }
}

From source file:org.etudes.mneme.impl.ImportQtiServiceImpl.java

/**
 * {@inheritDoc}//from ww w. j  ava  2  s .  c o m
 */
public boolean importPool(Document doc, String context, String unzipBackUpLocation)
        throws AssessmentPermissionException {
    boolean qti1File = false;
    //read exam file from the zip file 
    if ((doc == null) || (!doc.hasChildNodes()))
        return qti1File;
    try {
        XPath itemPath = new DOMXPath("//*[contains(local-name(),'resource')]");
        List<Element> items = itemPath.selectNodes(doc);

        for (Element item : items) {
            String type = item.getAttribute("type");

            if (type == null || type.length() == 0 || (type.indexOf("qti") > -1 && type.indexOf("v1") == -1))
                continue;

            qti1File = true;

            // read href value
            String fileLocation = item.getAttribute("href");
            if ("".equals(fileLocation))
                continue;

            // read Xml file and create question
            Document fileDoc = Xml.readDocument(unzipBackUpLocation + File.separator + fileLocation);
            importPool(fileDoc, context);
        }
    } catch (Exception ex) {
        M_log.warn(ex.toString());
    }
    return qti1File;
}

From source file:org.etudes.mneme.impl.ImportQtiServiceImpl.java

/**
 * {@inheritDoc}/*from w ww .  jav a 2s .co  m*/
 */
public void importPool(Document doc, String context) throws AssessmentPermissionException {
    if ((doc == null) || (!doc.hasChildNodes()))
        return;

    // get a name for the pool, with the date
    String poolId = "pool";
    try {
        XPath assessmentTitlePath = new DOMXPath("/questestinterop/assessment/@title");
        String title = StringUtil.trimToNull(assessmentTitlePath.stringValueOf(doc));
        if (title == null) {
            // try for a single /item
            XPath itemTitlePath = new DOMXPath("/item/@title");
            title = StringUtil.trimToNull(itemTitlePath.stringValueOf(doc));
        }

        if (title != null) {
            poolId = title;
        }
    } catch (JaxenException e) {
        M_log.warn(e.toString());
    }

    // add a date stamp
    poolId = addDate("import-text", poolId, new Date());

    // create the pool
    Pool pool = this.poolService.newPool(context);
    pool.setTitle(poolId);
    // pool.setDescription(info.description);

    // average the question points for the pool's point value
    Average pointsAverage = new Average();

    // process questions
    try {
        XPath itemPath = new DOMXPath("//item");
        List items = itemPath.selectNodes(doc);

        for (Object oItem : items) {
            Element item = (Element) oItem;

            if (processSamigoTrueFalse(item, pool, pointsAverage))
                continue;
            if (processSamigoMultipleChoice(item, pool, pointsAverage))
                continue;
            if (processSamigoSurvey(item, pool))
                continue;
            if (processSamigoFillIn(item, pool, pointsAverage))
                continue;

            // process Respondous 3.5 type of format
            if (processRespondousTrueFalse(item, pool, pointsAverage))
                continue;
            if (processRespondousMultipleChoice(item, pool, pointsAverage))
                continue;
            if (processRespondousEssay(item, pool))
                continue;
            if (processRespondousFillIn(item, pool, pointsAverage))
                continue;
            if (processRespondousMatching(item, pool, pointsAverage))
                continue;

            M_log.warn("item recognized: " + item.getAttribute("ident"));
        }
    } catch (JaxenException e) {
        M_log.warn(e.toString());
    }

    // changed to set the pool point value as default 1.0 
    //pool.setPointsEdit(Float.valueOf(pointsAverage.getAverage()));
    pool.setPointsEdit(Float.valueOf("1.0"));

    // save
    this.poolService.savePool(pool);
}

From source file:org.parelon.pskc.XmlManager.java

public void convertXml(String fileIn, String fileOut)
        throws FileNotFoundException, SAXException, IOException, InvalidKeyException, Base64DecodingException,
        NoSuchAlgorithmException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
        BadPaddingException, NoSuchPaddingException, UnsupportedEncodingException, ParserConfigurationException,
        DecoderException, Exception {
    ArrayList<OtpSeed> seeds = new ArrayList<OtpSeed>();

    /**//w  ww  .ja  v a 2 s .  co m
     * Parserizzazione XML
     */
    FileInputStream fileToConvert = new FileInputStream(fileIn);
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document parsedXml = builder.parse(fileToConvert);
    fileToConvert.close();
    if (parsedXml.hasChildNodes()) {
        int validSerials = 0;
        NodeList keyPackages = parsedXml.getElementsByTagName("KeyPackage");
        for (int i = 0; i < keyPackages.getLength(); i++) {
            Node keyPackageNode = keyPackages.item(i);
            /**
             * Parse PSKC node structure
             */
            String serialNo = ((Element) keyPackageNode).getElementsByTagName("SerialNo").item(0)
                    .getTextContent();

            if (validateSerial(serialNo)) {
                validSerials++;

                OtpSeed validSeed = new OtpSeed();
                validSeed.setSerialNo(serialNo);
                validSeed.setCryptoId(String.format("KR-%06d", validSerials));
                validSeed.setIssuer(issuer);
                validSeed.setKeyId(String.format("%08d", validSerials));
                validSeed.setManufacturer(manufactuer);

                NodeList tempNode = ((Element) keyPackageNode).getElementsByTagName("xenc:CipherValue");
                if (tempNode != null && tempNode.getLength() != 0) {
                    validSeed.setCipherValue(((Element) tempNode.item(0)).getTextContent());
                }
                seeds.add(validSeed);
            }
        }
    }

    /**
     * Creazione del nuovo XML
     */
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    // root elements
    Document doc = docBuilder.newDocument();
    doc.setXmlVersion("1.0");

    Element keyContainer = doc.createElement("KeyContainer");
    doc.appendChild(keyContainer);
    keyContainer.setAttribute("xmlns", "urn:ietf:params:xml:ns:keyprov:pskc");
    keyContainer.setAttribute("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
    keyContainer.setAttribute("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");
    keyContainer.setAttribute("Version", "1.0");
    keyContainer.setAttribute("ID", "KC0001");

    /**
     * Key Name
     */
    Element encryptionKey = doc.createElement("EncryptionKey");
    keyContainer.appendChild(encryptionKey);
    Element ds_keyName = doc.createElement("ds:KeyName");
    encryptionKey.appendChild(ds_keyName);
    ds_keyName.setTextContent(this.preSharedKeyName);

    /**
     * MAC Method
     */
    Element macMethod = doc.createElement("MACMethod");
    keyContainer.appendChild(macMethod);
    macMethod.setAttribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#hmac-sha1");
    /**
     * Mac Key
     */
    Element macKey = doc.createElement("MACKey");
    macMethod.appendChild(macKey);
    /**
     * EncryptionMethod
     */
    Element encryptionMethod = doc.createElement("xenc:EncryptionMethod");
    macKey.appendChild(encryptionMethod);
    encryptionMethod.setAttribute("Algorithm", "http://www.w3.org/2001/04/xmlenc#aes128-cbc");
    /**
     * xenc:CipherData
     */
    Element xenc_CipherData = doc.createElement("xenc:CipherData");
    macKey.appendChild(xenc_CipherData);
    /**
     * xenc:CipherValue
     */
    Element xenc_CipherValue = doc.createElement("xenc:CipherValue");
    xenc_CipherData.appendChild(xenc_CipherValue);

    /**
     * Passo 1: Criptare la MAC Key
     */
    String macSignature = Base64.encode(crypto.getAesCipheredMacKey());
    xenc_CipherValue.setTextContent(macSignature);

    for (OtpSeed seed : seeds) {
        /**
         * Passo 2: Convertire il dato criptato
         */
        byte[] reCipheredSecretBytes = crypto.convertRsaToAes(seed.getCipherValue());
        seed.setCipherValue(Base64.encode(reCipheredSecretBytes));
        /**
         * Passo 3: Firmare il dato criptato
         */
        byte[] secretSignatureBytes = crypto.signCipheredSecret(reCipheredSecretBytes);
        seed.setValueMac(Base64.encode(secretSignatureBytes));

        /**
         * KeyPackage
         */
        Element keyPackageElement = doc.createElement("KeyPackage");
        keyContainer.appendChild(keyPackageElement);
        /**
         * DeviceInfo
         */
        Element deviceInfoElement = doc.createElement("DeviceInfo");
        keyPackageElement.appendChild(deviceInfoElement);
        /**
         * Manufactuer
         */
        Element manufactuerElement = doc.createElement("Manufactuer");
        manufactuerElement.setTextContent(seed.getManufacturer());
        deviceInfoElement.appendChild(manufactuerElement);
        /**
         * SerialNo
         */
        Element serialNoElement = doc.createElement("SerialNo");
        serialNoElement.setTextContent(seed.getSerialNo());
        deviceInfoElement.appendChild(serialNoElement);
        /**
         * CryptoModuleInfo
         */
        Element cryptoModuleInfoElement = doc.createElement("CryptoModuleInfo");
        keyPackageElement.appendChild(cryptoModuleInfoElement);
        /**
         * ID
         */
        Element idElement = doc.createElement("ID");
        idElement.setTextContent(seed.getCryptoId());
        cryptoModuleInfoElement.appendChild(idElement);
        /**
         * Key
         */
        Element keyElement = doc.createElement("Key");
        keyPackageElement.appendChild(keyElement);
        keyElement.setAttribute("Id", seed.getKeyId());
        if (seed.getType().equals("TOTP")) {
            keyElement.setAttribute("Algorithm", "urn:ietf:params:xml:ns:keyprov:pskc:totp");
        } else if (seed.getType().equals("HOTP")) {
            keyElement.setAttribute("Algorithm", "urn:ietf:params:xml:ns:keyprov:pskc:hotp");
        } else {
            throw new Exception("OTP type not supported");
        }

        /**
         * Issuer
         */
        Element issuerElement = doc.createElement("Issuer");
        issuerElement.setTextContent(seed.getIssuer());
        keyElement.appendChild(issuerElement);
        /**
         * AlgorithmParameters
         */
        Element algorithmParametersElement = doc.createElement("AlgorithmParameters");
        keyElement.appendChild(algorithmParametersElement);
        /**
         * ResponseFormat
         */
        Element responseFormatElement = doc.createElement("ResponseFormat");
        algorithmParametersElement.appendChild(responseFormatElement);
        responseFormatElement.setAttribute("Length", seed.getLength());
        responseFormatElement.setAttribute("Encoding", seed.getEncoding());
        /**
         * Data
         */
        Element dataElement = doc.createElement("Data");
        keyElement.appendChild(dataElement);
        /**
         * Secret
         */
        Element secretElement = doc.createElement("Secret");
        dataElement.appendChild(secretElement);
        /**
         * EncryptedValue
         */
        Element encryptedValueElement = doc.createElement("EncryptedValue");
        secretElement.appendChild(encryptedValueElement);
        /**
         * xenc:EncryptionMethod
         */
        Element encryptionMethodElement = doc.createElement("xenc:EncryptionMethod");
        encryptedValueElement.appendChild(encryptionMethodElement);
        encryptionMethodElement.setAttribute("Algorithm", "http://www.w3.org/2001/04/xmlenc#aes128-cbc");
        /**
         * xenc:CipherData
         */
        Element cipherDataElement = doc.createElement("xenc:CipherData");
        encryptedValueElement.appendChild(cipherDataElement);
        /**
         * xenc:CipherValue
         */
        Element cipherValueElement = doc.createElement("xenc:CipherValue");
        cipherValueElement.setTextContent(seed.getCipherValue());
        cipherDataElement.appendChild(cipherValueElement);
        /**
         * ValueMAC
         */
        Element valueMACElement = doc.createElement("ValueMAC");
        valueMACElement.setTextContent(seed.getValueMac());
        secretElement.appendChild(valueMACElement);
        /**
         * Counter
         */
        Element counterElement = doc.createElement("Counter");
        dataElement.appendChild(counterElement);
        /**
         * PlainValue
         */
        Element counterPlainValueElement = doc.createElement("PlainValue");
        counterPlainValueElement.setTextContent(seed.getCounter());
        counterElement.appendChild(counterPlainValueElement);
        /**
         * TimeInterval
         */
        Element timeIntervalElement = doc.createElement("TimeInterval");
        dataElement.appendChild(timeIntervalElement);
        /**
         * PlainValue
         */
        Element timeIntervalPlainValueElement = doc.createElement("PlainValue");
        timeIntervalPlainValueElement.setTextContent(seed.getTimeInterval());
        timeIntervalElement.appendChild(timeIntervalPlainValueElement);
        /**
         * Time
         */
        Element timeElement = doc.createElement("Time");
        dataElement.appendChild(timeElement);
        /**
         * PlainValue
         */
        Element timePlainValueElement = doc.createElement("PlainValue");
        timePlainValueElement.setTextContent(seed.getTime());
        timeElement.appendChild(timePlainValueElement);
    }

    doc.normalizeDocument();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    DOMSource source = new DOMSource(doc);

    StreamResult result = new StreamResult(new File(fileOut));
    transformer.transform(source, result);
}

From source file:org.pentaho.agilebi.modeler.models.annotations.ModelAnnotationGroup.java

private Map<ApplyStatus, List<ModelAnnotation>> applyAnnotations(final Document mondrianSchema,
        final ModelAnnotationGroup toApply) throws ModelerException {
    AnnotateStrategy strategy = new AnnotateStrategy() {

        @Override//from  w w  w.j a  va  2  s.  c  om
        public boolean apply(final ModelAnnotation modelAnnotation) throws ModelerException {
            return modelAnnotation.apply(mondrianSchema);
        }

        @Override
        public Map<ApplyStatus, List<ModelAnnotation>> applyAll(final ModelAnnotationGroup modelAnnotations)
                throws ModelerException {
            return applyAnnotations(mondrianSchema, modelAnnotations);
        }

        @Override
        public boolean isEmptyModel() {
            return !mondrianSchema.hasChildNodes();
        }
    };
    return applyAnnotations(strategy, toApply);
}