List of usage examples for org.w3c.dom Document getFirstChild
public Node getFirstChild();
From source file:com.marklogic.client.functionaltest.TestBulkSearchWithStrucQueryDef.java
@Test public void testExtractDocumentData4() throws Exception { String head = "<search:search xmlns:search=\"http://marklogic.com/appservices/search\">"; String tail = "</search:search>"; String qtext4 = "<search:qtext>71 OR dog14</search:qtext>"; DocumentManager docMgr = client.newDocumentManager(); QueryManager queryMgr = client.newQueryManager(); String options = "<search:options>" + "<search:extract-document-data selected=\"include\">" + "<search:extract-path>//foo</search:extract-path>" + "<search:extract-path>//says</search:extract-path>" + "</search:extract-document-data>" + "</search:options>"; // test XML response with extracted XML and JSON matches String combinedSearch = head + qtext4 + options + tail; RawCombinedQueryDefinition rawCombinedQueryDefinition = queryMgr .newRawCombinedQueryDefinition(new StringHandle(combinedSearch).withMimetype("application/xml")); SearchHandle results = queryMgr.search(rawCombinedQueryDefinition, new SearchHandle()); MatchDocumentSummary[] summaries = results.getMatchResults(); assertNotNull(summaries);// w w w . j a va 2 s. com assertEquals(2, summaries.length); for (MatchDocumentSummary summary : summaries) { ExtractedResult extracted = summary.getExtracted(); if (Format.XML == summary.getFormat()) { // we don't test for kind because it isn't sent in this case assertEquals(1, extracted.size()); Document item1 = extracted.next().getAs(Document.class); assertEquals("This is so foo with a bar 71", item1.getFirstChild().getTextContent()); continue; } else if (Format.JSON == summary.getFormat()) { // we don't test for kind because it isn't sent in this case assertEquals(1, extracted.size()); for (ExtractedItem item : extracted) { String stringJsonItem = item.getAs(String.class); JsonNode nodeJsonItem = item.getAs(JsonNode.class); if (nodeJsonItem.has("says")) { assertEquals("{\"says\":\"woof\"}", stringJsonItem); continue; } fail("unexpected extracted item:" + stringJsonItem); } continue; } fail("unexpected search result:" + summary.getUri()); } }
From source file:com.marklogic.client.functionaltest.TestBulkSearchWithStrucQueryDef.java
@Test public void testExtractDocumentData5() throws Exception { String head = "<search:search xmlns:search=\"http://marklogic.com/appservices/search\">"; String tail = "</search:search>"; String qtext4 = "<search:qtext>71 OR dog14</search:qtext>"; DocumentManager docMgr = client.newDocumentManager(); QueryManager queryMgr = client.newQueryManager(); String options = "<search:options>" + "<search:extract-document-data selected=\"all\">" + "<search:extract-path>//foo</search:extract-path>" + "<search:extract-path>//says</search:extract-path>" + "</search:extract-document-data>" + "</search:options>"; // test XML response with extracted XML and JSON matches String combinedSearch = head + qtext4 + options + tail; RawCombinedQueryDefinition rawCombinedQueryDefinition = queryMgr .newRawCombinedQueryDefinition(new StringHandle(combinedSearch).withMimetype("application/xml")); SearchHandle results = queryMgr.search(rawCombinedQueryDefinition, new SearchHandle()); MatchDocumentSummary[] summaries = results.getMatchResults(); assertNotNull(summaries);//ww w.ja va2s . com assertEquals(2, summaries.length); for (MatchDocumentSummary summary : summaries) { ExtractedResult extracted = summary.getExtracted(); if (Format.XML == summary.getFormat()) { // we don't test for kind because it isn't sent in this case assertEquals(1, extracted.size()); Document item1 = extracted.next().getAs(Document.class); assertEquals("This is so foo with a bar 71", item1.getFirstChild().getTextContent()); continue; } else if (Format.JSON == summary.getFormat()) { // we don't test for kind because it isn't sent in this case assertEquals(1, extracted.size()); for (ExtractedItem item : extracted) { String stringJsonItem = item.getAs(String.class); JsonNode nodeJsonItem = item.getAs(JsonNode.class); if (nodeJsonItem.has("says")) { assertEquals("{\"animal\":\"dog14\", \"says\":\"woof\"}", stringJsonItem); continue; } fail("unexpected extracted item:" + stringJsonItem); } continue; } fail("unexpected search result:" + summary.getUri()); } }
From source file:com.marklogic.client.functionaltest.TestBulkSearchWithStrucQueryDef.java
@Test public void testExtractDocumentData() throws Exception { this.loadJSONDocuments(); this.loadXMLDocuments(); String head = "<search:search xmlns:search=\"http://marklogic.com/appservices/search\">"; String tail = "</search:search>"; String qtext4 = "<search:qtext>71 OR dog14</search:qtext>"; DocumentManager docMgr = client.newDocumentManager(); QueryManager queryMgr = client.newQueryManager(); String options = "<search:options>" + "<search:extract-document-data>" + "<search:extract-path>//foo</search:extract-path>" + "<search:extract-path>//says</search:extract-path>" + "</search:extract-document-data>" + "</search:options>"; // test XML response with extracted XML and JSON matches String combinedSearch = head + qtext4 + options + tail; RawCombinedQueryDefinition rawCombinedQueryDefinition = queryMgr .newRawCombinedQueryDefinition(new StringHandle(combinedSearch).withMimetype("application/xml")); SearchHandle results = queryMgr.search(rawCombinedQueryDefinition, new SearchHandle()); MatchDocumentSummary[] summaries = results.getMatchResults(); assertNotNull(summaries);//w w w .j a v a 2 s . com assertEquals(2, summaries.length); for (MatchDocumentSummary summary : summaries) { ExtractedResult extracted = summary.getExtracted(); if (Format.XML == summary.getFormat()) { // we don't test for kind because it isn't sent in this case assertEquals(1, extracted.size()); Document item1 = extracted.next().getAs(Document.class); assertEquals("This is so foo with a bar 71", item1.getFirstChild().getTextContent()); continue; } else if (Format.JSON == summary.getFormat()) { // we don't test for kind because it isn't sent in this case assertEquals(1, extracted.size()); for (ExtractedItem item : extracted) { String stringJsonItem = item.getAs(String.class); JsonNode nodeJsonItem = item.getAs(JsonNode.class); if (nodeJsonItem.has("says")) { assertEquals("{\"says\":\"woof\"}", stringJsonItem); continue; } fail("unexpected extracted item:" + stringJsonItem); } continue; } fail("unexpected search result:" + summary.getUri()); } }
From source file:org.universAAL.itests.IntegrationTest.java
/** * This method processes configured eclipse launch configuration. Extracts * list of bundles and sets run arguments as system properties. * * @return Returns list of resources.//from w w w .j av a2s.c o m */ private List<Resource> processEclipseLaunhFile() { List<Resource> bundleResources = null; try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new File(eclipseLaunchFile)); Node root = doc.getFirstChild(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); String name = n.getNodeName(); if (name != null && name.equals("listAttribute")) { NamedNodeMap attribs = n.getAttributes(); Node keyAttrib = attribs.getNamedItem("key"); String keyAttribStr = keyAttrib.getTextContent(); if (keyAttribStr.equals("org.ops4j.pax.cursor.runArguments")) { NodeList paxArgs = n.getChildNodes(); bundleResources = parsePaxArgs(paxArgs); } } if (name != null && name.equals("stringAttribute")) { NamedNodeMap attribs = n.getAttributes(); Node keyAttrib = attribs.getNamedItem("key"); String keyAttribStr = keyAttrib.getTextContent(); if (keyAttribStr.equals("org.eclipse.jdt.launching.VM_ARGUMENTS")) { String vmArgs = attribs.getNamedItem("value").getTextContent(); parseRunArgs(vmArgs); } } } return bundleResources; } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } }
From source file:com.github.zhanhb.ckfinder.connector.support.XmlConfigurationParser.java
/** * Initializes configuration from XML file. * * @param builder context builder/*w w w . j a v a2 s .c om*/ * @param basePathBuilder base url and path builder * @param resourceLoader resource loader to load xml configuration * @param basePath base path * @param xmlFilePath string representation of the xml file * @throws ConnectorException when error occurs * @throws IOException when IO Exception occurs. * @throws org.xml.sax.SAXException syntax error in xml file * @throws ParserConfigurationException no xml provider is avaliable */ private void init(DefaultCKFinderContext.Builder builder, ResourceLoader resourceLoader, String xmlFilePath, Path basePath, BasePathBuilder basePathBuilder) throws ConnectorException, IOException, ParserConfigurationException, SAXException { Resource resource = getFullConfigPath(resourceLoader, xmlFilePath); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc; try (InputStream stream = resource.getInputStream()) { doc = db.parse(stream); } doc.normalize(); License.Builder licenseBuilder = License.builder().name("").key(""); Node node = doc.getFirstChild(); ThumbnailProperties thumbnail = null; ImageProperties.Builder image = ImageProperties.builder(); if (node != null) { NodeList nodeList = node.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node childNode = nodeList.item(i); switch (childNode.getNodeName()) { case "enabled": builder.enabled(Boolean.parseBoolean(nullNodeToString(childNode))); break; case "licenseName": licenseBuilder.name(nullNodeToString(childNode)); break; case "licenseKey": licenseBuilder.key(nullNodeToString(childNode)); break; case "imgWidth": String width = nullNodeToString(childNode); width = width.replaceAll("\\D", ""); try { image.maxWidth(Integer.parseInt(width)); } catch (NumberFormatException e) { image.maxWidth(Constants.DEFAULT_IMG_WIDTH); } break; case "imgQuality": String quality = nullNodeToString(childNode); quality = quality.replaceAll("\\D", ""); image.quality(adjustQuality(quality)); break; case "imgHeight": String height = nullNodeToString(childNode); height = height.replaceAll("\\D", ""); try { image.maxHeight(Integer.parseInt(height)); } catch (NumberFormatException e) { image.maxHeight(Constants.DEFAULT_IMG_HEIGHT); } break; case "thumbs": thumbnail = createThumbs(childNode.getChildNodes(), basePath, basePathBuilder); break; case "accessControls": setACLs(builder, childNode.getChildNodes()); break; case "hideFolders": setHiddenFolders(builder, childNode.getChildNodes()); break; case "hideFiles": setHiddenFiles(builder, childNode.getChildNodes()); break; case "checkDoubleExtension": builder.checkDoubleFileExtensions(Boolean.parseBoolean(nullNodeToString(childNode))); break; case "disallowUnsafeCharacters": builder.disallowUnsafeCharacters(Boolean.parseBoolean(nullNodeToString(childNode))); break; case "forceASCII": builder.forceAscii(Boolean.parseBoolean(nullNodeToString(childNode))); break; case "checkSizeAfterScaling": builder.checkSizeAfterScaling(Boolean.parseBoolean(nullNodeToString(childNode))); break; case "htmlExtensions": String htmlExt = nullNodeToString(childNode); StringTokenizer scanner = new StringTokenizer(htmlExt, ","); while (scanner.hasMoreTokens()) { String val = scanner.nextToken(); if (val != null && !val.isEmpty()) { builder.htmlExtension(val.trim().toLowerCase()); } } break; case "secureImageUploads": builder.secureImageUploads(Boolean.parseBoolean(nullNodeToString(childNode))); break; case "uriEncoding": break; case "userRoleSessionVar": builder.userRoleName(nullNodeToString(childNode)); break; case "defaultResourceTypes": String value = nullNodeToString(childNode); StringTokenizer sc = new StringTokenizer(value, ","); while (sc.hasMoreTokens()) { builder.defaultResourceType(sc.nextToken()); } break; case "plugins": setPlugins(builder, childNode, resourceLoader); break; default: break; } } } builder.image(image.build()); builder.licenseFactory(new FixLicenseFactory(licenseBuilder.build())); setTypes(builder.thumbnail(thumbnail), doc, basePathBuilder, thumbnail); }
From source file:com.zimbra.common.util.QuotedTextUtil.java
/** * Using the DOM structure of the message content, traverse node by node and * if we find a node that is recognized as a separator, remove all * subsequent elements/*from w w w . j av a 2 s.co m*/ * * @param text the message content * @return original content if the quoted content was found otherwise the * complete message content */ private String getOriginalHtmlContent(String text) { ArrayList<Node> nodeList = new ArrayList<Node>(); Node previousNode = null, sepNode = null; LineType previousType = null; boolean done = false; DOMParser parser = new DOMParser(); Document document; Node htmlNode = null; try { parser.parse(new InputSource(new StringReader(text))); document = parser.getDocument(); htmlNode = document.getFirstChild(); flatten(htmlNode, nodeList); for (int i = 0; i < nodeList.size(); i++) { Node currentNode = nodeList.get(i); if (currentNode.getNodeType() == ELEMENT_NODE) { currentNode.normalize(); } String nodeName = currentNode.getNodeName() != null ? currentNode.getNodeName() : ""; String nodeValue = currentNode.getNodeValue() != null ? currentNode.getNodeValue() : ""; LineType type = checkNode(currentNode); /* * Check for a multi-element "wrote:" attribution (usually a * combo of #text and A nodes), for example: * * On Feb 28, 2014, at 3:42 PM, Joe Smith <<a * href="mailto:jsmith@zimbra.com" * target="_blank">jsmith@zimbra.com</a>> wrote: * * If the current node is a #text with a date or "On ...", find * #text nodes within the next ten nodes, concatenate them, and * check the result. */ if (type == LineType.UNKNOWN && nodeName.equals("#text") && (MATCHER_ORIG_DATE.reset(nodeValue).matches() || MATCHER_ORIG_INTRO.reset(nodeValue).matches())) { String value = nodeValue; for (int j = 1; j < 10; j++) { Node tempNode = nodeList.get(i + j); if (tempNode != null && tempNode.getNodeName() != null && tempNode.getNodeName().equals("#text")) { value += tempNode.getNodeValue(); if ("/:$/".matches(value)) { type = getLineType(value.trim()); if (type == LineType.SEP_STRONG) { i = i + j; break; } } } } } if (type != null) { // TODO: confirm if you need to add the nodes in a map and // maintain count as done is javascript // definite separator if (type == LineType.SEP_STRONG || type == LineType.WROTE_STRONG) { sepNode = currentNode; done = true; break; } // some sort of line followed by a header if (type == LineType.HEADER && previousType == LineType.LINE) { sepNode = previousNode; done = true; break; } previousNode = currentNode; previousType = type; } } if (sepNode != null) { prune(sepNode, true); } if (done) { String originalText = getHtml(document); return (originalText == null || originalText.isEmpty()) ? text : originalText; } } catch (SAXException | IOException e) { ZimbraLog.soap.warn("Exception while removing quoted text from html message", e); } return text; }
From source file:com.l2jfree.gameserver.datatables.AugmentationData.java
@SuppressWarnings("unchecked") private final void load() { // Load the skillmap // Note: the skillmap data is only used when generating new augmentations // the client expects a different id in order to display the skill in the // items description... try {/*from w ww.j av a 2 s.com*/ int badAugmantData = 0; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setIgnoringComments(true); File file = new File(Config.DATAPACK_ROOT + "/data/stats/augmentation/augmentation_skillmap.xml"); if (!file.exists()) { _log.warn("The augmentation skillmap file is missing."); return; } Document doc = factory.newDocumentBuilder().parse(file); for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { if ("list".equalsIgnoreCase(n.getNodeName())) { for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) { if ("augmentation".equalsIgnoreCase(d.getNodeName())) { NamedNodeMap attrs = d.getAttributes(); int skillId = 0, augmentationId = Integer.parseInt(attrs.getNamedItem("id").getNodeValue()); int skillLvL = 0; String type = "blue"; for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) { if ("skillId".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); skillId = Integer.parseInt(attrs.getNamedItem("val").getNodeValue()); } else if ("skillLevel".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); skillLvL = Integer.parseInt(attrs.getNamedItem("val").getNodeValue()); } else if ("type".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); type = attrs.getNamedItem("val").getNodeValue(); } } if (skillId == 0) { _log.warn("Bad skillId in augmentation_skillmap.xml in the augmentationId:" + augmentationId); badAugmantData++; continue; } else if (skillLvL == 0) { _log.warn("Bad skillLevel in augmentation_skillmap.xml in the augmentationId:" + augmentationId); badAugmantData++; continue; } int k = (augmentationId - BLUE_START) / SKILLS_BLOCKSIZE; if (type.equalsIgnoreCase("blue")) ((ArrayList<Integer>) _blueSkills[k]).add(augmentationId); else if (type.equalsIgnoreCase("purple")) ((ArrayList<Integer>) _purpleSkills[k]).add(augmentationId); else ((ArrayList<Integer>) _redSkills[k]).add(augmentationId); _allSkills.put(augmentationId, new augmentationSkill(skillId, skillLvL)); } } } } if (badAugmantData != 0) _log.info("AugmentationData: " + badAugmantData + " bad skill(s) were skipped."); } catch (Exception e) { _log.error("Error parsing augmentation_skillmap.xml.", e); return; } // Load the stats from xml for (int i = 1; i < 5; i++) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); File file = new File( Config.DATAPACK_ROOT + "/data/stats/augmentation/augmentation_stats" + i + ".xml"); if (!file.exists()) { _log.warn("The augmentation stat data file " + i + " is missing."); return; } Document doc = factory.newDocumentBuilder().parse(file); for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { if ("list".equalsIgnoreCase(n.getNodeName())) { for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) { if ("stat".equalsIgnoreCase(d.getNodeName())) { NamedNodeMap attrs = d.getAttributes(); String statName = attrs.getNamedItem("name").getNodeValue(); float soloValues[] = null, combinedValues[] = null; for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) { if ("table".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); String tableName = attrs.getNamedItem("name").getNodeValue(); StringTokenizer data = new StringTokenizer( cd.getFirstChild().getNodeValue()); FastList<Float> array = new FastList<Float>(); while (data.hasMoreTokens()) array.add(Float.parseFloat(data.nextToken())); if (tableName.equalsIgnoreCase("#soloValues")) { soloValues = new float[array.size()]; int x = 0; for (float value : array) soloValues[x++] = value; } else { combinedValues = new float[array.size()]; int x = 0; for (float value : array) combinedValues[x++] = value; } } } // store this stat ((ArrayList<augmentationStat>) _augStats[(i - 1)]).add(new augmentationStat( Stats.valueOfXml(statName), soloValues, combinedValues)); } } } } } catch (Exception e) { _log.error("Error parsing augmentation_stats" + i + ".xml.", e); return; } try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); File file = new File( Config.DATAPACK_ROOT + "/data/stats/augmentation/augmentation_jewel_stats" + i + ".xml"); if (!file.exists()) { _log.warn("The jewel augmentation stat data file " + i + " is missing."); return; } Document doc = factory.newDocumentBuilder().parse(file); for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { if ("list".equalsIgnoreCase(n.getNodeName())) { for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) { if ("stat".equalsIgnoreCase(d.getNodeName())) { NamedNodeMap attrs = d.getAttributes(); String statName = attrs.getNamedItem("name").getNodeValue(); float soloValues[] = null, combinedValues[] = null; for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) { if ("table".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); String tableName = attrs.getNamedItem("name").getNodeValue(); StringTokenizer data = new StringTokenizer( cd.getFirstChild().getNodeValue()); FastList<Float> array = new FastList<Float>(); while (data.hasMoreTokens()) array.add(Float.parseFloat(data.nextToken())); if (tableName.equalsIgnoreCase("#soloValues")) { soloValues = new float[array.size()]; int x = 0; for (float value : array) soloValues[x++] = value; } else { combinedValues = new float[array.size()]; int x = 0; for (float value : array) combinedValues[x++] = value; } } } // store this stat ((ArrayList<augmentationStat>) _augAccStats[(i - 1)]).add(new augmentationStat( Stats.valueOfXml(statName), soloValues, combinedValues)); } } } } } catch (Exception e) { _log.error("Error parsing jewel augmentation_stats" + i + ".xml.", e); return; } } }
From source file:lineage2.gameserver.Config.java
/** * Method loadGMAccess.// w ww .jav a 2 s .c om * @param file File */ public static void loadGMAccess(File file) { try { Field fld; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); Document doc = factory.newDocumentBuilder().parse(file); for (Node z = doc.getFirstChild(); z != null; z = z.getNextSibling()) { for (Node n = z.getFirstChild(); n != null; n = n.getNextSibling()) { if (!n.getNodeName().equalsIgnoreCase("char")) { continue; } PlayerAccess pa = new PlayerAccess(); for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) { Class<?> cls = pa.getClass(); String node = d.getNodeName(); if (node.equalsIgnoreCase("#text")) { continue; } try { fld = cls.getField(node); } catch (NoSuchFieldException e) { _log.info("Not found desclarate ACCESS name: " + node + " in XML Player access Object"); continue; } if (fld.getType().getName().equalsIgnoreCase("boolean")) { fld.setBoolean(pa, Boolean.parseBoolean(d.getAttributes().getNamedItem("set").getNodeValue())); } else if (fld.getType().getName().equalsIgnoreCase("int")) { fld.setInt(pa, Integer.valueOf(d.getAttributes().getNamedItem("set").getNodeValue())); } } gmlist.put(pa.PlayerID, pa); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java
/** * This method processes the SOAP response from the IdP, and converts it * for presenting it back to the WSP that requested a delegated SAML * assertion.//from www. j a va 2 s .co m * * @param samlSession SAML session * @param authnState * @return true, if successful */ private boolean processSOAPResponse(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) { this.logger.debug("Step 5 of 5: Processing SOAP response"); try { String expression = "/soap:Envelope/soap:Header/ecp:Response"; InputStream is = new ByteArrayInputStream(authnState.getSoapResponse().getBytes()); InputSource source = new InputSource(is); DOMParser parser = new DOMParser(); parser.setFeature("http://xml.org/sax/features/namespaces", true); parser.parse(source); Document doc = parser.getDocument(); Node node = EXPRESSION_POOL.evaluate(expression, doc, XPathConstants.NODE); if (node != null) { String responseConsumerURL = node.getAttributes().getNamedItem("AssertionConsumerServiceURL") .getTextContent(); logger.debug("Found {} node found in SOAP response.", expression); if (responseConsumerURL != null && responseConsumerURL.equals(authnState.getResponseConsumerURL())) { logger.debug("responseConsumerURL {} matches {}", responseConsumerURL, authnState.getResponseConsumerURL()); // Retrieve and save the SOAP prefix used String soapPrefix = node.getParentNode().getPrefix(); Element ecpResponse = (Element) node; Element soapHeader = (Element) ecpResponse.getParentNode(); removeAllChildren(soapHeader); // Now on to the PAOS Response Element paosResponse = doc.createElementNS("urn:liberty:paos:2003-08", "paos:Response"); paosResponse.setAttribute(soapPrefix + ":mustUnderstand", "1"); paosResponse.setAttribute(soapPrefix + ":actor", "http://schemas.xmlsoap.org/soap/actor/next"); // messageID is optional if (authnState.getPaosMessageID() != null) paosResponse.setAttribute("refToMessageID", authnState.getPaosMessageID()); soapHeader.appendChild(paosResponse); if (authnState.getRelayStateElement() != null) { Node relayState = doc.importNode(authnState.getRelayStateElement(), true); soapHeader.appendChild(relayState); } // Store the modified SOAP Request in the SAML Session String modifiedSOAPResponse = writeDomToString(doc); authnState.setModifiedSOAPResponse(modifiedSOAPResponse); return true; } logger.debug("responseConsumerURL {} does not match {}", responseConsumerURL, authnState.getResponseConsumerURL()); Document soapFaultMessage = createSOAPFaultDocument( "AssertionConsumerServiceURL attribute missing or not matching the expected value."); Element soapHeader = (Element) soapFaultMessage.getFirstChild().getFirstChild(); // Now on to the PAOS Response Element paosResponse = soapFaultMessage.createElementNS("urn:liberty:paos:2003-08", "paos:Response"); paosResponse.setAttribute(SOAP_PREFIX + ":mustUnderstand", "1"); paosResponse.setAttribute(SOAP_PREFIX + ":actor", "http://schemas.xmlsoap.org/soap/actor/next"); // messageID is optional if (authnState.getPaosMessageID() != null) { paosResponse.setAttribute("refToMessageID", authnState.getPaosMessageID()); } soapHeader.appendChild(paosResponse); if (authnState.getRelayStateElement() != null) { Node relayState = soapFaultMessage.importNode(authnState.getRelayStateElement(), true); soapHeader.appendChild(relayState); } // Store the SOAP Fault in the SAML Session String modifiedSOAPResponse = writeDomToString(soapFaultMessage); authnState.setModifiedSOAPResponse(modifiedSOAPResponse); sendSOAPFault(samlSession, authnState); return false; } // There was no response for the ECP. Look for and propagate an error. String errorMessage = getSOAPFaultAsString(is); logger.warn("No {} node found in SOAP response. Error: {}", expression, errorMessage); if (errorMessage != null) { throw new DelegatedAuthenticationRuntimeException(errorMessage); } return false; } catch (XPathExpressionException ex) { logger.error("XPath programming error.", ex); throw new DelegatedAuthenticationRuntimeException("XPath programming error.", ex); } catch (SAXNotRecognizedException ex) { logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex); throw new DelegatedAuthenticationRuntimeException("XPath programming error.", ex); } catch (SAXNotSupportedException ex) { logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex); throw new DelegatedAuthenticationRuntimeException( "Exception caught when trying to process the SOAP esponse from the IdP.", ex); } catch (SAXException ex) { logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex); throw new DelegatedAuthenticationRuntimeException( "Exception caught when trying to process the SOAP esponse from the IdP.", ex); } catch (DOMException ex) { logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex); throw new DelegatedAuthenticationRuntimeException( "Exception caught when trying to process the SOAP esponse from the IdP.", ex); } catch (IOException ex) { logger.error( "This exception should not ever really occur, as the only I/O this method performs is on a ByteArrayInputStream.", ex); throw new DelegatedAuthenticationRuntimeException( "This exception should not ever really occur, as the only I/O this method performs is on a ByteArrayInputStream.", ex); } catch (SOAPException ex) { logger.error("Error processing a SOAP message.", ex); throw new DelegatedAuthenticationRuntimeException("Error processing a SOAP message.", ex); } }
From source file:com.l2jfree.gameserver.model.entity.Instance.java
public void loadInstanceTemplate(String filename) { Document doc = null; File xml = new File(Config.DATAPACK_ROOT, "data/instances/" + filename); try {// w w w . j a va2s.c om DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); // DTD isn't used factory.setIgnoringComments(true); // Such validation will not find element 'instance' //SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); //factory.setSchema(sf.newSchema(new File(Config.DATAPACK_ROOT, "data/templates/instances.xsd"))); doc = factory.newDocumentBuilder().parse(xml); for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { if ("instance".equalsIgnoreCase(n.getNodeName())) { parseInstance(n); } } } catch (IOException e) { _log.warn("Instance: can not find " + xml.getAbsolutePath() + " !", e); } catch (Exception e) { _log.warn("Instance: error while loading " + xml.getAbsolutePath() + " !", e); } }