Java Code Examples for org.w3c.dom.Document.getDocumentElement()

The following are Jave code examples for showing how to use getDocumentElement() of the org.w3c.dom.Document class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: cas-server-4.2.1   File: AbstractMetadataResolverAdapter.java   View Source Code Vote up 6 votes
/**
 * Build single metadata resolver.
 *
 * @param metadataFilterChain the metadata filters chained together
 * @param resource the resource
 * @param document the xml document to parse
 * @return list of resolved metadata from resources.
 * @throws IOException the iO exception
 */
private List<MetadataResolver> buildSingleMetadataResolver(final MetadataFilter metadataFilterChain,
                                         final Resource resource, final Document document) throws IOException {
    final List<MetadataResolver> resolvers = new ArrayList<>();
    final Element metadataRoot = document.getDocumentElement();
    final DOMMetadataResolver metadataProvider = new DOMMetadataResolver(metadataRoot);

    metadataProvider.setParserPool(this.configBean.getParserPool());
    metadataProvider.setFailFastInitialization(true);
    metadataProvider.setRequireValidMetadata(this.requireValidMetadata);
    metadataProvider.setId(metadataProvider.getClass().getCanonicalName());
    if (metadataFilterChain != null) {
        metadataProvider.setMetadataFilter(metadataFilterChain);
    }
    logger.debug("Initializing metadata resolver for [{}]", resource.getURL());

    try {
        metadataProvider.initialize();
    } catch (final ComponentInitializationException ex) {
        logger.warn("Could not initialize metadata resolver. Resource will be ignored", ex);
    }
    resolvers.add(metadataProvider);
    return resolvers;
}
 
Example 2
Project: alvisnlp   File: AbstractAlvisNLP.java   View Source Code Vote up 5 votes
@Override
public void setValue(Logger logger, PlanLoader<A> planLoader, Module<A> module) throws ParameterException, ConverterException, UnsupportedServiceException, SAXException, IOException, PlanException, URISyntaxException {
	logger.config("setting XML value to module " + module.getPath() + ": '" + xmlValue + "'");
  		InputSource is = new InputSource(new StringReader(xmlValue));
  		Document doc = XMLUtils.docBuilder.parse(is);
  		Element elt = doc.getDocumentElement();
  		planLoader.setParam(elt, module);
}
 
Example 3
Project: openjdk-jdk10   File: Bug6690015.java   View Source Code Vote up 5 votes
@Test
public void test() {
    try {
        FileInputStream fis = new FileInputStream(getClass().getResource("bug6690015.xml").getFile());

        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(fis));
        Element root = doc.getDocumentElement();
        NodeList textnodes = root.getElementsByTagName("text");
        int len = textnodes.getLength();
        int index = 0;
        int attindex = 0;
        int attrlen = 0;
        NamedNodeMap attrs = null;

        while (index < len) {
            Element te = (Element) textnodes.item(index);
            attrs = te.getAttributes();
            attrlen = attrs.getLength();
            attindex = 0;
            Node node = null;

            while (attindex < attrlen) {
                node = attrs.item(attindex);
                System.out.println("attr: " + node.getNodeName() + " is shown holding value: " + node.getNodeValue());
                attindex++;
            }
            index++;
            System.out.println("-------------");
        }
        fis.close();
    } catch (Exception e) {
        Assert.fail("Exception: " + e.getMessage());
    }
}
 
Example 4
Project: alvisnlp   File: ConverterFactoryModel.java   View Source Code Vote up 5 votes
@Override
protected void fillDOM(ModelContext ctx, Document doc) {
	org.w3c.dom.Element root = doc.getDocumentElement();
	for (String base : resourceBases) {
		org.w3c.dom.Element baseElt = doc.createElement("resource-base");
		baseElt.setTextContent(base);
		root.appendChild(baseElt);
	}
	for (ConverterModel converter : converters) {
		root.appendChild(converter.getDOM(doc));
	}
}
 
Example 5
Project: gemini.blueprint   File: OsgiDefaultsDefinition.java   View Source Code Vote up 5 votes
public OsgiDefaultsDefinition(Document document, ParserContext parserContext) {
	Assert.notNull(document);
	Element root = document.getDocumentElement();

	ReferenceParsingUtil.checkAvailabilityAndCardinalityDuplication(root, DEFAULT_AVAILABILITY,
			DEFAULT_CARDINALITY, parserContext);

	parseDefaults(root, EGB_NS);
	parseDefaults(root, SDM_NS);
}
 
Example 6
Project: alvisnlp   File: DocumentableResource.java   View Source Code Vote up 5 votes
private void addStylesheet(Document doc) {
	for (Node node : XMLUtils.childrenNodes(doc)) {
		if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
			ProcessingInstruction pi = (ProcessingInstruction) node;
			if (pi.getTarget().equals("xml-stylesheet")) {
				return;
			}
		}
	}
	ProcessingInstruction stylesheetPI = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\""+getURLBase()+"/static/style/alvisnlp-doc2xhtml.xslt\"");
	Element root = doc.getDocumentElement();
	doc.insertBefore(stylesheetPI, root);
}
 
Example 7
Project: Cognizant-Intelligent-Test-Scripter   File: AndroidTree.java   View Source Code Vote up 5 votes
@Override
public void loadTree(String xml) {
    Document doc = XMLOperation.initTreeOp(xml);
    Element rootElement = doc.getDocumentElement();
    rotation = getAttribute(rootElement, "rotation");
    AndroidTreeNode rootNode = new AndroidTreeNode(rootElement.getTagName());
    rootNode.setAttribute("Location", xml);
    loadNodes(rootElement, rootNode);
    DefaultTreeModel newModel = new DefaultTreeModel(rootNode);
    getTree().setModel(newModel);
}
 
Example 8
Project: mi-firma-android   File: IlpResponse.java   View Source Code Vote up 5 votes
private static List<String> getErrorsFromResponse(final byte[] serverResponse) {
	final List<String> ret = new ArrayList<String>();
	final InputStream is = new ByteArrayInputStream(serverResponse);
	final Document doc;
	try {
		doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
		is.close();
	}
	catch (final Exception e) {
		LOGGER.severe("Error analizando la respuesta del servidor: " + e); //$NON-NLS-1$
		return Collections.singletonList(
			"Error analizando la respuesta del servidor" //$NON-NLS-1$
		);
	}
	final Node errorsNode = doc.getDocumentElement();
	if (!"errors".equalsIgnoreCase(errorsNode.getNodeName())) { //$NON-NLS-1$
		LOGGER.severe("La respuesta del servidor no contiene un nodo padre de errores"); //$NON-NLS-1$
		return Collections.singletonList(
			"La respuesta del servidor no contiene un nodo padre de errores" //$NON-NLS-1$
		);
	}
	final NodeList childNodes = errorsNode.getChildNodes();
	int idx = nextNodeElementIndex(childNodes, 0);
	while (idx != -1) {
		final Node errorItemNode = childNodes.item(idx);
		ret.add(errorItemNode.getTextContent());
		idx = nextNodeElementIndex(childNodes, idx + 1);
	}
	return ret;
}
 
Example 9
Project: kaltura-ce-sakai-extension   File: KalturaAPIService.java   View Source Code Vote up 5 votes
/**
 * gets the metadata fields for a playlist
 * 
 * @param playlistIds the playlist's id (can be multiple ids)
 * @return map of {playlistId -> map of the playlist metadata {fieldname -> value} }
 * @throws IllegalArgumentException if playlistId is invalid
 * @throws RuntimeException if error getting metadata
 */
protected Map<String, Map<String, String>> getPlaylistMetadataFields(String... playlistIds) {
    if (log.isDebugEnabled()) log.debug("getPlaylistMetadataFields(playlistId="+Arrays.toString(playlistIds)+")");
    HashMap<String, Map<String, String>> m;
    if (playlistIds == null) {
        throw new IllegalArgumentException("playlistIds must not be null or empty");
    } else if (playlistIds.length == 0) {
        m = new HashMap<String, Map<String, String>>(0);
    } else {
        m = new HashMap<String, Map<String, String>>(playlistIds.length);
        Map<String, KalturaMetadata> metadataMap = getMetadataObjectsForKalturaPlaylistIds(playlistIds);
        for (String playlistId : playlistIds) {
            KalturaMetadata metadata = metadataMap.get(playlistId);
            Map<String, String> fields = new LinkedHashMap<String, String>();
            // if metadata exists for object
            if (metadata != null) {
                try {
                    Document metadataDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(metadata.xml)));
                    org.w3c.dom.Element root = metadataDoc.getDocumentElement();
                    NodeList childNodes = root.getChildNodes();
                    for (int i = 0; i < childNodes.getLength(); i++) {
                        Node node = childNodes.item(i);
                        if (node instanceof org.w3c.dom.Element) {
                            fields.put(node.getNodeName(), node.getTextContent());
                        }
                    }
                    fields = stripUnusedMetadataFields(fields, METADATA_PROFILE_NAME_PLAYLIST);
                } catch (Exception e) {
                    throw new RuntimeException("Error getting metadata fields for kaltura playlist " + playlistIds + " :: " + e, e);
                }
            } else { // if no existing metadata then use default metadata
                fields = initialMetadataFields.get(METADATA_PROFILE_NAME_PLAYLIST);
            }
            m.put(playlistId, fields);
        }
    }
    return m;
}
 
Example 10
Project: hadoop   File: TestQueuePlacementPolicy.java   View Source Code Vote up 5 votes
private QueuePlacementPolicy parse(String str) throws Exception {
  // Read and parse the allocations file.
  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
      .newInstance();
  docBuilderFactory.setIgnoringComments(true);
  DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
  Document doc = builder.parse(IOUtils.toInputStream(str));
  Element root = doc.getDocumentElement();
  return QueuePlacementPolicy.fromXml(root, configuredQueues, conf);
}
 
Example 11
Project: vind   File: SolrSchemaChecker.java   View Source Code Vote up 5 votes
public static void checkSchema(Path solrSchemaPath, SchemaResponse response) throws IOException, SchemaValidationException {
    // read the local schema.xml
    final Document local;
    try (InputStream xml = Files.newInputStream(solrSchemaPath, StandardOpenOption.READ)) {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        final DocumentBuilder builder = factory.newDocumentBuilder();

        local = builder.parse(xml);
    } catch (ParserConfigurationException | SAXException e) {
        log.error("Error checking schema.xml: {}", e.getMessage(), e);
        throw new IOException(e);
    }

    final SchemaRepresentation remote = response.getSchemaRepresentation();
    final Element schema = local.getDocumentElement();
    // check the field-types
    final NodeList fieldTypes = schema.getElementsByTagName("fieldType");
    final Set<String> fieldTypeNames = remote.getFieldTypes().stream()
            .map(FieldTypeDefinition::getAttributes)
            .map(m -> m.get("name"))
            .filter(Objects::nonNull)
            .map(String::valueOf)
            .collect(Collectors.toSet());
    for (int i = 0; i < fieldTypes.getLength(); i++) {
        final Node fieldType = fieldTypes.item(i);
        final String fieldTypeName = fieldType.getAttributes().getNamedItem("name").getNodeValue();
        if (! fieldTypeNames.contains(fieldTypeName)) {
            throw new SchemaValidationException(String.format("Missing <fieldType name='%s' />", fieldTypeName));
        }
    }

    // TODO: check local -> remote.

}
 
Example 12
Project: joai-project   File: Harvester.java   View Source Code Vote up 4 votes
/**
 *  Returns an array of the legal metadataFormats for the specified host.
 *
 * @param  baseURL                DESCRIPTION
 * @return                        The prefices value
 * @exception  Hexception         DESCRIPTION
 * @exception  OAIErrorException  DESCRIPTION
 */

private String[] getPrefices(String baseURL)
		 throws Hexception, OAIErrorException {
	int ii;

	String request = baseURL + "?verb=ListMetadataFormats";
	if (msgHandler != null) {
		msgHandler.statusMessage("A request for ListMetadataFormats has been made. Establishing connection with the data provider...");
	}
	Document doc = getDoc(request);

	Element root = doc.getDocumentElement();
	Element errele = findChild(root, "error");
	if (errele != null) {
		String oaiErrCode = errele.getAttribute("code");
		String errMsg = getContent(errele);
		if (errMsg == null) {
			errMsg = "";
		}
		throw new OAIErrorException(oaiErrCode, getContent(errele));
	}
	Element verbele = mustFindChild(root, "ListMetadataFormats");

	LinkedList reslist = new LinkedList();
	Element pfxele = mustFindChild(verbele, "metadataFormat");
	while (pfxele != null) {
		Element pfxspec = mustFindChild(pfxele, "metadataPrefix");
		reslist.add(getContent(pfxspec));
		pfxele = findSibling(pfxele, "metadataFormat");
	}
	String[] prefices = new String[reslist.size()];
	for (ii = 0; ii < prefices.length; ii++) {
		String prefix = (String) reslist.get(ii);
		prefices[ii] = prefix.replaceAll(":", "/");
		if (bugs >= 1) {
			prtln("prefix: \"" + prefices[ii] + "\"");
		}
	}
	return prefices;
}
 
Example 13
Project: openjdk-jdk10   File: DOMConfigurationTest.java   View Source Code Vote up 4 votes
/**
 * Equivalence class partitioning with state and input values orientation
 * for public void setParameter(String name, Object value) throws
 * DOMException, <br>
 * <b>pre-conditions</b>: the doc contains two subsequent processing
 * instrictions, <br>
 * <b>name</b>: canonical-form <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: the subsequent processing instrictions are
 * separated with a single line break
 */
@Test
public void testCanonicalForm001() {
    DOMImplementation domImpl = null;
    try {
        domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        Assert.fail(pce.toString());
    } catch (FactoryConfigurationError fce) {
        Assert.fail(fce.toString());
    }

    Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);

    DOMConfiguration config = doc.getDomConfig();

    Element root = doc.getDocumentElement();
    ProcessingInstruction pi1 = doc.createProcessingInstruction("target1", "data1");
    ProcessingInstruction pi2 = doc.createProcessingInstruction("target2", "data2");

    root.appendChild(pi1);
    root.appendChild(pi2);

    if (!config.canSetParameter("canonical-form", Boolean.TRUE)) {
        System.out.println("OK, setting 'canonical-form' to true is not supported");
        return;
    }

    config.setParameter("canonical-form", Boolean.TRUE);
    setHandler(doc);
    doc.normalizeDocument();

    Node child1 = root.getFirstChild();
    Node child2 = child1.getNextSibling();

    if (child2.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        Assert.fail("the second child is expected to be a" + "single line break, returned: " + child2);
    }

    // return Status.passed("OK");
}
 
Example 14
Project: alfresco-remote-api   File: PropPatchMethod.java   View Source Code Vote up 4 votes
/**
 * Parse the request body
 * 
 * @exception WebDAVServerException
 */
@Override
protected void parseRequestBody() throws WebDAVServerException
{
    Document body = getRequestBodyAsDocument();
    if (body != null)
    {
        Element rootElement = body.getDocumentElement();
        NodeList childList = rootElement.getChildNodes();

        m_propertyActions = new ArrayList<PropertyAction>();

        for (int i = 0; i < childList.getLength(); i++)
        {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType())
            {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                if (currentNode.getNodeName().endsWith(WebDAV.XML_SET) || currentNode.getNodeName().endsWith(WebDAV.XML_REMOVE))
                {
                    NodeList propertiesList = currentNode.getChildNodes();

                    for (int j = 0; j < propertiesList.getLength(); j++)
                    {
                        Node propertiesNode = propertiesList.item(j);
                        switch (propertiesNode.getNodeType())
                        {
                        case Node.TEXT_NODE:
                            break;
                        case Node.ELEMENT_NODE:
                            if (propertiesNode.getNodeName().endsWith(WebDAV.XML_PROP))
                            {
                                NodeList propList = propertiesNode.getChildNodes();

                                for (int k = 0; k < propList.getLength(); k++)
                                {
                                    Node propNode = propList.item(k);
                                    switch (propNode.getNodeType())
                                    {
                                    case Node.TEXT_NODE:
                                        break;
                                    case Node.ELEMENT_NODE:
                                        int action = currentNode.getNodeName().endsWith(WebDAV.XML_SET) ? PropertyAction.SET : PropertyAction.REMOVE;
                                        m_propertyActions.add(new PropertyAction(action, createProperty(propNode)));
                                        break;
                                }
                            }
                        }
                        break;
                        }
                    }
                }
                break;
            }
        }

    }
    
}
 
Example 15
Project: openjdk-jdk10   File: DOMConfigurationTest.java   View Source Code Vote up 4 votes
/**
 * Equivalence class partitioning with state and input values orientation
 * for public void setParameter(String name, Object value) throws
 * DOMException, <br>
 * <b>pre-conditions</b>: the doc contains one entity and one entity
 * reference, <br>
 * <b>name</b>: entities <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: the entity and the entity reference are left
 * unchanged
 */
@Test
public void testEntities001() {
    Document doc = null;
    try {
        doc = loadDocument(null, test1_xml);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }

    DOMConfiguration config = doc.getDomConfig();
    if (!config.canSetParameter("entities", Boolean.TRUE)) {
        Assert.fail("setting 'entities' to true is not supported");
    }

    Element root = doc.getDocumentElement();
    root.appendChild(doc.createEntityReference("x"));

    config.setParameter("entities", Boolean.TRUE);

    setHandler(doc);
    doc.normalizeDocument();
    Node child = root.getFirstChild();
    if (child == null) {
        Assert.fail("root has no child");
    }
    if (child.getNodeType() != Node.ENTITY_REFERENCE_NODE) {
        Assert.fail("root's child is " + child + ", expected entity reference &x;");
    }

    if (doc.getDoctype() == null) {
        Assert.fail("no doctype found");
    }

    if (doc.getDoctype().getEntities() == null) {
        Assert.fail("no entitiy found");
    }

    if (doc.getDoctype().getEntities().getNamedItem("x") == null) {
        Assert.fail("no entitiy with name 'x' found");
    }

    return; // Status.passed("OK");
}
 
Example 16
Project: OpenJSharp   File: DOMUtil.java   View Source Code Vote up 4 votes
public static Element getRoot(Document doc) {
    return doc.getDocumentElement();
}
 
Example 17
Project: convertigo-engine   File: XMLCopyStep.java   View Source Code Vote up 4 votes
@Override
public XmlSchemaObject getXmlSchemaObject(XmlSchemaCollection collection, XmlSchema schema) {
	try {
		StepSource source = getTargetSource();
		if (!source.isEmpty()) {
			XmlSchemaObject object = SchemaMeta.getXmlSchemaObject(schema, source.getStep());
			if (object != null) {
				SchemaMeta.setSchema(object, schema);
				String xpath = source.getXpath();
				String anchor = source.getAnchor() + getTargetXPath();
				if (!".".equals(xpath)) {
					Map<Node, XmlSchemaObject> references = new HashMap<Node, XmlSchemaObject>();
					Document doc = XmlSchemaUtils.getDomInstance(object, references);
					//String sDoc = XMLUtils.prettyPrintDOM(doc);
					Element contextNode = doc.getDocumentElement();
					if (anchor.startsWith("//"+contextNode.getNodeName()+"/")) {
						anchor = anchor.replaceFirst("//"+contextNode.getNodeName()+"/", "./");
					}
					NodeList list = getXPathAPI().selectNodeList(contextNode, anchor);
					if (list != null) {
						boolean isList = false;
						if (list.getLength() > 1) {
							isList = true;
							object = XmlSchemaUtils.makeDynamic(this, new XmlSchemaSequence());
						}
						
						for (int i = 0; i < list.getLength(); i++) {
							Node node = list.item(i);
							XmlSchemaObject referenced = references.get(node);
							if (referenced != null) {
								if (isList) {
									XmlSchemaSequence xmlSchemaSequence = (XmlSchemaSequence)object;
									xmlSchemaSequence.getItems().add(referenced);
								}
								else {
									object = referenced;
								}
							}
						}
					}
				}
				return object;
			}
		}
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
	return super.getXmlSchemaObject(collection, schema);
}
 
Example 18
Project: OSWf-OSWorkflow-fork   File: XMLHelper.java   View Source Code Vote up 4 votes
public static Element getDocumentRoot(Document document) {
    return (Element)document.getDocumentElement();
}
 
Example 19
Project: convertigo-engine   File: Create.java   View Source Code Vote up 3 votes
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
	
	this.document = document;
	rootElement = document.getDocumentElement();
	    
       createElements(request);
}
 
Example 20
Project: SVG_taiwan_View   File: MapView.java   View Source Code Vote up 2 votes
@Override
public void run() {
    InputStream inputStream = context.getResources().openRawResource(R.raw.taiwanhigh);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;

    try {
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(inputStream);

        Element rootElement = doc.getDocumentElement();
        NodeList items = rootElement.getElementsByTagName("path");
        for (int i = 0; i <items.getLength() ; i++) {
            Element element = (Element) items.item(i);
            String pathData = element.getAttribute("android:pathData");

            Path path = PathParser.createPathFromPathData(pathData);


            RectF rectF = new RectF();
            path.computeBounds(rectF,true);

            left = left == -1 ? rectF.left : Math.min(rectF.left,left);
            top = top == -1 ? rectF.top : Math.min(rectF.top,top);

            right = right == -1 ? rectF.right : Math.max(rectF.right,right);
            bottom = bottom == -1 ? rectF.bottom : Math.max(rectF.bottom,bottom);



            CountyItem countyItem = new CountyItem(path);

            countyItems.add(countyItem);


        }
        topRectF = new RectF(left,top,right,bottom);
        handler.sendEmptyMessage(1);
    } catch (Exception e) {
        e.printStackTrace();
    }


}