From d1d206293ea012fd37c891673a8b5e74ad40a0cf Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 22 Jun 2018 15:20:53 +0200 Subject: some more pvp2 updates --- .../commons/api/data/AuthProzessDataConstants.java | 22 +- .../commons/api/data/IAuthenticationSession.java | 106 +- .../moa/id/commons/api/data/IIdentityLink.java | 175 --- .../java/at/gv/egovernment/moa/util/DOMUtils.java | 1263 -------------------- .../gv/egovernment/moa/util/MOADefaultHandler.java | 6 +- .../egovernment/moa/util/NodeIteratorAdapter.java | 111 -- .../gv/egovernment/moa/util/NodeListAdapter.java | 68 -- .../at/gv/egovernment/moa/util/XPathException.java | 86 -- .../at/gv/egovernment/moa/util/XPathUtils.java | 557 --------- 9 files changed, 11 insertions(+), 2383 deletions(-) delete mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/IIdentityLink.java delete mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DOMUtils.java delete mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeIteratorAdapter.java delete mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeListAdapter.java delete mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathException.java delete mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathUtils.java (limited to 'id/server/moa-id-commons/src/main/java') diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/AuthProzessDataConstants.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/AuthProzessDataConstants.java index 439138645..31a0573b6 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/AuthProzessDataConstants.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/AuthProzessDataConstants.java @@ -22,39 +22,25 @@ */ package at.gv.egovernment.moa.id.commons.api.data; +import at.gv.egiz.eaaf.core.api.idp.EAAFAuthProcessDataConstants; + /** * @author tlenz * */ -public interface AuthProzessDataConstants { - - public static final String GENERIC_PREFIX = "generic_"; - +public interface AuthProzessDataConstants extends EAAFAuthProcessDataConstants { - public static final String FLAG_IS_FOREIGNER = "direct_flagIsForeigner"; - public static final String FLAG_USE_MANDATE = "direct_flagUseMandate"; - public static final String FLAG_IS_ORGANWALTER = "direct_flagOrganwalter"; - public static final String FLAG_IS_AUTHENTICATED = "direct_flagIsAuth"; public static final String FLAG_SAMLATTRIBUTEGEBEORWBPK = "direct_SAMLAttributeGebeORwbpk"; - - public static final String VALUE_ISSUEINSTANT = "direct_issueInstant"; - public static final String VALUE_SIGNER_CERT = "direct_signerCert"; public static final String VALUE_IDENTITYLINK = "direct_idl"; public static final String VALUE_BKUURL = "direct_bkuUrl"; public static final String VALUE_AUTHBLOCK = "direct_authBlock"; public static final String VALUE_AUTNBLOCKTOKKEN = "direct_authblocktokken"; - public static final String VALUE_QAALEVEL = "direct_qaaLevel"; - public static final String VALUE_VERIFYSIGRESP = "direct_verifySigResp"; - + public static final String VALUE_VERIFYSIGRESP = "direct_verifySigResp"; public static final String VALUE_MISSESSIONID = "direct_MIS_SessionId"; public static final String VALUE_MISREFVALUE = "direct_MIS_RefValue"; - public static final String VALUE_MISMANDATE = "direct_MIS_Mandate"; - - - @Deprecated public static final String VALUE_EXTENTEDSAMLATTRAUTH = "direct_extSamlAttrAuth"; diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/IAuthenticationSession.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/IAuthenticationSession.java index 8cb2b31bc..1d54af7c8 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/IAuthenticationSession.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/IAuthenticationSession.java @@ -22,22 +22,17 @@ */ package at.gv.egovernment.moa.id.commons.api.data; -import java.util.Date; import java.util.List; import java.util.Map; -import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; +import at.gv.egiz.eaaf.core.api.idp.auth.data.IAuthProcessDataContainer; import iaik.x509.X509Certificate; /** * @author tlenz * */ -public interface IAuthenticationSession { - - boolean isAuthenticated(); - - void setAuthenticated(boolean authenticated); +public interface IAuthenticationSession extends IAuthProcessDataContainer { X509Certificate getSignerCertificate(); @@ -45,13 +40,6 @@ public interface IAuthenticationSession { void setSignerCertificate(X509Certificate signerCertificate); - /** - * Returns the identityLink. - * - * @return IdentityLink - */ - IIdentityLink getIdentityLink(); - /** * Returns the sessionID. * @@ -59,14 +47,7 @@ public interface IAuthenticationSession { */ String getSSOSessionID(); - /** - * Sets the identityLink. - * - * @param identityLink - * The identityLink to set - */ - void setIdentityLink(IIdentityLink identityLink); - + /** * Sets the sessionID. * @@ -158,20 +139,6 @@ public interface IAuthenticationSession { */ void setSAMLAttributeGebeORwbpk(boolean samlAttributeGebeORwbpk); - /** - * Returns the issuing time of the AUTH-Block SAML assertion. - * - * @return The issuing time of the AUTH-Block SAML assertion. - */ - String getIssueInstant(); - - /** - * Sets the issuing time of the AUTH-Block SAML assertion. - * - * @param issueInstant - * The issueInstant to set. - */ - void setIssueInstant(String issueInstant); /** * @@ -180,13 +147,6 @@ public interface IAuthenticationSession { */ void setUseMandate(String useMandate); - void setUseMandates(boolean useMandates); - - /** - * @return - */ - boolean isMandateUsed(); - /** * * @param misSessionID @@ -212,9 +172,6 @@ public interface IAuthenticationSession { */ void setMandateReferenceValue(String mandateReferenceValue); - boolean isForeigner(); - - void setForeigner(boolean isForeigner); IVerifiyXMLSignatureResponse getXMLVerifySignatureResponse(); @@ -224,17 +181,6 @@ public interface IAuthenticationSession { void setMISMandate(IMISMandate mandate); - /** - * @return the isOW - */ - boolean isOW(); - - /** - * @param isOW - * the isOW to set - */ - void setOW(boolean isOW); - /** * @return the authBlockTokken */ @@ -246,52 +192,6 @@ public interface IAuthenticationSession { */ void setAuthBlockTokken(String authBlockTokken); - /** - * eIDAS QAA level - * - * @return the qAALevel - */ - String getQAALevel(); - - /** - * set QAA level in eIDAS form - * - * @param qAALevel the qAALevel to set - */ - void setQAALevel(String qAALevel); - - /** - * @return the sessionCreated - */ - Date getSessionCreated(); - - Map getGenericSessionDataStorage(); - - /** - * Returns a generic session-data object with is stored with a specific identifier - * - * @param key The specific identifier of the session-data object - * @return The session-data object or null if no data is found with this key - */ - Object getGenericDataFromSession(String key); - - /** - * Returns a generic session-data object with is stored with a specific identifier - * - * @param key The specific identifier of the session-data object - * @param clazz The class type which is stored with this key - * @return The session-data object or null if no data is found with this key - */ - T getGenericDataFromSession(String key, Class clazz); - - /** - * Store a generic data-object to session with a specific identifier - * - * @param key Identifier for this data-object - * @param object Generic data-object which should be stored. This data-object had to be implement the 'java.io.Serializable' interface - * @throws SessionDataStorageException Error message if the data-object can not stored to generic session-data storage - */ - void setGenericDataToSession(String key, Object object) throws SessionDataStorageException; /** * Generates a Key / Value representation from Authenticated session diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/IIdentityLink.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/IIdentityLink.java deleted file mode 100644 index 3a0ccd7c9..000000000 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/IIdentityLink.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.commons.api.data; - -import java.io.IOException; -import java.security.PublicKey; - -import javax.xml.transform.TransformerException; - -import org.w3c.dom.Element; - -/** - * @author tlenz - * - */ -public interface IIdentityLink { - - /** - * Returns the dateOfBirth. - * @return Calendar - */ - String getDateOfBirth(); - - /** - * Returns the familyName. - * @return String - */ - String getFamilyName(); - - /** - * Returns the givenName. - * @return String - */ - String getGivenName(); - - /** - * Returns the name. - * @return The name. - */ - String getName(); - - /** - * Returns the identificationValue. - * "identificationValue" is the translation of "Stammzahl". - * @return String - */ - String getIdentificationValue(); - - /** - * Returns the identificationType. - * "identificationType" type of the identificationValue in the IdentityLink. - * @return String - */ - String getIdentificationType(); - - /** - * Sets the dateOfBirth. - * @param dateOfBirth The dateOfBirth to set - */ - void setDateOfBirth(String dateOfBirth); - - /** - * Sets the familyName. - * @param familyName The familyName to set - */ - void setFamilyName(String familyName); - - /** - * Sets the givenName. - * @param givenName The givenName to set - */ - void setGivenName(String givenName); - - /** - * Sets the identificationValue. - * "identificationValue" is the translation of "Stammzahl". - * @param identificationValue The identificationValue to set - */ - void setIdentificationValue(String identificationValue); - - /** - * Sets the Type of the identificationValue. - * @param identificationType The type of identificationValue to set - */ - void setIdentificationType(String identificationType); - - /** - * Returns the samlAssertion. - * @return Element - */ - Element getSamlAssertion(); - - /** - * Returns the samlAssertion. - * @return Element - */ - String getSerializedSamlAssertion(); - - /** - * Sets the samlAssertion and the serializedSamlAssertion. - * @param samlAssertion The samlAssertion to set - */ - void setSamlAssertion(Element samlAssertion) throws TransformerException, IOException; - - /** - * Returns the dsigReferenceTransforms. - * @return Element[] - */ - Element[] getDsigReferenceTransforms(); - - /** - * Sets the dsigReferenceTransforms. - * @param dsigReferenceTransforms The dsigReferenceTransforms to set - */ - void setDsigReferenceTransforms(Element[] dsigReferenceTransforms); - - /** - * Returns the publicKey. - * @return PublicKey[] - */ - PublicKey[] getPublicKey(); - - /** - * Sets the publicKey. - * @param publicKey The publicKey to set - */ - void setPublicKey(PublicKey[] publicKey); - - /** - * Returns the prPerson. - * @return Element - */ - Element getPrPerson(); - - /** - * Sets the prPerson. - * @param prPerson The prPerson to set - */ - void setPrPerson(Element prPerson); - - /** - * Returns the issuing time of the identity link SAML assertion. - * - * @return The issuing time of the identity link SAML assertion. - */ - String getIssueInstant(); - - /** - * Sets the issuing time of the identity link SAML assertion. - * - * @param issueInstant The issueInstant to set. - */ - void setIssueInstant(String issueInstant); - -} \ No newline at end of file diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DOMUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DOMUtils.java deleted file mode 100644 index 62a168ac8..000000000 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DOMUtils.java +++ /dev/null @@ -1,1263 +0,0 @@ -/* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - - -package at.gv.egovernment.moa.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.Vector; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.apache.commons.io.IOUtils; -import org.apache.xerces.parsers.DOMParser; -import org.apache.xerces.parsers.SAXParser; -import org.apache.xerces.parsers.XMLGrammarPreparser; -import org.apache.xerces.util.SymbolTable; -import org.apache.xerces.util.XMLGrammarPoolImpl; -import org.apache.xerces.xni.grammars.XMLGrammarDescription; -import org.apache.xerces.xni.grammars.XMLGrammarPool; -import org.apache.xerces.xni.parser.XMLInputSource; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import at.gv.egovernment.moa.logging.Logger; - -/** - * Various utility functions for handling XML DOM trees. - * - * The parsing methods in this class make use of some features internal to the - * Xerces DOM parser, mainly for performance reasons. As soon as JAXP - * (currently at version 1.2) is better at schema handling, it should be used as - * the parser interface. - * - * @author Patrick Peck - * @version $Id$ - */ -public class DOMUtils { - - /** Feature URI for namespace aware parsing. */ - private static final String NAMESPACES_FEATURE = - "http://xml.org/sax/features/namespaces"; - /** Feature URI for validating parsing. */ - private static final String VALIDATION_FEATURE = - "http://xml.org/sax/features/validation"; - /** Feature URI for schema validating parsing. */ - private static final String SCHEMA_VALIDATION_FEATURE = - "http://apache.org/xml/features/validation/schema"; - /** Feature URI for normalization of element/attribute values. */ - private static final String NORMALIZED_VALUE_FEATURE = - "http://apache.org/xml/features/validation/schema/normalized-value"; - /** Feature URI for parsing ignorable whitespace. */ - private static final String INCLUDE_IGNORABLE_WHITESPACE_FEATURE = - "http://apache.org/xml/features/dom/include-ignorable-whitespace"; - /** Feature URI for creating EntityReference nodes in the DOM tree. */ - private static final String CREATE_ENTITY_REF_NODES_FEATURE = - "http://apache.org/xml/features/dom/create-entity-ref-nodes"; - /** Property URI for providing external schema locations. */ - private static final String EXTERNAL_SCHEMA_LOCATION_PROPERTY = - "http://apache.org/xml/properties/schema/external-schemaLocation"; - /** Property URI for providing the external schema location for elements - * without a namespace. */ - private static final String EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY = - "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation"; - - private static final String EXTERNAL_GENERAL_ENTITIES_FEATURE = - "http://xml.org/sax/features/external-general-entities"; - - private static final String EXTERNAL_PARAMETER_ENTITIES_FEATURE = - "http://xml.org/sax/features/external-parameter-entities"; - - public static final String DISALLOW_DOCTYPE_FEATURE = - "http://apache.org/xml/features/disallow-doctype-decl"; - - - - /** Property URI for the Xerces grammar pool. */ - private static final String GRAMMAR_POOL = - org.apache.xerces.impl.Constants.XERCES_PROPERTY_PREFIX - + org.apache.xerces.impl.Constants.XMLGRAMMAR_POOL_PROPERTY; - /** A prime number for initializing the symbol table. */ - private static final int BIG_PRIME = 2039; - /** Symbol table for the grammar pool. */ - private static SymbolTable symbolTable = new SymbolTable(BIG_PRIME); - /** Xerces schema grammar pool. */ - private static XMLGrammarPool grammarPool = new XMLGrammarPoolImpl(); - /** Set holding the NamespaceURIs of the grammarPool, to prevent multiple - * entries of same grammars to the pool */ - private static Set grammarNamespaces; - - static { - grammarPool.lockPool(); - grammarNamespaces = new HashSet(); - } - - /** - * Preparse a schema and add it to the schema pool. - * The method only adds the schema to the pool if a schema having the same - * systemId (namespace URI) is not already present in the pool. - * - * @param inputStream An InputStream providing the contents of - * the schema. - * @param systemId The systemId (namespace URI) to use for the schema. - * @throws IOException An error occurred reading the schema. - */ - public static void addSchemaToPool(InputStream inputStream, String systemId) - throws IOException { - XMLGrammarPreparser preparser; - - if (!grammarNamespaces.contains(systemId)) { - - grammarNamespaces.add(systemId); - - // unlock the pool so that we can add another grammar - grammarPool.unlockPool(); - - // prepare the preparser - preparser = new XMLGrammarPreparser(symbolTable); - preparser.registerPreparser(XMLGrammarDescription.XML_SCHEMA, null); - preparser.setProperty(GRAMMAR_POOL, grammarPool); - preparser.setFeature(NAMESPACES_FEATURE, true); - preparser.setFeature(VALIDATION_FEATURE, true); - - // add the grammar to the pool - preparser.preparseGrammar( - XMLGrammarDescription.XML_SCHEMA, - new XMLInputSource(null, systemId, null, inputStream, null)); - - // lock the pool again so that schemas are not added automatically - grammarPool.lockPool(); - } - } - - /** - * Parse an XML document from an InputStream. - * - * @param inputStream The InputStream containing the XML - * document. - * @param validating If true, parse validating. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @param entityResolver An EntityResolver to resolve external - * entities (schemas and DTDs). If null, it will not be set. - * @param errorHandler An ErrorHandler to decide what to do - * with parsing errors. If null, it will not be set. - * @return The parsed XML document as a DOM tree. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Document parseDocument( - InputStream inputStream, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation, - EntityResolver entityResolver, - ErrorHandler errorHandler, - Map parserFeatures) - throws SAXException, IOException, ParserConfigurationException { - - DOMParser parser; - -// class MyEntityResolver implements EntityResolver { -// -// public InputSource resolveEntity(String publicId, String systemId) -// throws SAXException, IOException { -// return new InputSource(new ByteArrayInputStream(new byte[0])); -// } -// } - - - //if Debug is enabled make a copy of inputStream to enable debug output in case of SAXException - byte buffer [] = null; - ByteArrayInputStream baStream = null; - if(true == Logger.isDebugEnabled()) { - buffer = IOUtils.toByteArray(inputStream); - baStream = new ByteArrayInputStream(buffer); - - } - - - - // create the DOM parser - if (symbolTable != null) { - parser = new DOMParser(symbolTable, grammarPool); - } else { - parser = new DOMParser(); - } - - // set parser features and properties - try { - parser.setFeature(NAMESPACES_FEATURE, true); - parser.setFeature(VALIDATION_FEATURE, validating); - parser.setFeature(SCHEMA_VALIDATION_FEATURE, validating); - parser.setFeature(NORMALIZED_VALUE_FEATURE, false); - parser.setFeature(INCLUDE_IGNORABLE_WHITESPACE_FEATURE, true); - parser.setFeature(CREATE_ENTITY_REF_NODES_FEATURE, false); - parser.setFeature(EXTERNAL_GENERAL_ENTITIES_FEATURE, false); - parser.setFeature(EXTERNAL_PARAMETER_ENTITIES_FEATURE, false); - - //set external added parser features - if (parserFeatures != null) { - for (Entry el : parserFeatures.entrySet()) { - String key = el.getKey(); - if (MiscUtil.isNotEmpty(key)) { - Object value = el.getValue(); - if (value != null && value instanceof Boolean) - parser.setFeature(key, (boolean)value); - - else - Logger.warn("This XML parser only allows features with 'boolean' values"); - - } else - Logger.warn("Can not set 'null' feature to XML parser"); - } - } - - //fix XXE problem - //parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - - - if (validating) { - if (externalSchemaLocations != null) { - parser.setProperty( - EXTERNAL_SCHEMA_LOCATION_PROPERTY, - externalSchemaLocations); - } - if (externalNoNamespaceSchemaLocation != null) { - parser.setProperty( - EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, - externalNoNamespaceSchemaLocation); - } - } - - // set entity resolver and error handler - if (entityResolver != null) { - parser.setEntityResolver(entityResolver); - } - if (errorHandler != null) { - parser.setErrorHandler(errorHandler); - } - - // parse the document and return it - // if debug is enabled: use copy of strem (baStream) else use orig stream - if(null != baStream) - parser.parse(new InputSource(baStream)); - else - parser.parse(new InputSource(inputStream)); - } catch(SAXException e) { - if(true == Logger.isDebugEnabled() && null != buffer) { - String xmlContent = new String(buffer); - Logger.debug("SAXException in:\n" + xmlContent); - } - throw(e); - } - - return parser.getDocument(); - } - - /** - * Parse an XML document from an InputStream. - * - * @param inputStream The InputStream containing the XML - * document. - * @param validating If true, parse validating. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @param entityResolver An EntityResolver to resolve external - * entities (schemas and DTDs). If null, it will not be set. - * @param errorHandler An ErrorHandler to decide what to do - * with parsing errors. If null, it will not be set. - * @return The parsed XML document as a DOM tree. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Document parseDocumentSimple(InputStream inputStream) - throws SAXException, IOException, ParserConfigurationException { - - DOMParser parser; - - parser = new DOMParser(); - // set parser features and properties - parser.setFeature(NAMESPACES_FEATURE, true); - parser.setFeature(VALIDATION_FEATURE, false); - parser.setFeature(SCHEMA_VALIDATION_FEATURE, false); - parser.setFeature(NORMALIZED_VALUE_FEATURE, false); - parser.setFeature(INCLUDE_IGNORABLE_WHITESPACE_FEATURE, true); - parser.setFeature(CREATE_ENTITY_REF_NODES_FEATURE, false); - - parser.parse(new InputSource(inputStream)); - - return parser.getDocument(); - } - - - /** - * Parse an XML document from an InputStream. - * - * It uses a MOAEntityResolver as the EntityResolver - * and a MOAErrorHandler as the ErrorHandler. - * - * @param inputStream The InputStream containing the XML - * document. - * @param validating If true, parse validating. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @param parserFeatures - * @return The parsed XML document as a DOM tree. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Document parseDocument( - InputStream inputStream, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation, Map parserFeatures) - throws SAXException, IOException, ParserConfigurationException { - - - - return parseDocument( - inputStream, - validating, - externalSchemaLocations, - externalNoNamespaceSchemaLocation, - new MOAEntityResolver(), - new MOAErrorHandler(), - parserFeatures); - } - - /** - * Parse an XML document from a String. - * - * It uses a MOAEntityResolver as the EntityResolver - * and a MOAErrorHandler as the ErrorHandler. - * - * @param xmlString The String containing the XML document. - * @param encoding The encoding of the XML document. - * @param validating If true, parse validating. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @return The parsed XML document as a DOM tree. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Document parseDocument( - String xmlString, - String encoding, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation, - Map parserFeatures) - throws SAXException, IOException, ParserConfigurationException { - - InputStream in = new ByteArrayInputStream(xmlString.getBytes(encoding)); - return parseDocument( - in, - validating, - externalSchemaLocations, - externalNoNamespaceSchemaLocation, - parserFeatures); - } - - - /** - * Parse an XML document from a String. - * - * It uses a MOAEntityResolver as the EntityResolver - * and a MOAErrorHandler as the ErrorHandler. - * - * @param xmlString The String containing the XML document. - * @param encoding The encoding of the XML document. - * @param validating If true, parse validating. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @return The parsed XML document as a DOM tree. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Document parseDocument( - String xmlString, - String encoding, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation) - throws SAXException, IOException, ParserConfigurationException { - - InputStream in = new ByteArrayInputStream(xmlString.getBytes(encoding)); - return parseDocument( - in, - validating, - externalSchemaLocations, - externalNoNamespaceSchemaLocation, - null); - } - - /** - * Parse an UTF-8 encoded XML document from a String. - * - * @param xmlString The String containing the XML document. - * @param validating If true, parse validating. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @return The parsed XML document as a DOM tree. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Document parseDocument( - String xmlString, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation) - throws SAXException, IOException, ParserConfigurationException { - - return parseDocument( - xmlString, - "UTF-8", - validating, - externalSchemaLocations, - externalNoNamespaceSchemaLocation); - } - - /** - * A convenience method to parse an XML document validating. - * - * @param inputStream The InputStream containing the XML - * document. - * @return The root element of the parsed XML document. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Element parseXmlValidating(InputStream inputStream) - throws ParserConfigurationException, SAXException, IOException { - return DOMUtils - .parseDocument(inputStream, true, Constants.ALL_SCHEMA_LOCATIONS, null, null) - .getDocumentElement(); - } - - /** - * A convenience method to parse an XML document validating. - * - * @param inputStream The InputStream containing the XML - * document. - * @param parserFeatures Set additional features to XML parser - * @return The root element of the parsed XML document. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Element parseXmlValidating(InputStream inputStream, Map parserFeatures) - throws ParserConfigurationException, SAXException, IOException { - return DOMUtils - .parseDocument(inputStream, true, Constants.ALL_SCHEMA_LOCATIONS, null, parserFeatures) - .getDocumentElement(); - } - - /** - * A convenience method to parse an XML document non validating. - * This method disallow DocType declarations - * - * @param inputStream The InputStream containing the XML - * document. - * @return The root element of the parsed XML document. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Element parseXmlNonValidating(InputStream inputStream) - throws ParserConfigurationException, SAXException, IOException { - return DOMUtils - .parseDocument(inputStream, false, Constants.ALL_SCHEMA_LOCATIONS, null, - Collections.unmodifiableMap(new HashMap() { - private static final long serialVersionUID = 1L; - { - put(DOMUtils.DISALLOW_DOCTYPE_FEATURE, true); - - } - })).getDocumentElement(); - } - - /** - * Schema validate a given DOM element. - * - * @param element The element to validate. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @return true, if the element validates against - * the schemas declared in it. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document from its - * serialized representation. - * @throws ParserConfigurationException An error occurred configuring the XML - * @throws TransformerException An error occurred serializing the element. - */ - public static boolean validateElement( - Element element, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation) - throws - ParserConfigurationException, - IOException, - SAXException, - TransformerException { - - byte[] docBytes; - SAXParser parser; - - // create the SAX parser - if (symbolTable != null) { - parser = new SAXParser(symbolTable, grammarPool); - } else { - parser = new SAXParser(); - } - - // serialize the document - docBytes = serializeNode(element, "UTF-8"); - - // set up parser features and attributes - parser.setFeature(NAMESPACES_FEATURE, true); - parser.setFeature(VALIDATION_FEATURE, true); - parser.setFeature(SCHEMA_VALIDATION_FEATURE, true); - parser.setFeature(EXTERNAL_GENERAL_ENTITIES_FEATURE, false); - parser.setFeature(DISALLOW_DOCTYPE_FEATURE, true); - - - if (externalSchemaLocations != null) { - parser.setProperty( - EXTERNAL_SCHEMA_LOCATION_PROPERTY, - externalSchemaLocations); - } - if (externalNoNamespaceSchemaLocation != null) { - parser.setProperty( - EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, - "externalNoNamespaceSchemaLocation"); - } - - // set up entity resolver and error handler - parser.setEntityResolver(new MOAEntityResolver()); - parser.setErrorHandler(new MOAErrorHandler()); - - // parse validating - parser.parse(new InputSource(new ByteArrayInputStream(docBytes))); - return true; - } - - - /** - * Schema validate a given DOM element. - * - * @param element The element to validate. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @return true, if the element validates against - * the schemas declared in it. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document from its - * serialized representation. - * @throws ParserConfigurationException An error occurred configuring the XML - * @throws TransformerException An error occurred serializing the element. - */ - public static boolean validateElement( - Element element, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation, - EntityResolver entityResolver) - throws - ParserConfigurationException, - IOException, - SAXException, - TransformerException { - - byte[] docBytes; - SAXParser parser; - - // create the SAX parser - if (symbolTable != null) { - parser = new SAXParser(symbolTable, grammarPool); - } else { - parser = new SAXParser(); - } - - // serialize the document - docBytes = serializeNode(element, "UTF-8"); - - // set up parser features and attributes - parser.setFeature(NAMESPACES_FEATURE, true); - parser.setFeature(VALIDATION_FEATURE, true); - parser.setFeature(SCHEMA_VALIDATION_FEATURE, true); - - if (externalSchemaLocations != null) { - parser.setProperty( - EXTERNAL_SCHEMA_LOCATION_PROPERTY, - externalSchemaLocations); - } - if (externalNoNamespaceSchemaLocation != null) { - parser.setProperty( - EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, - "externalNoNamespaceSchemaLocation"); - } - - // set up entity resolver and error handler - parser.setEntityResolver(entityResolver); - parser.setErrorHandler(new MOAErrorHandler()); - - // parse validating - parser.parse(new InputSource(new ByteArrayInputStream(docBytes))); - return true; - } - - /** - * Serialize the given DOM node. - * - * The node will be serialized using the UTF-8 encoding. - * - * @param node The node to serialize. - * @return String The String representation of the given DOM - * node. - * @throws TransformerException An error occurred transforming the - * node to a String. - * @throws IOException An IO error occurred writing the node to a byte array. - */ - public static String serializeNode(Node node) - throws TransformerException, IOException { - return new String(serializeNode(node, "UTF-8", false), "UTF-8"); - } - - - /** - * Serialize the given DOM node. - * - * The node will be serialized using the UTF-8 encoding. - * - * @param node The node to serialize. - * @param omitXmlDeclaration The boolean value for omitting the XML Declaration. - * @return String The String representation of the given DOM - * node. - * @throws TransformerException An error occurred transforming the - * node to a String. - * @throws IOException An IO error occurred writing the node to a byte array. - */ - public static String serializeNode(Node node, boolean omitXmlDeclaration) - throws TransformerException, IOException { - return new String(serializeNode(node, "UTF-8", omitXmlDeclaration), "UTF-8"); - } - - /** - * Serialize the given DOM node. - * - * The node will be serialized using the UTF-8 encoding. - * - * @param node The node to serialize. - * @param omitXmlDeclaration The boolean value for omitting the XML Declaration. - * @param lineSeperator Sets the line seperator String of the parser - * @return String The String representation of the given DOM - * node. - * @throws TransformerException An error occurred transforming the - * node to a String. - * @throws IOException An IO error occurred writing the node to a byte array. - */ - public static String serializeNode(Node node, boolean omitXmlDeclaration, String lineSeperator) - throws TransformerException, IOException { - return new String(serializeNode(node, "UTF-8", omitXmlDeclaration, lineSeperator), "UTF-8"); - } - - /** - * Serialize the given DOM node to a byte array. - * - * @param node The node to serialize. - * @param xmlEncoding The XML encoding to use. - * @return The serialized node, as a byte array. Using a compatible encoding - * this can easily be converted into a String. - * @throws TransformerException An error occurred transforming the node to a - * byte array. - * @throws IOException An IO error occurred writing the node to a byte array. - */ - public static byte[] serializeNode(Node node, String xmlEncoding) - throws TransformerException, IOException { - return serializeNode(node, xmlEncoding, false); - } - - /** - * Serialize the given DOM node to a byte array. - * - * @param node The node to serialize. - * @param xmlEncoding The XML encoding to use. - * @param omitDeclaration The boolean value for omitting the XML Declaration. - * @return The serialized node, as a byte array. Using a compatible encoding - * this can easily be converted into a String. - * @throws TransformerException An error occurred transforming the node to a - * byte array. - * @throws IOException An IO error occurred writing the node to a byte array. - */ - public static byte[] serializeNode(Node node, String xmlEncoding, boolean omitDeclaration) - throws TransformerException, IOException { - return serializeNode(node, xmlEncoding, omitDeclaration, null); - } - - - /** - * Serialize the given DOM node to a byte array. - * - * @param node The node to serialize. - * @param xmlEncoding The XML encoding to use. - * @param omitDeclaration The boolean value for omitting the XML Declaration. - * @param lineSeperator Sets the line seperator String of the parser - * @return The serialized node, as a byte array. Using a compatible encoding - * this can easily be converted into a String. - * @throws TransformerException An error occurred transforming the node to a - * byte array. - * @throws IOException An IO error occurred writing the node to a byte array. - */ - public static byte[] serializeNode(Node node, String xmlEncoding, boolean omitDeclaration, String lineSeperator) - throws TransformerException, IOException { - - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(16384); - - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); - transformer.setOutputProperty(OutputKeys.ENCODING, xmlEncoding); - String omit = omitDeclaration ? "yes" : "no"; - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omit); - if (null!=lineSeperator) { - transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", lineSeperator);//does not work for xalan <= 2.5.1 - } - transformer.transform(new DOMSource(node), new StreamResult(bos)); - - bos.flush(); - bos.close(); - - return bos.toByteArray(); - } - - /** - * Return the text that a node contains. - * - * This routine: - *
    - *
  • Ignores comments and processing instructions.
  • - *
  • Concatenates TEXT nodes, CDATA nodes, and the results recursively - * processing EntityRef nodes.
  • - *
  • Ignores any element nodes in the sublist. (Other possible options are - * to recurse into element sublists or throw an exception.)
  • - *
- * - * @param node A DOM node from which to extract text. - * @return A String representing its contents. - */ - public static String getText(Node node) { - if (!node.hasChildNodes()) { - return ""; - } - - StringBuffer result = new StringBuffer(); - NodeList list = node.getChildNodes(); - - for (int i = 0; i < list.getLength(); i++) { - Node subnode = list.item(i); - if (subnode.getNodeType() == Node.TEXT_NODE) { - result.append(subnode.getNodeValue()); - } else if (subnode.getNodeType() == Node.CDATA_SECTION_NODE) { - result.append(subnode.getNodeValue()); - } else if (subnode.getNodeType() == Node.ENTITY_REFERENCE_NODE) { - // Recurse into the subtree for text - // (and ignore comments) - result.append(getText(subnode)); - } - } - return result.toString(); - } - - /** - * Build the namespace prefix to namespace URL mapping in effect for a given - * node. - * - * @param node The context node for which build the map. - * @return The namespace prefix to namespace URL mapping ( - * a String value to String value mapping). - */ - public static Map getNamespaceDeclarations(Node node) { - Map nsDecls = new HashMap(); - int i; - - do { - if (node.hasAttributes()) { - NamedNodeMap attrs = node.getAttributes(); - - for (i = 0; i < attrs.getLength(); i++) { - Attr attr = (Attr) attrs.item(i); - - // add prefix mapping if none exists - if ("xmlns".equals(attr.getPrefix()) - || "xmlns".equals(attr.getName())) { - - String nsPrefix = - attr.getPrefix() != null ? attr.getLocalName() : ""; - - if (nsDecls.get(nsPrefix) == null) { - nsDecls.put(nsPrefix, attr.getValue()); - } - } - } - } - } while ((node = node.getParentNode()) != null); - - return nsDecls; - } - - /** - * Add all namespace declarations declared in the parent(s) of a given - * element and used in the subtree of the given element to the given element. - * - * @param context The element to which to add the namespaces. - */ - public static void localizeNamespaceDeclarations(Element context) { - Node parent = context.getParentNode(); - - if (parent != null) { - Map namespaces = getNamespaceDeclarations(context.getParentNode()); - Set nsUris = collectNamespaceURIs(context); - Iterator iter; - - for (iter = namespaces.entrySet().iterator(); iter.hasNext();) { - Map.Entry e = (Map.Entry) iter.next(); - - if (nsUris.contains(e.getValue())) { - String prefix = (String) e.getKey(); - String nsUri = (String) e.getValue(); - String nsAttrName = "".equals(prefix) ? "xmlns" : "xmlns:" + prefix; - - context.setAttributeNS(Constants.XMLNS_NS_URI, nsAttrName, nsUri); - } - } - } - } - - /** - * Collect all the namespace URIs used in the subtree of a given element. - * - * @param context The element that should be searched for namespace URIs. - * @return All namespace URIs used in the subtree of context, - * including the ones used in context itself. - */ - public static Set collectNamespaceURIs(Element context) { - Set result = new HashSet(); - - collectNamespaceURIsImpl(context, result); - return result; - } - - /** - * A recursive method to do the work of collectNamespaceURIs. - * - * @param context The context element to evaluate. - * @param result The result, passed as a parameter to avoid unnecessary - * instantiations of Set. - */ - private static void collectNamespaceURIsImpl(Element context, Set result) { - NamedNodeMap attrs = context.getAttributes(); - NodeList childNodes = context.getChildNodes(); - String nsUri; - int i; - - // add the namespace of the context element - nsUri = context.getNamespaceURI(); - if (nsUri != null && nsUri != Constants.XMLNS_NS_URI) { - result.add(nsUri); - } - - // add all namespace URIs from attributes - for (i = 0; i < attrs.getLength(); i++) { - nsUri = attrs.item(i).getNamespaceURI(); - if (nsUri != null && nsUri != Constants.XMLNS_NS_URI) { - result.add(nsUri); - } - } - - // add all namespaces from subelements - for (i = 0; i < childNodes.getLength(); i++) { - Node node = childNodes.item(i); - - if (node.getNodeType() == Node.ELEMENT_NODE) { - collectNamespaceURIsImpl((Element) node, result); - } - } - } - - /** - * Check, that each attribute node in the given NodeList has its - * parent in the NodeList as well. - * - * @param nodes The NodeList to check. - * @return true, if each attribute node in nodes - * has its parent in nodes as well. - */ - public static boolean checkAttributeParentsInNodeList(NodeList nodes) { - Set nodeSet = new HashSet(); - int i; - - // put the nodes into the nodeSet - for (i = 0; i < nodes.getLength(); i++) { - nodeSet.add(nodes.item(i)); - } - - // check that each attribute node's parent is in the node list - for (i = 0; i < nodes.getLength(); i++) { - Node n = nodes.item(i); - - if (n.getNodeType() == Node.ATTRIBUTE_NODE) { - Attr attr = (Attr) n; - Element owner = attr.getOwnerElement(); - - if (owner == null) { - if (!isNamespaceDeclaration(attr)) { - return false; - } - } - - if (!nodeSet.contains(owner) && !isNamespaceDeclaration(attr)) { - return false; - } - } - } - - return true; - } - - /** - * Convert an unstructured NodeList into a - * DocumentFragment. - * - * @param nodeList Contains the node list to be converted into a DOM - * DocumentFragment. - * @return the resulting DocumentFragment. The DocumentFragment will be - * backed by a new DOM Document, i.e. all noded of the node list will be - * cloned. - * @throws ParserConfigurationException An error occurred creating the - * DocumentFragment. - * @precondition The nodes in the node list appear in document order - * @precondition for each Attr node in the node list, the owning Element is - * in the node list as well. - * @precondition each Element or Attr node in the node list is namespace - * aware. - */ - public static DocumentFragment nodeList2DocumentFragment(NodeList nodeList) - throws ParserConfigurationException { - - DocumentBuilder builder = - DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document doc = builder.newDocument(); - DocumentFragment result = doc.createDocumentFragment(); - - if (null == nodeList || nodeList.getLength() == 0) { - return result; - } - - int currPos = 0; - currPos = - nodeList2DocumentFragment(nodeList, currPos, result, null, null) + 1; - - while (currPos < nodeList.getLength()) { - currPos = - nodeList2DocumentFragment(nodeList, currPos, result, null, null) + 1; - } - return result; - } - - /** - * Helper method for the nodeList2DocumentFragment. - * - * @param nodeList The NodeList to convert. - * @param currPos The current position in the nodeList. - * @param result The resulting DocumentFragment. - * @param currOrgElem The current original element. - * @param currClonedElem The current cloned element. - * @return The current position. - */ - private static int nodeList2DocumentFragment( - NodeList nodeList, - int currPos, - DocumentFragment result, - Element currOrgElem, - Element currClonedElem) { - - while (currPos < nodeList.getLength()) { - Node currentNode = nodeList.item(currPos); - switch (currentNode.getNodeType()) { - case Node.COMMENT_NODE : - case Node.PROCESSING_INSTRUCTION_NODE : - case Node.TEXT_NODE : - { - // Append current node either to resulting DocumentFragment or to - // current cloned Element - if (null == currClonedElem) { - result.appendChild( - result.getOwnerDocument().importNode(currentNode, false)); - } else { - // Stop processing if current Node is not a descendant of - // current Element - if (!isAncestor(currOrgElem, currentNode)) { - return --currPos; - } - - currClonedElem.appendChild( - result.getOwnerDocument().importNode(currentNode, false)); - } - break; - } - - case Node.ELEMENT_NODE : - { - Element nextCurrOrgElem = (Element) currentNode; - Element nextCurrClonedElem = - result.getOwnerDocument().createElementNS( - nextCurrOrgElem.getNamespaceURI(), - nextCurrOrgElem.getNodeName()); - - // Append current Node either to resulting DocumentFragment or to - // current cloned Element - if (null == currClonedElem) { - result.appendChild(nextCurrClonedElem); - currOrgElem = nextCurrOrgElem; - currClonedElem = nextCurrClonedElem; - } else { - // Stop processing if current Node is not a descendant of - // current Element - if (!isAncestor(currOrgElem, currentNode)) { - return --currPos; - } - - currClonedElem.appendChild(nextCurrClonedElem); - } - - // Process current Node (of type Element) recursively - currPos = - nodeList2DocumentFragment( - nodeList, - ++currPos, - result, - nextCurrOrgElem, - nextCurrClonedElem); - - break; - } - - case Node.ATTRIBUTE_NODE : - { - Attr currAttr = (Attr) currentNode; - - // GK 20030411: Hack to overcome problems with IAIK IXSIL - if (currAttr.getOwnerElement() == null) - break; - if (currClonedElem == null) - break; - - // currClonedElem must be the owner Element of currAttr if - // preconditions are met - currClonedElem.setAttributeNS( - currAttr.getNamespaceURI(), - currAttr.getNodeName(), - currAttr.getValue()); - break; - } - - default : - { - // All other nodes will be ignored - } - } - - currPos++; - } - - return currPos; - } - - /** - * Check, if the given attribute is a namespace declaration. - * - * @param attr The attribute to check. - * @return true, if the attribute is a namespace declaration, - * false otherwise. - */ - private static boolean isNamespaceDeclaration(Attr attr) { - return Constants.XMLNS_NS_URI.equals(attr.getNamespaceURI()); - } - - /** - * Check, if a given DOM element is an ancestor of a given node. - * - * @param candAnc The DOM element to check for being the ancestor. - * @param cand The node to check for being the child. - * @return true, if candAnc is an (indirect) - * ancestor of cand; false otherwise. - */ - public static boolean isAncestor(Element candAnc, Node cand) { - Node currPar = cand.getParentNode(); - - while (currPar != null) { - if (candAnc == currPar) - return true; - currPar = currPar.getParentNode(); - } - return false; - } - - /** - * Selects the (first) element from a node list and returns it. - * - * @param nl The NodeList to get the element from. - * @return The (first) element included in the node list or null - * if the node list is null or empty or no element is - * included in the list. - */ - public static Element getElementFromNodeList (NodeList nl) { - if ((nl == null) || (nl.getLength() == 0)) { - return null; - } - for (int i=0; iDefaultHandler that uses a MOAEntityResolver and * a MOAErrorHandler. @@ -48,9 +50,9 @@ public class MOADefaultHandler extends DefaultHandler { /** * Create a new MOADefaultHandler. - */ + */ public MOADefaultHandler() { - entityResolver = new MOAEntityResolver(); + entityResolver = new EAAFDomEntityResolver(); errorHandler = new MOAErrorHandler(); } diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeIteratorAdapter.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeIteratorAdapter.java deleted file mode 100644 index fdc823229..000000000 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeIteratorAdapter.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - - -package at.gv.egovernment.moa.util; - -import java.util.ListIterator; - -import org.w3c.dom.DOMException; -import org.w3c.dom.Node; -import org.w3c.dom.traversal.NodeFilter; -import org.w3c.dom.traversal.NodeIterator; - -/** - * A NodeIterator implementation based on a - * ListIterator. - * - * @see java.util.ListIterator - * @see org.w3c.dom.traversal.NodeIterator - * - * @author Patrick Peck - * @version $Id$ - */ -public class NodeIteratorAdapter implements NodeIterator { - - /** The ListIterator to wrap. */ - private ListIterator nodeIterator; - - /** - * Create a new NodeIteratorAdapter. - * @param nodeIterator The ListIterator to iterate over. - */ - public NodeIteratorAdapter(ListIterator nodeIterator) { - this.nodeIterator = nodeIterator; - } - - /** - * @see org.w3c.dom.traversal.NodeIterator#getRoot() - */ - public Node getRoot() { - return null; - } - - /** - * @see org.w3c.dom.traversal.NodeIterator#getWhatToShow() - */ - public int getWhatToShow() { - return NodeFilter.SHOW_ALL; - } - - /** - * @see org.w3c.dom.traversal.NodeIterator#getFilter() - */ - public NodeFilter getFilter() { - return null; - } - - /** - * @see org.w3c.dom.traversal.NodeIterator#getExpandEntityReferences() - */ - public boolean getExpandEntityReferences() { - return false; - } - - /** - * @see org.w3c.dom.traversal.NodeIterator#nextNode() - */ - public Node nextNode() throws DOMException { - if (nodeIterator.hasNext()) { - return (Node) nodeIterator.next(); - } - return null; - } - - /** - * @see org.w3c.dom.traversal.NodeIterator#previousNode() - */ - public Node previousNode() throws DOMException { - if (nodeIterator.hasPrevious()) { - return (Node) nodeIterator.previous(); - } - return null; - } - - /** - * @see org.w3c.dom.traversal.NodeIterator#detach() - */ - public void detach() { - } - -} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeListAdapter.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeListAdapter.java deleted file mode 100644 index e39cc0291..000000000 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeListAdapter.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - - -package at.gv.egovernment.moa.util; - -import java.util.List; - -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - * A NodeList implementation based on a List. - * - * @see java.util.List - * @see org.w3c.dom.NodeList - * - * @author Patrick Peck - * @version $Id$ - */ -public class NodeListAdapter implements NodeList { - /** The List to wrap. */ - private List nodeList; - - /** - * Create a new NodeListAdapter. - * - * @param nodeList The List containing the nodes. - */ - public NodeListAdapter(List nodeList) { - this.nodeList = nodeList; - } - - /** - * @see org.w3c.dom.NodeList#item(int) - */ - public Node item(int index) { - return (Node) nodeList.get(index); - } - - /** - * @see org.w3c.dom.NodeList#getLength() - */ - public int getLength() { - return nodeList.size(); - } - -} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathException.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathException.java deleted file mode 100644 index 206245a68..000000000 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathException.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - - -package at.gv.egovernment.moa.util; - -import java.io.PrintStream; -import java.io.PrintWriter; - -/** - * An exception occurred evaluating an XPath. - * - * @author Patrick Peck - * @version $Id$ - */ -public class XPathException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 1736311265333034392L; -/** The wrapped exception. */ - private Throwable wrapped; - - /** - * Create a XPathException. - * - * @param message The exception message. - * @param wrapped The exception being the likely cause of this exception. - */ - public XPathException(String message, Throwable wrapped) { - super(message); - this.wrapped = wrapped; - } - - /** - * Return the wrapped exception. - * - * @return The wrapped exception being the likely cause of this exception. - */ - public Throwable getWrapped() { - return wrapped; - } - - /** - * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) - */ - public void printStackTrace(PrintStream s) { - super.printStackTrace(s); - if (getWrapped() != null) { - s.print("Caused by: "); - getWrapped().printStackTrace(s); - } - } - - /** - * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) - */ - public void printStackTrace(PrintWriter s) { - super.printStackTrace(s); - if (getWrapped() != null) { - s.print("Caused by: "); - getWrapped().printStackTrace(s); - } - } - -} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathUtils.java deleted file mode 100644 index 89aeaf3d1..000000000 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathUtils.java +++ /dev/null @@ -1,557 +0,0 @@ -/* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - - -package at.gv.egovernment.moa.util; - -import java.util.List; -import java.util.Map; - -import org.w3c.dom.Attr; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.traversal.NodeIterator; - -import org.jaxen.JaxenException; -import org.jaxen.NamespaceContext; -import org.jaxen.Navigator; -import org.jaxen.SimpleNamespaceContext; -import org.jaxen.dom.DOMXPath; -import org.jaxen.dom.DocumentNavigator; - -/** - * Utility methods to evaluate XPath expressions on DOM nodes. - * - * @author Patrick Peck - * @version $Id$ - */ -public class XPathUtils { - - /** - * The XPath expression selecting all nodes under a given root (including the - * root node itself). - */ - public static final String ALL_NODES_XPATH = - "(.//. | .//@* | .//namespace::*)"; - - /** The DocumentNavigator to use for navigating the document. */ - private static Navigator documentNavigator = - DocumentNavigator.getInstance(); - /** The default namespace prefix to namespace URI mappings. */ - private static NamespaceContext NS_CONTEXT; - - static { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(); - ctx.addNamespace(Constants.MOA_PREFIX, Constants.MOA_NS_URI); - ctx.addNamespace(Constants.MOA_CONFIG_PREFIX, Constants.MOA_CONFIG_NS_URI); - ctx.addNamespace(Constants.MOA_ID_CONFIG_PREFIX, Constants.MOA_ID_CONFIG_NS_URI); - ctx.addNamespace(Constants.SL10_PREFIX, Constants.SL10_NS_URI); - ctx.addNamespace(Constants.SL11_PREFIX, Constants.SL11_NS_URI); - ctx.addNamespace(Constants.SL12_PREFIX, Constants.SL12_NS_URI); - ctx.addNamespace(Constants.ECDSA_PREFIX, Constants.ECDSA_NS_URI); - ctx.addNamespace(Constants.PD_PREFIX, Constants.PD_NS_URI); - ctx.addNamespace(Constants.SAML_PREFIX, Constants.SAML_NS_URI); - ctx.addNamespace(Constants.SAMLP_PREFIX, Constants.SAMLP_NS_URI); - ctx.addNamespace(Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); - ctx.addNamespace(Constants.XSLT_PREFIX, Constants.XSLT_NS_URI); - ctx.addNamespace(Constants.XSI_PREFIX, Constants.XSI_NS_URI); - ctx.addNamespace(Constants.DSIG_FILTER2_PREFIX, Constants.DSIG_FILTER2_NS_URI); - ctx.addNamespace(Constants.DSIG_EC_PREFIX, Constants.DSIG_EC_NS_URI); - ctx.addNamespace(Constants.MD_PREFIX, Constants.MD_NS_URI); - ctx.addNamespace(Constants.MDP_PREFIX, Constants.MDP_NS_URI); - ctx.addNamespace(Constants.MVV_PREFIX, Constants.MVV_NS_URI); - ctx.addNamespace(Constants.STB_PREFIX, Constants.STB_NS_URI); - ctx.addNamespace(Constants.WRR_PREFIX, Constants.WRR_NS_URI); - ctx.addNamespace(Constants.STORK_PREFIX, Constants.STORK_NS_URI); - ctx.addNamespace(Constants.STORKP_PREFIX, Constants.STORKP_NS_URI); - ctx.addNamespace(Constants.SAML2_PREFIX, Constants.SAML2_NS_URI); - ctx.addNamespace(Constants.SAML2P_PREFIX, Constants.SAML2P_NS_URI); - ctx.addNamespace(Constants.XENC_PREFIX, Constants.XENC_NS_URI); - ctx.addNamespace(Constants.XADES_1_1_1_NS_PREFIX, Constants.XADES_1_1_1_NS_URI); - NS_CONTEXT = ctx; - } - - /** - * Return a NodeIterator over the nodes matching the XPath - * expression. - * - * All namespace URIs and prefixes declared in the Constants - * interface are used for resolving namespaces. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param exp The XPath expression to evaluate. - * @return An iterator over the resulting nodes. - * @throws XPathException An error occurred evaluating the XPath expression. - */ - public static NodeIterator selectNodeIterator(Node contextNode, String exp) - throws XPathException { - - return selectNodeIterator(contextNode, NS_CONTEXT, exp); - } - - /** - * Return a NodeIterator over the nodes matching the XPath - * expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param namespaceElement An element from which to build the - * namespace mapping for evaluating the XPath expression - * @param exp The XPath expression to evaluate. - * @return An iterator over the resulting nodes. - * @throws XPathException An error occurred evaluating the XPath expression. - */ - public static NodeIterator selectNodeIterator( - Node contextNode, - Element namespaceElement, - String exp) - throws XPathException { - - try { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(); - ctx.addElementNamespaces(documentNavigator, namespaceElement); - return selectNodeIterator(contextNode, ctx, exp); - } catch (JaxenException e) { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { exp }); - throw new XPathException(message, e); - } - } - - /** - * Return a NodeIterator over the nodes matching the XPath - * expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param namespaceMapping A namespace prefix to namespace URI mapping - * (String to String) for evaluating the XPath - * expression. - * @param exp The XPath expression to evaluate. - * @return An iterator over the resulting nodes. - * @throws XPathException An error occurred evaluating the XPath expression. - */ - public static NodeIterator selectNodeIterator( - Node contextNode, - Map namespaceMapping, - String exp) - throws XPathException { - - SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); - - return selectNodeIterator(contextNode, ctx, exp); - } - - /** - * Return a NodeIterator over the nodes matching the XPath - * expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param nsContext The NamespaceContext for resolving namespace - * prefixes to namespace URIs for evaluating the XPath expression. - * @param exp The XPath expression to evaluate. - * @return An iterator over the resulting nodes. - * @throws XPathException An error occurred evaluating the XPath expression. - */ - private static NodeIterator selectNodeIterator( - Node contextNode, - NamespaceContext nsContext, - String exp) - throws XPathException { - - try { - DOMXPath xpath = new DOMXPath(exp); - List nodes; - - xpath.setNamespaceContext(nsContext); - nodes = xpath.selectNodes(contextNode); - return new NodeIteratorAdapter(nodes.listIterator()); - } catch (JaxenException e) { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { exp }); - throw new XPathException(message, e); - } - } - - /** - * Return a NodeList of all the nodes matching the XPath - * expression. - * - * All namespace URIs and prefixes declared in the Constants - * interface are used for resolving namespaces. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param exp The XPath expression to evaluate. - * @return A NodeList containing the matching nodes. - * @throws XPathException An error occurred evaluating the XPath expression. - */ - public static NodeList selectNodeList(Node contextNode, String exp) - throws XPathException { - - return selectNodeList(contextNode, NS_CONTEXT, exp); - } - - /** - * Return a NodeList of all the nodes matching the XPath - * expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param namespaceElement An element from which to build the - * namespace mapping for evaluating the XPath expression - * @param exp The XPath expression to evaluate. - * @return A NodeList containing the matching nodes. - * @throws XPathException An error occurred evaluating the XPath expression. - */ - public static NodeList selectNodeList( - Node contextNode, - Element namespaceElement, - String exp) - throws XPathException { - - try { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(); - - ctx.addElementNamespaces(documentNavigator, namespaceElement); - return selectNodeList(contextNode, ctx, exp); - } catch (JaxenException e) { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { exp }); - throw new XPathException(message, e); - } - } - - /** - * Return a NodeList of all the nodes matching the XPath - * expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param namespaceMapping A namespace prefix to namespace URI mapping - * (String to String) for evaluating the XPath - * expression. - * @param exp The XPath expression to evaluate. - * @return A NodeList containing the matching nodes. - * @throws XPathException An error occurred evaluating the XPath expression. - */ - public static NodeList selectNodeList( - Node contextNode, - Map namespaceMapping, - String exp) - throws XPathException { - - SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); - - return selectNodeList(contextNode, ctx, exp); - } - - /** - * Return a NodeList of all the nodes matching the XPath - * expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param nsContext The NamespaceContext for resolving namespace - * prefixes to namespace URIs for evaluating the XPath expression. - * @param exp The XPath expression to evaluate. - * @return A NodeList containing the matching nodes. - * @throws XPathException An error occurred evaluating the XPath expression. - */ - private static NodeList selectNodeList( - Node contextNode, - NamespaceContext nsContext, - String exp) - throws XPathException { - - try { - DOMXPath xpath = new DOMXPath(exp); - List nodes; - - xpath.setNamespaceContext(nsContext); - nodes = xpath.selectNodes(contextNode); - return new NodeListAdapter(nodes); - } catch (JaxenException e) { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { exp }); - throw new XPathException(message, e); - } - } - - /** - * Select the first node matching an XPath expression. - * - * All namespace URIs and prefixes declared in the Constants - * interface are used for resolving namespaces. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param exp The XPath expression to evaluate. - * @return Node The first node matching the XPath expression, or - * null, if no node matched. - * @throws XPathException An error occurred evaluating the XPath expression. - */ - public static Node selectSingleNode(Node contextNode, String exp) - throws XPathException { - - return selectSingleNode(contextNode, NS_CONTEXT, exp); - } - - /** - * Select the first node matching an XPath expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param namespaceElement An element from which to build the - * namespace mapping for evaluating the XPath expression - * @param exp The XPath expression to evaluate. - * @return Node The first node matching the XPath expression, or - * null, if no node matched. - * @throws XPathException An error occurred evaluating the XPath expression. - */ - public static Node selectSingleNode( - Node contextNode, - Element namespaceElement, - String exp) - throws XPathException { - - try { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(); - ctx.addElementNamespaces(documentNavigator, namespaceElement); - - return selectSingleNode(contextNode, ctx, exp); - } catch (JaxenException e) { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { exp }); - throw new XPathException(message, e); - } - } - - /** - * Select the first node matching an XPath expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param namespaceMapping A namespace prefix to namespace URI mapping - * (String to String) for evaluating the XPath - * expression. - * @param exp The XPath expression to evaluate. - * @return Node The first node matching the XPath expression, or - * null, if no node matched. - * @throws XPathException An error occurred evaluating the XPath expression. - */ - public static Node selectSingleNode( - Node contextNode, - Map namespaceMapping, - String exp) - throws XPathException { - - SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); - - return selectSingleNode(contextNode, ctx, exp); - } - - /** - * Select the first node matching an XPath expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param nsContext The NamespaceContext for resolving namespace - * prefixes to namespace URIs for evaluating the XPath expression. - * @param exp The XPath expression to evaluate. - * @return Node The first node matching the XPath expression, or - * null, if no node matched. - * @throws XPathException An error occurred evaluating the XPath expression. - */ - public static Node selectSingleNode( - Node contextNode, - NamespaceContext nsContext, - String exp) - throws XPathException { - - try { - DOMXPath xpath = new DOMXPath(exp); - xpath.setNamespaceContext(nsContext); - return (Node) xpath.selectSingleNode(contextNode); - } catch (JaxenException e) { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { exp }); - throw new XPathException(message, e); - } - } - - /** - * Return the value of a DOM element whose location is given by an XPath - * expression. - * - * @param root The root element from which to evaluate the XPath. - * @param xpath The XPath expression pointing to the element whose value - * to return. - * @param def The default value to return, if no element can be found using - * the given xpath. - * @return The element value, if it can be located using the - * xpath. Otherwise, def is returned. - */ - public static String getElementValue( - Element root, - String xpath, - String def) { - - Element elem = (Element) XPathUtils.selectSingleNode(root, xpath); - return elem != null ? DOMUtils.getText(elem) : def; - } - - /** - * Return the value of a DOM attribute whose location is given by an XPath - * expression. - * - * @param root The root element from which to evaluate the XPath. - * @param xpath The XPath expression pointing to the attribute whose value to - * return. - * @param def The default value to return, if no attribute can be found using - * the given xpath. - * @return The element value, if it can be located using the - * xpath. Otherwise, def is returned. - */ - public static String getAttributeValue( - Element root, - String xpath, - String def) { - - Attr attr = (Attr) XPathUtils.selectSingleNode(root, xpath); - return attr != null ? attr.getValue() : def; - } - - /** - * Returns the namespace prefix used within XPathUtils for referring to - * the namespace of the specified (Security Layer command) element. - * - * This namespace prefix can be used in various XPath expression evaluation methods - * within XPathUtils without explicitely binding it to the particular - * namespace. - * - * @param contextElement The (Security Layer command) element. - * - * @return the namespace prefix used within XPathUtils for referring to - * the namespace of the specified (Security Layer command) element. - * - * throws XpathException If the specified element has a namespace other than the ones - * known by this implementation as valid Security Layer namespaces (cf. - * @link Constants#SL10_NS_URI, @link Constants#SL11_NS_URI, @link Constants#SL12_NS_URI). - */ - public static String getSlPrefix (Element contextElement) throws XPathException - { - String sLNamespace = contextElement.getNamespaceURI(); - String sLPrefix = null; - - if (sLNamespace.equals(Constants.SL10_NS_URI)) - { - sLPrefix = Constants.SL10_PREFIX; - } - else if (sLNamespace.equals(Constants.SL12_NS_URI)) - { - sLPrefix = Constants.SL12_PREFIX; - } - else if (sLNamespace.equals(Constants.SL11_NS_URI)) - { - sLPrefix = Constants.SL11_PREFIX; - } - else - { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { "Ung�ltiger Security Layer Namespace: \"" + sLNamespace + "\"."}); - throw new XPathException(message, null); - } - - return sLPrefix; - } - - - /** - * Return the SecurityLayer namespace prefix of the context element. - * If the context element is not the element that lies within the - * SecurityLayer namespace. The Securitylayer namespace is derived from - * the xmlns:sl10, sl11 or sl - * attribute of the context element. - * - * The returned prefix is needed for evaluating XPATH expressions. - * - * @param contextElement The element to get a prefix for the Securitylayer namespace, - * that is used within the corresponding document. - * - * @return The string sl10, sl11 or sl, - * depending on the SecurityLayer namespace of the contextElement. - * - * throws XPathException If no (vlalid) SecurityLayer namespace prefix or namespace - * is defined. - */ - public static String getSlPrefixFromNoRoot (Element contextElement) throws XPathException { - - String slPrefix = checkSLnsDeclaration(contextElement, Constants.SL10_PREFIX, Constants.SL10_NS_URI); - if (slPrefix == null) { - slPrefix = checkSLnsDeclaration(contextElement, Constants.SL11_PREFIX, Constants.SL11_NS_URI); - } - if (slPrefix == null) { - slPrefix = checkSLnsDeclaration(contextElement, Constants.SL12_PREFIX, Constants.SL12_NS_URI); - } - - return slPrefix; - - } - - /** - * Checks if the context element has an attribute xmlns:slPrefix and - * if the prefix of that attribute corresponds with a valid SecurityLayer namespace. - * - * @param contextElement The element to be checked. - * @param slPrefix The prefix which should be checked. Must be a valid SecurityLayer - * namespace prefix. - * @param slNameSpace The SecurityLayer namespace that corresponds to the specified prefix. - * - * @return The valid SecurityLayer prefix or null if this prefix is - * not used. - * @throws XPathException - */ - private static String checkSLnsDeclaration(Element contextElement, String slPrefix, String slNameSpace) - throws XPathException - { - String nsAtt = "xmlns:" + slPrefix; - String nameSpace = contextElement.getAttribute(nsAtt); - if (nameSpace == "") { - return null; - } else { - // check if namespace is correct - if (nameSpace.equals(slNameSpace)) { - return slPrefix; - } else { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { "Ung�ltiger SecurityLayer Namespace: \"" + nameSpace + "\"."}); - throw new XPathException(message, null); - } - } - } - -} -- cgit v1.2.3