org.w3c.dom.Document Java Examples
The following examples show how to use
org.w3c.dom.Document.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WSDLToCorbaBindingTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testUnionType() throws Exception { try { String fileName = getClass().getResource("/wsdl/uniontype.wsdl").toString(); generator.setWsdlFile(fileName); generator.addInterfaceName("Test.MultiPart"); Definition model = generator.generateCORBABinding(); Document document = writer.getDocument(model); Element typemap = getElementNode(document, "corba:typeMapping"); assertNotNull(typemap); assertEquals(1, typemap.getElementsByTagName("corba:union").getLength()); assertEquals(1, typemap.getElementsByTagName("corba:enum").getLength()); WSDLToIDLAction idlgen = new WSDLToIDLAction(); idlgen.setBindingName("Test.MultiPartCORBABinding"); idlgen.setOutputFile("uniontype.idl"); idlgen.generateIDL(model); File f = new File("uniontype.idl"); assertTrue("uniontype.idl should be generated", f.exists()); } finally { new File("uniontype.idl").deleteOnExit(); } }
Example #2
Source File: WSDLParser.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
public WSDLDocument parse() throws SAXException, IOException { // parse external binding files for (InputSource value : options.getWSDLBindings()) { errReceiver.pollAbort(); Document root = forest.parse(value, false); if(root==null) continue; // error must have been reported Element binding = root.getDocumentElement(); if (!Internalizer.fixNull(binding.getNamespaceURI()).equals(JAXWSBindingsConstants.NS_JAXWS_BINDINGS) || !binding.getLocalName().equals("bindings")){ errReceiver.error(forest.locatorTable.getStartLocation(binding), WsdlMessages.PARSER_NOT_A_BINDING_FILE( binding.getNamespaceURI(), binding.getLocalName())); continue; } NodeList nl = binding.getElementsByTagNameNS( "http://java.sun.com/xml/ns/javaee", "handler-chains"); for(int i = 0; i < nl.getLength(); i++){ options.addHandlerChainConfiguration((Element) nl.item(i)); } } return buildWSDLDocument(); }
Example #3
Source File: FixProjectsUtils.java From hybris-commerce-eclipse-plugin with Apache License 2.0 | 6 votes |
private static void removeAndAddComment(Document doc, String moduleName) { Node extensionNode; Node moduleNode; moduleNode = doc.getElementsByTagName(moduleName).item(0); if (moduleNode != null) { extensionNode = moduleNode.getParentNode(); NamedNodeMap attrs = moduleNode.getAttributes(); StringBuilder sb = new StringBuilder("<"); sb.append(moduleName); for (int i = 0 ; i<attrs.getLength() ; i++) { Attr attribute = (Attr)attrs.item(i); sb.append(" " + attribute.getName() + "=\"" + attribute.getValue() + "\""); } sb.append("/>"); appendXmlFragment(extensionNode, sb.toString()); extensionNode.removeChild(moduleNode); } }
Example #4
Source File: BasicLayoutProcessor.java From ttt with BSD 2-Clause "Simplified" License | 6 votes |
@Override public List<Area> layout(Document d) { List<Area> areas = null; if (d != null) { Element root = d.getDocumentElement(); if (root != null) { LayoutState ls = makeLayoutState(); if (isElement(root, isdSequenceElementName)) areas = layoutISDSequence(root, ls); else if (isElement(root, isdInstanceElementName)) areas = layoutISDInstance(root, ls); warnOnCounterViolations(ls); } } return (areas != null) ? areas : new java.util.ArrayList<Area>(); }
Example #5
Source File: AddonsListFetcher.java From java-n-IDE-for-Android with Apache License 2.0 | 6 votes |
/** * Takes an XML document as a string as parameter and returns a DOM for it. * * On error, returns null and prints a (hopefully) useful message on the monitor. */ @VisibleForTesting(visibility=Visibility.PRIVATE) protected Document getDocument(InputStream xml, ITaskMonitor monitor) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(true); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); assert xml.markSupported(); xml.reset(); Document doc = builder.parse(new InputSource(xml)); return doc; } catch (ParserConfigurationException e) { monitor.logError("Failed to create XML document builder"); } catch (SAXException e) { monitor.logError("Failed to parse XML document"); } catch (IOException e) { monitor.logError("Failed to read XML document"); } return null; }
Example #6
Source File: AlgorithmsParametersMarshallingProviderImpl.java From xades4j with GNU Lesser General Public License v3.0 | 6 votes |
@Override public List<Node> marshalParameters(Algorithm alg, Document doc) throws UnsupportedAlgorithmException { AlgorithmParametersMarshaller marshaller; try { ParameterizedType pt = Types.newParameterizedType(AlgorithmParametersMarshaller.class, alg.getClass()); marshaller = (AlgorithmParametersMarshaller) injector.getInstance(Key.get(TypeLiteral.get(pt))); } catch (RuntimeException ex) { throw new UnsupportedAlgorithmException("AlgorithmParametersMarshaller not available", alg.getUri(), ex); } List<Node> params = marshaller.marshalParameters(alg, doc); if (params != null && params.isEmpty()) { throw new IllegalArgumentException(String.format("Parameter marshaller returned empty parameter list for algorithm %s", alg.getUri())); } return params; }
Example #7
Source File: KeyValue.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Constructor KeyValue * * @param doc * @param pk */ public KeyValue(Document doc, PublicKey pk) { super(doc); XMLUtils.addReturnToElement(this.constructionElement); if (pk instanceof java.security.interfaces.DSAPublicKey) { DSAKeyValue dsa = new DSAKeyValue(this.doc, pk); this.constructionElement.appendChild(dsa.getElement()); XMLUtils.addReturnToElement(this.constructionElement); } else if (pk instanceof java.security.interfaces.RSAPublicKey) { RSAKeyValue rsa = new RSAKeyValue(this.doc, pk); this.constructionElement.appendChild(rsa.getElement()); XMLUtils.addReturnToElement(this.constructionElement); } }
Example #8
Source File: DavCmpFsImpl.java From io with Apache License 2.0 | 6 votes |
private Element parseProp(String value) { // valをDOMでElement化 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = null; Document doc = null; try { builder = factory.newDocumentBuilder(); ByteArrayInputStream is = new ByteArrayInputStream(value.getBytes(CharEncoding.UTF_8)); doc = builder.parse(is); } catch (Exception e1) { throw DcCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e1); } Element e = doc.getDocumentElement(); return e; }
Example #9
Source File: SignedInfo.java From axelor-open-suite with GNU Affero General Public License v3.0 | 6 votes |
/** * Canonizes and signs a given input with the authentication private key. of the EBICS user. * * <p>The given input to be signed is first Canonized using the * http://www.w3.org/TR/2001/REC-xml-c14n-20010315 algorithm. * * <p>The element to be canonized is only the SignedInfo element that should be contained in the * request to be signed. Otherwise, a {@link TransformationException} is thrown. * * <p>The namespace of the SignedInfo element should be named <b>ds</b> as specified in the EBICS * specification for common namespaces nomination. * * <p>The signature is ensured using the user X002 private key. This step is done in {@link * EbicsUser#authenticate(byte[]) authenticate}. * * @param toSign the input to sign * @return the signed input * @throws EbicsException signature fails. */ public byte[] sign(byte[] toSign) throws AxelorException { try { DocumentBuilderFactory factory; DocumentBuilder builder; Document document; Node node; Canonicalizer canonicalizer; factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); builder = factory.newDocumentBuilder(); builder.setErrorHandler(new IgnoreAllErrorHandler()); document = builder.parse(new ByteArrayInputStream(toSign)); node = XPathAPI.selectSingleNode(document, "//ds:SignedInfo"); canonicalizer = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); return Beans.get(EbicsUserService.class) .authenticate(user, canonicalizer.canonicalizeSubtree(node)); } catch (Exception e) { e.printStackTrace(); throw new AxelorException(e, TraceBackRepository.CATEGORY_CONFIGURATION_ERROR); } }
Example #10
Source File: PXDOMStyleAdapter.java From pixate-freestyle-android with Apache License 2.0 | 6 votes |
@Override public boolean updateStyle(List<PXRuleSet> ruleSets, List<PXStylerContext> contexts) { for (int i = 0; i < ruleSets.size(); i++) { PXStylerContext context = contexts.get(i); PXRuleSet ruleSet = ruleSets.get(i); Node node = (Node) context.getStyleable(); Document ownerDocument = node.getOwnerDocument(); NamedNodeMap attributes = node.getAttributes(); for (PXDeclaration declaration : ruleSet.getDeclarations()) { String name = declaration.getName(); String value = declaration.getStringValue(); // Set the node's attribute Node attNode = ownerDocument.createAttribute(name); attNode.setNodeValue(value); attributes.setNamedItem(attNode); } } return true; }
Example #11
Source File: CreateMVPFiles.java From MvpCodeCreator with Apache License 2.0 | 6 votes |
private String readPackageName() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(project.getBasePath() + "/App/src/main/AndroidManifest.xml"); NodeList dogList = doc.getElementsByTagName("manifest"); for (int i = 0; i < dogList.getLength(); i++) { Node dog = dogList.item(i); Element elem = (Element) dog; return elem.getAttribute("package"); } } catch (Exception e) { e.printStackTrace(); } return ""; }
Example #12
Source File: WebProjectUtilsImpl.java From gvnix with GNU General Public License v3.0 | 6 votes |
/** * Append a css definition in loadScript.tagx * <p/> * This first append a "spring:url" (if not exists) and then add the "link" * tag (if not exists) * * @param docTagx loadScript.tagx document * @param root root node * @param varName name of variable to hold css url * @param location css location * @return document has changed */ public boolean updateCssToTag(Document docTagx, Element root, String varName, String location) { boolean modified = false; // add url resolution modified = updateUrlToTag(docTagx, root, varName, location); // Add link Element cssElement = XmlUtils.findFirstElement( String.format("link[@href='${%s}']", varName), root); if (cssElement == null) { cssElement = docTagx.createElement("link"); cssElement.setAttribute("rel", "stylesheet"); cssElement.setAttribute("type", "text/css"); cssElement.setAttribute("media", "screen"); cssElement.setAttribute("href", "${".concat(varName).concat("}")); root.appendChild(cssElement); modified = true; } return modified; }
Example #13
Source File: Kyero_3.java From OpenEstate-IO with Apache License 2.0 | 6 votes |
/** * Upgrade <currency> elements to Kyero 3. * <p> * The <currency> only supports the values "EUR", "GBP", "USD" in * version 3. * <p> * Any <currency> with an unsupported value is removed from the * document. * * @param doc Kyero document in version 2.1 * @throws JaxenException if xpath evaluation failed */ protected void upgradeCurrencyElements(Document doc) throws JaxenException { List nodes = XmlUtils.newXPath( "/io:root/io:property/io:currency", doc).selectNodes(doc); for (Object item : nodes) { Element node = (Element) item; Element parentNode = (Element) node.getParentNode(); String value = StringUtils.trimToNull(node.getTextContent()); if ("EUR".equalsIgnoreCase(value)) node.setTextContent("EUR"); else if ("GBP".equalsIgnoreCase(value)) node.setTextContent("GBP"); else if ("USD".equalsIgnoreCase(value)) node.setTextContent("USD"); else parentNode.removeChild(node); } }
Example #14
Source File: WSDL11Validator.java From cxf with Apache License 2.0 | 6 votes |
private Document getWSDLDoc(String wsdl) { LOG.log(Level.FINE, new Message("VALIDATE_WSDL", LOG, wsdl).toString()); try { OASISCatalogManager catalogResolver = OASISCatalogManager.getCatalogManager(this.getBus()); String nw = new OASISCatalogManagerHelper().resolve(catalogResolver, wsdl, null); if (nw == null) { nw = wsdl; } return new Stax2DOM().getDocument(URIParserUtil.getAbsoluteURI(nw)); } catch (FileNotFoundException fe) { LOG.log(Level.WARNING, "Cannot find the wsdl " + wsdl + "to validate"); return null; } catch (Exception e) { throw new ToolException(e); } }
Example #15
Source File: MaintainableXMLConversionServiceImpl.java From rice with Educational Community License v2.0 | 5 votes |
private String transformSection(String xml) { String maintenanceAction = StringUtils.substringBetween(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">", "</" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"); xml = StringUtils.substringBefore(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"); try { xml = upgradeBONotes(xml); if (classNameRuleMap == null) { setRuleMaps(); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new InputSource(new StringReader(xml))); removePersonObjects(document); for(Node childNode = document.getFirstChild(); childNode != null;) { Node nextChild = childNode.getNextSibling(); transformClassNode(document, childNode); childNode = nextChild; } TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer trans = transFactory.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); DOMSource source = new DOMSource(document); trans.transform(source, result); xml = writer.toString().replaceAll("(?m)^\\s+\\n", ""); } catch (Exception e) { e.printStackTrace(); } return xml + "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">" + maintenanceAction + "</" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"; }
Example #16
Source File: SOAPRequestTypesDateTimeListLeapYearTest.java From cougar with Apache License 2.0 | 5 votes |
@Test public void doTest() throws Exception { // Create the SOAP request as an XML Document (with a dateTimeList parameter containing a date set to Feb 29th in a leap year) XMLHelpers xMLHelpers1 = new XMLHelpers(); Document createAsDocument1 = xMLHelpers1.getXMLObjectFromString("<DateTimeListOperationRequest><message><dateTimeList><Date>2012-02-29T13:50:00Z</Date><Date>2012-02-29T13:50:00Z</Date></dateTimeList></message></DateTimeListOperationRequest>"); // Set up the Http Call Bean to make the request CougarManager cougarManager2 = CougarManager.getInstance(); HttpCallBean hbean = cougarManager2.getNewHttpCallBean("87.248.113.14"); CougarManager hinstance = cougarManager2; hbean.setServiceName("Baseline"); hbean.setVersion("v2"); // Create the date object expected to be returned in the response String convertUTCDateTimeToCougarFormat6 = TimingHelpers.convertUTCDateTimeToCougarFormat((int) 2012, (int) 2, (int) 29, (int) 13, (int) 50, (int) 0, (int) 0); // Set the created SOAP request as the PostObject hbean.setPostObjectForRequestType(createAsDocument1, "SOAP"); // Get current time for getting log entries later Timestamp getTimeAsTimeStamp8 = new Timestamp(System.currentTimeMillis()); // Make the SOAP call to the operation hinstance.makeSoapCougarHTTPCalls(hbean); // Create the expected response object as an XML document (using the date object created earlier) XMLHelpers xMLHelpers5 = new XMLHelpers(); Document createAsDocument10 = xMLHelpers5.createAsDocument(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(("<response><responseList><Date>"+convertUTCDateTimeToCougarFormat6+"</Date><Date>"+convertUTCDateTimeToCougarFormat6+"</Date></responseList></response>").getBytes()))); // Check the response is as expected HttpResponseBean response6 = hbean.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.SOAP); AssertionUtils.multiAssertEquals(createAsDocument10, response6.getResponseObject()); // generalHelpers.pauseTest(3000L); // Check the log entries are as expected hinstance.verifyRequestLogEntriesAfterDate(getTimeAsTimeStamp8, new RequestLogRequirement("2.8", "dateTimeListOperation") ); }
Example #17
Source File: SlaveServer.java From pentaho-kettle with Apache License 2.0 | 5 votes |
public long getNextSlaveSequenceValue( String slaveSequenceName, long incrementValue ) throws KettleException { try { String xml = execService( NextSequenceValueServlet.CONTEXT_PATH + "/" + "?" + NextSequenceValueServlet.PARAM_NAME + "=" + URLEncoder.encode( slaveSequenceName, "UTF-8" ) + "&" + NextSequenceValueServlet.PARAM_INCREMENT + "=" + Long.toString( incrementValue ) ); Document doc = XMLHandler.loadXMLString( xml ); Node seqNode = XMLHandler.getSubNode( doc, NextSequenceValueServlet.XML_TAG ); String nextValueString = XMLHandler.getTagValue( seqNode, NextSequenceValueServlet.XML_TAG_VALUE ); String errorString = XMLHandler.getTagValue( seqNode, NextSequenceValueServlet.XML_TAG_ERROR ); if ( !Utils.isEmpty( errorString ) ) { throw new KettleException( errorString ); } if ( Utils.isEmpty( nextValueString ) ) { throw new KettleException( "No value retrieved from slave sequence '" + slaveSequenceName + "' on slave " + toString() ); } long nextValue = Const.toLong( nextValueString, Long.MIN_VALUE ); if ( nextValue == Long.MIN_VALUE ) { throw new KettleException( "Incorrect value '" + nextValueString + "' retrieved from slave sequence '" + slaveSequenceName + "' on slave " + toString() ); } return nextValue; } catch ( Exception e ) { throw new KettleException( "There was a problem retrieving a next sequence value from slave sequence '" + slaveSequenceName + "' on slave " + toString(), e ); } }
Example #18
Source File: SAMLClaimsTest.java From cxf with Apache License 2.0 | 5 votes |
@org.junit.Test public void testSAML1Claims() throws Exception { AttributeBean attributeBean = new AttributeBean(); attributeBean.setSimpleName("role"); attributeBean.setQualifiedName("http://schemas.xmlsoap.org/ws/2005/05/identity/claims"); attributeBean.addAttributeValue("employee"); SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(false); samlCallbackHandler.setAttributes(Collections.singletonList(attributeBean)); // Create the SAML Assertion via the CallbackHandler SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); Document doc = DOMUtils.newDocument(); samlAssertion.toDOM(doc); ClaimCollection claims = SAMLUtils.getClaims(samlAssertion); assertEquals(claims.getDialect().toString(), "http://schemas.xmlsoap.org/ws/2005/05/identity"); assertEquals(1, claims.size()); // Check Claim values Claim claim = claims.get(0); assertEquals(claim.getClaimType(), SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT); assertEquals(1, claim.getValues().size()); assertTrue(claim.getValues().contains("employee")); // Check SAMLClaim values assertTrue(claim instanceof SAMLClaim); assertEquals("role", ((SAMLClaim)claim).getName()); // Check roles Set<Principal> roles = SAMLUtils.parseRolesFromClaims(claims, "role", null); assertEquals(1, roles.size()); Principal p = roles.iterator().next(); assertEquals("employee", p.getName()); }
Example #19
Source File: DOMCategory.java From groovy with Apache License 2.0 | 5 votes |
public static void putAt(Element self, String property, Object value) { if (property.startsWith("@")) { String attributeName = property.substring(1); Document doc = self.getOwnerDocument(); Attr newAttr = doc.createAttribute(attributeName); newAttr.setValue(value.toString()); self.setAttributeNode(newAttr); return; } InvokerHelper.setProperty(self, property, value); }
Example #20
Source File: ActiveToolComponent.java From sakai with Educational Community License v2.0 | 5 votes |
/** * @inheritDoc */ public void register(File toolXmlFile, ServletContext context) { String path = toolXmlFile.getAbsolutePath(); if (!path.endsWith(".xml")) { log.info("register: skiping non .xml file: " + path); return; } log.info("register: file: " + path); Document doc = Xml.readDocument(path); register(doc, context); }
Example #21
Source File: Texto.java From brModelo with GNU General Public License v3.0 | 5 votes |
@Override protected void ToXmlValores(Document doc, Element me) { super.ToXmlValores(doc, me); me.appendChild(util.XMLGenerate.ValorText(doc, "Titulo", getTitulo())); me.appendChild(util.XMLGenerate.ValorBoolean(doc, "PaintTitulo", isPaintTitulo())); me.appendChild(util.XMLGenerate.ValorInteger(doc, "Alinhamento", getAlinhamento().ordinal())); me.appendChild(util.XMLGenerate.ValorBoolean(doc, "CentrarVertical", isCentrarVertical())); me.appendChild(util.XMLGenerate.ValorInteger(doc, "Tipo", getTipo().ordinal())); me.appendChild(util.XMLGenerate.ValorColor(doc, "BackColor", getBackColor())); me.appendChild(util.XMLGenerate.ValorBoolean(doc, "Sombra", isSombra())); me.appendChild(util.XMLGenerate.ValorColor(doc, "CorSombra", getCorSombra())); me.appendChild(util.XMLGenerate.ValorBoolean(doc, "Gradiente", isGradiente())); me.appendChild(util.XMLGenerate.ValorColor(doc, "GradienteStartColor", getGradienteStartColor())); me.appendChild(util.XMLGenerate.ValorColor(doc, "GradienteEndColor", getGradienteEndColor())); me.appendChild(util.XMLGenerate.ValorBoolean(doc, "GradientePinteDetalhe", isGradientePinteDetalhe())); me.appendChild(util.XMLGenerate.ValorColor(doc, "GradienteCorDetalhe", getGradienteCorDetalhe())); me.appendChild(util.XMLGenerate.ValorInteger(doc, "GDirecao", getGDirecao())); me.appendChild(util.XMLGenerate.ValorInteger(doc, "Alfa", (int)(100 * getAlfa()))); me.appendChild(util.XMLGenerate.ValorBoolean(doc, "Autosize", isAutosize())); me.appendChild(util.XMLGenerate.ValorBoolean(doc, "MovimentacaoManual", isMovimentacaoManual())); //remover dicionário do XML do objeto. NodeList nl = me.getElementsByTagName("Dicionario"); if (nl != null && nl.getLength() > 0) { me.removeChild(nl.item(0)); } }
Example #22
Source File: GENAEventProcessorImpl.java From DroidDLNA with GNU General Public License v3.0 | 5 votes |
protected void writeProperties(Document d, Element propertysetElement, OutgoingEventRequestMessage message) { for (StateVariableValue stateVariableValue : message.getStateVariableValues()) { Element propertyElement = d.createElementNS(Constants.NS_UPNP_EVENT_10, "e:property"); propertysetElement.appendChild(propertyElement); XMLUtil.appendNewElement( d, propertyElement, stateVariableValue.getStateVariable().getName(), stateVariableValue.toString() ); } }
Example #23
Source File: Feature317.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
@NoWarning("IIL_ELEMENTS_GET_LENGTH_IN_LOOP") public static double getAvgPriorityFast(Document document) { NodeList bugs = document.getElementsByTagName("BugInstance"); int prioritySum = 0; int length = bugs.getLength(); for(int i=0; i<length; i++) { prioritySum += Integer.parseInt(((Element)bugs.item(i)).getAttribute("priority")); } return ((double)prioritySum)/length; }
Example #24
Source File: XMLRipperOutput.java From AndroidRipper with GNU Affero General Public License v3.0 | 5 votes |
@Override public String outputEvent(IEvent evt) { try { Document doc = this.buildIEventDescriptionDocument(evt, EVENT); return this.XML2String(doc); } catch (ParserConfigurationException pex) { pex.printStackTrace(); } return null; }
Example #25
Source File: Http.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
/** * Parse the input HTML into a DOM. */ public Element parseHTML(String html) throws Exception { String xhtml = convertToXHTML(html); StringReader reader = new StringReader(xhtml); Document document = getParser().parse(new InputSource(reader)); return document.getDocumentElement(); }
Example #26
Source File: DecoderTest.java From jStyleParser with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void boxShadow() throws SAXException, IOException { DOMSource ds = new DOMSource(getClass().getResourceAsStream("/advanced/boxshadow.html")); Document doc = ds.parse(); ElementMap elements = new ElementMap(doc); StyleMap decl = CSSFactory.assignDOM(doc, null, getClass().getResource("/advanced/boxshadow.html"), "screen", true); Map<String, Integer> elementsToCheck = new LinkedHashMap<>(); elementsToCheck.put("shadow1", 4); elementsToCheck.put("shadow2", 4); elementsToCheck.put("shadow3", 5); elementsToCheck.put("shadow4", 6); elementsToCheck.put("shadow5", 2); elementsToCheck.put("shadow_multi1", 8); elementsToCheck.put("shadow_multi2", 7); elementsToCheck.put("shadow_multi3", 12); for (Map.Entry<String, Integer> entry : elementsToCheck.entrySet()) { NodeData data = decl.get(elements.getElementById(entry.getKey())); assertNotNull("Data for #" + entry.getKey() + " exists", data); TermList value = data.getValue(TermList.class, "box-shadow"); assertNotNull("TermList for #" + entry.getKey() + " exists", value); assertEquals("parsed all components of shadow for #" + entry.getKey(), (int)entry.getValue(), value.size()); } }
Example #27
Source File: EpubBook.java From BookyMcBookface with GNU General Public License v3.0 | 5 votes |
private static Map<String,?> processToc(BufferedReader tocReader) { Map<String,Object> bookdat = new LinkedHashMap<>(); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); XPathFactory factory = XPathFactory.newInstance(); DocumentBuilder builder = null; try { builder = dfactory.newDocumentBuilder(); tocReader.mark(4); if ('\ufeff' != tocReader.read()) tocReader.reset(); // not the BOM marker Document doc = builder.parse(new InputSource(tocReader)); XPath tocPath = factory.newXPath(); tocPath.setNamespaceContext(tocnsc); Node nav = (Node)tocPath.evaluate("/ncx/navMap", doc, XPathConstants.NODE); int total = readNavPoint(nav, tocPath, bookdat, 0); bookdat.put(TOCCOUNT, total); } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) { Log.e("BMBF", "Error parsing xml " + e.getMessage(), e); } return bookdat; }
Example #28
Source File: XMLConverterTest.java From development with Apache License 2.0 | 5 votes |
@Test public void testGetNodeTextContentByXPath2() throws Exception { final String s = "<test><a/><b/><c/></test>"; final Document doc = XMLConverter.convertToDocument(s, false); final String text = XMLConverter.getNodeTextContentByXPath(doc, "//test/x"); assertNull(text); }
Example #29
Source File: ModelLoader.java From hottub with GNU General Public License v2.0 | 5 votes |
/** * Parses a set of schemas inside a WSDL file. * * A WSDL file may contain multiple <xsd:schema> elements. */ private XSSchemaSet loadWSDL() throws SAXException { // build DOMForest just like we handle XML Schema DOMForest forest = buildDOMForest( new XMLSchemaInternalizationLogic() ); DOMForestScanner scanner = new DOMForestScanner(forest); XSOMParser xsomParser = createXSOMParser( forest ); // find <xsd:schema>s and parse them individually for( InputSource grammar : opt.getGrammars() ) { Document wsdlDom = forest.get( grammar.getSystemId() ); if (wsdlDom == null) { String systemId = Options.normalizeSystemId(grammar.getSystemId()); if (forest.get(systemId) != null) { grammar.setSystemId(systemId); wsdlDom = forest.get( grammar.getSystemId() ); } } NodeList schemas = wsdlDom.getElementsByTagNameNS(XMLConstants.W3C_XML_SCHEMA_NS_URI,"schema"); for( int i=0; i<schemas.getLength(); i++ ) scanner.scan( (Element)schemas.item(i), xsomParser.getParserHandler() ); } return xsomParser.getResult(); }
Example #30
Source File: SamlResponseHelper.java From keycloak-protocol-cas with Apache License 2.0 | 5 votes |
public static Document toDOM(SAML11ResponseType response) throws ParserConfigurationException, XMLStreamException, ProcessingException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); XMLOutputFactory factory = XMLOutputFactory.newFactory(); Document doc = dbf.newDocumentBuilder().newDocument(); DOMResult result = new DOMResult(doc); XMLStreamWriter xmlWriter = factory.createXMLStreamWriter(result); SAML11ResponseWriter writer = new SAML11ResponseWriter(xmlWriter); writer.write(response); return doc; }