List of usage examples for org.w3c.dom.bootstrap DOMImplementationRegistry newInstance
public static DOMImplementationRegistry newInstance() throws ClassNotFoundException, InstantiationException, IllegalAccessException, ClassCastException
DOMImplementationRegistry
. From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java
/** * Serialize the given Dom Object to a String. * // w w w. j a v a 2 s . c o m * @param xml The Xml Node to serialize. * @param omitXMLDeclaration Indicates if XML declaration will be omitted. * @return The String representation of the Xml Node. * @throws Exception If anything fails. */ protected static String toString(final Node xml, final boolean omitXMLDeclaration) throws Exception { if (xml == null) { throw new IllegalArgumentException(TestBase.class.getSimpleName() + ":toString:xml is null"); } String result = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // serialize DOMImplementation implementation = DOMImplementationRegistry.newInstance().getDOMImplementation("XML 3.0"); DOMImplementationLS feature = (DOMImplementationLS) implementation.getFeature("LS", "3.0"); LSSerializer serial = feature.createLSSerializer(); LSOutput output = feature.createLSOutput(); output.setByteStream(outputStream); serial.write(xml, output); result = output.toString(); return result; }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Serialize the given Dom Object to a String. * // w w w. j a v a 2s. c o m * @param xml * The Xml Node to serialize. * @param omitXMLDeclaration * Indicates if XML declaration will be omitted. * @return The String representation of the Xml Node. * @throws Exception * If anything fails. */ public static String toString(final Node xml, final boolean omitXMLDeclaration) throws Exception { String result = new String(); if (xml instanceof AttrImpl) { result = xml.getTextContent(); } else if (xml instanceof Document) { StringWriter stringOut = new StringWriter(); // format OutputFormat format = new OutputFormat((Document) xml); format.setIndenting(true); format.setPreserveSpace(true); format.setOmitXMLDeclaration(omitXMLDeclaration); format.setEncoding(DEFAULT_CHARSET); // serialize XMLSerializer serial = new XMLSerializer(stringOut, format); serial.asDOMSerializer(); serial.serialize((Document) xml); result = stringOut.toString(); } else { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSOutput lsOutput = impl.createLSOutput(); lsOutput.setEncoding(DEFAULT_CHARSET); ByteArrayOutputStream os = new ByteArrayOutputStream(); lsOutput.setByteStream(os); LSSerializer writer = impl.createLSSerializer(); // result = writer.writeToString(xml); writer.write(xml, lsOutput); result = ((ByteArrayOutputStream) lsOutput.getByteStream()).toString(DEFAULT_CHARSET); if ((omitXMLDeclaration) && (result.indexOf("?>") != -1)) { result = result.substring(result.indexOf("?>") + 2); } // result = toString(getDocument(writer.writeToString(xml)), // true); } return result; }
From source file:nl.imvertor.common.file.XmlFile.java
/** * Zet een Document weg als file. Transformeer middels het XSLT file. Als * XSLT file is "", identity transform./*from w w w . ja v a 2 s . c om*/ * * @param doc * @param xsltfile * @param parms * @throws Exception */ public void fromDocument(Document doc) throws Exception { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("XML 3.0 LS 3.0"); if (impl == null) { System.out.println("No DOMImplementation found !"); System.exit(0); } LSSerializer serializer = impl.createLSSerializer(); LSOutput output = impl.createLSOutput(); output.setEncoding("UTF-8"); output.setByteStream(new FileOutputStream(this)); serializer.write(doc, output); }
From source file:org.alfresco.web.forms.xforms.SchemaUtil.java
public static XSModel parseSchema(final Document schemaDocument, final boolean failOnError) throws FormBuilderException { try {// w w w . j a v a 2 s . co m // Get DOM Implementation using DOM Registry System.setProperty(DOMImplementationRegistry.PROPERTY, "org.apache.xerces.dom.DOMXSImplementationSourceImpl"); final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); final DOMImplementationLS lsImpl = (DOMImplementationLS) registry .getDOMImplementation("XML 1.0 LS 3.0"); if (lsImpl == null) { throw new FormBuilderException("unable to create DOMImplementationLS using " + registry); } final LSInput in = lsImpl.createLSInput(); in.setStringData(XMLUtil.toString(schemaDocument)); final XSImplementation xsImpl = (XSImplementation) registry.getDOMImplementation("XS-Loader"); final XSLoader schemaLoader = xsImpl.createXSLoader(null); final DOMConfiguration config = (DOMConfiguration) schemaLoader.getConfig(); final LinkedList<DOMError> errors = new LinkedList<DOMError>(); config.setParameter("error-handler", new DOMErrorHandler() { public boolean handleError(final DOMError domError) { errors.add(domError); return true; } }); final XSModel result = schemaLoader.load(in); if (failOnError && errors.size() != 0) { final HashSet<String> messages = new HashSet<String>(); StringBuilder message = null; for (DOMError e : errors) { message = new StringBuilder(); final DOMLocator dl = e.getLocation(); if (dl != null) { message.append("at line ").append(dl.getLineNumber()).append(" column ") .append(dl.getColumnNumber()); if (dl.getRelatedNode() != null) { message.append(" node ").append(dl.getRelatedNode().getNodeName()); } message.append(": ").append(e.getMessage()); } messages.add(message.toString()); } message = new StringBuilder(); message.append(messages.size() > 1 ? "errors" : "error").append(" parsing schema: \n"); for (final String s : messages) { message.append(s).append("\n"); } throw new FormBuilderException(message.toString()); } if (result == null) { throw new FormBuilderException("invalid schema"); } return result; } catch (ClassNotFoundException x) { throw new FormBuilderException(x); } catch (InstantiationException x) { throw new FormBuilderException(x); } catch (IllegalAccessException x) { throw new FormBuilderException(x); } }
From source file:org.apache.rahas.impl.SAML2TokenIssuer.java
public SOAPEnvelope issue(RahasData data) throws TrustException { MessageContext inMsgCtx = data.getInMessageContext(); try {//from w ww. j a va 2s. c o m SAMLTokenIssuerConfig config = null; if (this.configElement != null) { config = new SAMLTokenIssuerConfig( configElement.getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG)); } // Look for the file if (config == null && this.configFile != null) { config = new SAMLTokenIssuerConfig(this.configFile); //config = new SAMLTokenIssuerConfig("/home/thilina/Desktop/saml-issuer-config.xml"); } // Look for the param if (config == null && this.configParamName != null) { Parameter param = inMsgCtx.getParameter(this.configParamName); if (param != null && param.getParameterElement() != null) { config = new SAMLTokenIssuerConfig(param.getParameterElement() .getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG)); } else { throw new TrustException("expectedParameterMissing", new String[] { this.configParamName }); } } if (config == null) { throw new TrustException("configurationIsNull"); } //initialize and set token persister and config in configuration context. if (TokenIssuerUtil.isPersisterConfigured(config)) { TokenIssuerUtil.manageTokenPersistenceSettings(config, inMsgCtx); } SOAPEnvelope env = TrustUtil .createSOAPEnvelope(inMsgCtx.getEnvelope().getNamespace().getNamespaceURI()); Crypto crypto; if (config.cryptoElement != null) { // crypto props // defined as // elements crypto = CryptoFactory.getInstance(TrustUtil.toProperties(config.cryptoElement), inMsgCtx.getAxisService().getClassLoader()); } else { // crypto props defined in a properties file crypto = CryptoFactory.getInstance(config.cryptoPropertiesFile, inMsgCtx.getAxisService().getClassLoader()); } // Get the document Document doc = ((Element) env).getOwnerDocument(); // Get the key size and create a new byte array of that size int keySize = data.getKeysize(); String keyType = data.getKeyType(); keySize = (keySize == -1) ? config.keySize : keySize; //Build the assertion AssertionBuilder assertionBuilder = new AssertionBuilder(); Assertion assertion = assertionBuilder.buildObject(); assertion.setVersion(SAMLVersion.VERSION_20); // Set an UUID as the ID of an assertion assertion.setID(UUIDGenerator.getUUID()); //Set the issuer IssuerBuilder issuerBuilder = new IssuerBuilder(); Issuer issuer = issuerBuilder.buildObject(); issuer.setValue(config.issuerName); assertion.setIssuer(issuer); // Validity period DateTime creationDate = new DateTime(); DateTime expirationDate = new DateTime(creationDate.getMillis() + config.ttl); // These variables are used to build the trust assertion Date creationTime = creationDate.toDate(); Date expirationTime = expirationDate.toDate(); Conditions conditions = new ConditionsBuilder().buildObject(); conditions.setNotBefore(creationDate); conditions.setNotOnOrAfter(expirationDate); if (data.getAppliesToAddress() != null) { AudienceRestriction audienceRestriction = new AudienceRestrictionBuilder().buildObject(); Audience issuerAudience = new AudienceBuilder().buildObject(); issuerAudience.setAudienceURI(data.getAppliesToAddress()); audienceRestriction.getAudiences().add(issuerAudience); conditions.getAudienceRestrictions().add(audienceRestriction); } assertion.setConditions(conditions); // Set the issued time. assertion.setIssueInstant(new DateTime()); // Create the subject Subject subject; if (!data.getKeyType().endsWith(RahasConstants.KEY_TYPE_BEARER)) { subject = createSubjectWithHolderOfKeySC(config, doc, crypto, creationDate, expirationDate, data); } else { subject = createSubjectWithBearerSC(data); } // Set the subject assertion.setSubject(subject); // If a SymmetricKey is used build an attr stmt, if a public key is build an authn stmt. if (isSymmetricKeyBasedHoK) { AttributeStatement attrStmt = createAttributeStatement(data, config); assertion.getAttributeStatements().add(attrStmt); } else { AuthnStatement authStmt = createAuthnStatement(data); assertion.getAuthnStatements().add(authStmt); if (data.getClaimDialect() != null && data.getClaimElem() != null) { assertion.getAttributeStatements().add(createAttributeStatement(data, config)); } } if (data.getOverridenSubjectValue() != null && data.getOverridenSubjectValue().trim().length() > 0) { subject.getNameID().setValue(data.getOverridenSubjectValue()); } // Create a SignKeyHolder to hold the crypto objects that are used to sign the assertion SignKeyHolder signKeyHolder = createSignKeyHolder(config, crypto); // Sign the assertion assertion = setSignature(assertion, signKeyHolder); OMElement rstrElem; int wstVersion = data.getVersion(); if (RahasConstants.VERSION_05_02 == wstVersion) { rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(wstVersion, env.getBody()); } else { OMElement rstrcElem = TrustUtil.createRequestSecurityTokenResponseCollectionElement(wstVersion, env.getBody()); rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(wstVersion, rstrcElem); } TrustUtil.createTokenTypeElement(wstVersion, rstrElem).setText(RahasConstants.TOK_TYPE_SAML_20); if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) { TrustUtil.createKeySizeElement(wstVersion, rstrElem, keySize); } if (config.addRequestedAttachedRef) { TrustUtil.createRequestedAttachedRef(wstVersion, rstrElem, "#" + assertion.getID(), RahasConstants.TOK_TYPE_SAML_20); } if (config.addRequestedUnattachedRef) { TrustUtil.createRequestedUnattachedRef(wstVersion, rstrElem, assertion.getID(), RahasConstants.TOK_TYPE_SAML_20); } if (data.getAppliesToAddress() != null) { TrustUtil.createAppliesToElement(rstrElem, data.getAppliesToAddress(), data.getAddressingNs()); } // Use GMT time in milliseconds DateFormat zulu = new XmlSchemaDateFormat(); // Add the Lifetime element TrustUtil.createLifetimeElement(wstVersion, rstrElem, zulu.format(creationTime), zulu.format(expirationTime)); // Create the RequestedSecurityToken element and add the SAML token // to it OMElement reqSecTokenElem = TrustUtil.createRequestedSecurityTokenElement(wstVersion, rstrElem); Token assertionToken; Node tempNode = assertion.getDOM(); //Serializing and re-generating the AXIOM element using the DOM Element created using xerces Element element = assertion.getDOM(); ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream(); DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); LSOutput output = impl.createLSOutput(); output.setByteStream(byteArrayOutputStrm); writer.write(element, output); String elementString = byteArrayOutputStrm.toString(); OMElement assertionElement = AXIOMUtil.stringToOM(elementString); reqSecTokenElem.addChild((OMNode) ((Element) rstrElem).getOwnerDocument().importNode(tempNode, true)); // Store the token assertionToken = new Token(assertion.getID(), (OMElement) assertionElement, creationTime, expirationTime); // At this point we definitely have the secret // Otherwise it should fail with an exception earlier assertionToken.setSecret(data.getEphmeralKey()); if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY) && config.keyComputation != SAMLTokenIssuerConfig.KeyComputation.KEY_COMP_USE_REQ_ENT) { TokenIssuerUtil.handleRequestedProofToken(data, wstVersion, config, rstrElem, assertionToken, doc); } //SAML tokens are enabled for persistence only if token store is not disabled. if (!config.isTokenStoreDisabled()) { assertionToken.setPersistenceEnabled(true); TrustUtil.getTokenStore(inMsgCtx).add(assertionToken); } return env; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.apache.rahas.impl.util.SAML2Utils.java
public static Element getElementFromAssertion(XMLObject xmlObj) throws TrustException { try {/*from w w w. j a v a 2s. co m*/ String jaxpProperty = System.getProperty("javax.xml.parsers.DocumentBuilderFactory"); System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory(); Marshaller marshaller = marshallerFactory.getMarshaller(xmlObj); Element element = marshaller.marshall(xmlObj); // Reset the sys. property to its previous value. if (jaxpProperty == null) { System.getProperties().remove("javax.xml.parsers.DocumentBuilderFactory"); } else { System.setProperty("javax.xml.parsers.DocumentBuilderFactory", jaxpProperty); } ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream(); DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); LSOutput output = impl.createLSOutput(); output.setByteStream(byteArrayOutputStrm); writer.write(element, output); String elementString = byteArrayOutputStrm.toString(); DocumentBuilderFactoryImpl.setDOOMRequired(true); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = docBuilder.parse(new ByteArrayInputStream(elementString.trim().getBytes())); Element assertionElement = document.getDocumentElement(); DocumentBuilderFactoryImpl.setDOOMRequired(false); log.debug("DOM element is created successfully from the OpenSAML2 XMLObject"); return assertionElement; } catch (Exception e) { throw new TrustException("Error creating DOM object from the assertion", e); } }
From source file:org.apache.syncope.core.logic.init.CamelRouteLoader.java
private void loadRoutes(final String domain, final DataSource dataSource, final Resource resource, final AnyTypeKind anyTypeKind) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); boolean shouldLoadRoutes = jdbcTemplate.queryForList( String.format("SELECT * FROM %s WHERE ANYTYPEKIND = ?", CamelRoute.class.getSimpleName()), new Object[] { anyTypeKind.name() }).isEmpty(); if (shouldLoadRoutes) { try {//from ww w . j a v a 2 s .c o m TransformerFactory tf = null; DOMImplementationLS domImpl = null; NodeList routeNodes; if (IS_JBOSS) { tf = TransformerFactory.newInstance(); tf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(resource.getInputStream()); routeNodes = doc.getDocumentElement().getElementsByTagName("route"); } else { DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance(); domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS"); LSInput lsinput = domImpl.createLSInput(); lsinput.setByteStream(resource.getInputStream()); LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); routeNodes = parser.parse(lsinput).getDocumentElement().getElementsByTagName("route"); } for (int s = 0; s < routeNodes.getLength(); s++) { Node routeElement = routeNodes.item(s); String routeContent = IS_JBOSS ? nodeToString(routeNodes.item(s), tf) : nodeToString(routeNodes.item(s), domImpl); String routeId = ((Element) routeElement).getAttribute("id"); jdbcTemplate.update( String.format("INSERT INTO %s(ID, ANYTYPEKIND, CONTENT) VALUES (?, ?, ?)", CamelRoute.class.getSimpleName()), new Object[] { routeId, anyTypeKind.name(), routeContent }); LOG.info("[{}] Route successfully loaded: {}", domain, routeId); } } catch (Exception e) { LOG.error("[{}] Route load failed", domain, e); } } }
From source file:org.apache.syncope.core.provisioning.camel.SyncopeCamelContext.java
private void loadContext(final Collection<String> routes) { try {/*from w w w . j a v a 2s .c o m*/ DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance(); DOMImplementationLS domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS"); LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); JAXBContext jaxbContext = JAXBContext.newInstance(Constants.JAXB_CONTEXT_PACKAGES); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); List<RouteDefinition> routeDefs = new ArrayList<>(); for (String route : routes) { try (InputStream input = IOUtils.toInputStream(route, StandardCharsets.UTF_8)) { LSInput lsinput = domImpl.createLSInput(); lsinput.setByteStream(input); Node routeElement = parser.parse(lsinput).getDocumentElement(); routeDefs.add(unmarshaller.unmarshal(routeElement, RouteDefinition.class).getValue()); } } camelContext.addRouteDefinitions(routeDefs); } catch (Exception e) { LOG.error("While loading Camel context {}", e); throw new CamelException(e); } }
From source file:org.betaconceptframework.astroboa.configuration.W3CRelatedSchemaEntityResolver.java
public W3CRelatedSchemaEntityResolver() { try {/*from w ww . j a v a2 s . c o m*/ registry = DOMImplementationRegistry.newInstance(); } catch (Exception e) { throw new CmsException(e); } }
From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java
private void loadSchema(String inputURI) throws java.lang.ClassNotFoundException, java.lang.InstantiationException, java.lang.IllegalAccessException { // Get DOM Implementation using DOM Registry System.setProperty(DOMImplementationRegistry.PROPERTY, "org.apache.xerces.dom.DOMXSImplementationSourceImpl"); DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); Object o = registry.getDOMImplementation("XS-Loader"); if (o instanceof XSImplementation) { XSImplementation impl = (XSImplementation) o; XSLoader schemaLoader = impl.createXSLoader(null); schema = schemaLoader.loadURI(inputURI); } else if (o != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("DOMImplementation is not a XSImplementation: " + o.getClass().getName()); }/*from www.j a v a2 s . c om*/ System.exit(1); } }