public void signAssertion(Document samlDocument) throws ProcessingException { Element originalAssertionElement = org.keycloak.saml.common.util.DocumentUtil.getChildElement( samlDocument.getDocumentElement(), new QName( JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get())); if (originalAssertionElement == null) return; Node clonedAssertionElement = originalAssertionElement.cloneNode(true); Document temporaryDocument; try { temporaryDocument = org.keycloak.saml.common.util.DocumentUtil.createDocument(); } catch (ConfigurationException e) { throw new ProcessingException(e); } temporaryDocument.adoptNode(clonedAssertionElement); temporaryDocument.appendChild(clonedAssertionElement); signDocument(temporaryDocument); samlDocument.adoptNode(clonedAssertionElement); Element parentNode = (Element) originalAssertionElement.getParentNode(); parentNode.replaceChild(clonedAssertionElement, originalAssertionElement); }
private Object handeRootElementReplacement( final Object proxy, final Method method, final Document document, final Object valueToSet) { int count = document.getDocumentElement() == null ? 0 : 1; if (valueToSet == null) { DOMHelper.setDocumentElement(document, null); return getProxyReturnValueForMethod(proxy, method, Integer.valueOf(count)); } if (valueToSet instanceof Element) { Element clone = (Element) ((Element) valueToSet).cloneNode(true); document.adoptNode(clone); if (document.getDocumentElement() == null) { document.appendChild(clone); return getProxyReturnValueForMethod(proxy, method, Integer.valueOf(1)); } document.replaceChild(document.getDocumentElement(), clone); return getProxyReturnValueForMethod(proxy, method, Integer.valueOf(1)); } if (!(valueToSet instanceof DOMAccess)) { throw new IllegalArgumentException( "Method " + method + " was invoked as setter changing the document root element. Expected value type was a projection so I can determine a element name. But you provided a " + valueToSet); } DOMAccess projection = (DOMAccess) valueToSet; Element element = projection.getDOMBaseElement(); assert element != null; DOMHelper.setDocumentElement(document, element); return getProxyReturnValueForMethod(proxy, method, Integer.valueOf(count)); }
@Override public void react(SEMAINEMessage m) throws JMSException { if (!(m instanceof SEMAINEXMLMessage)) { throw new MessageFormatException("expected XML message, got " + m.getClass().getSimpleName()); } SEMAINEXMLMessage xm = (SEMAINEXMLMessage) m; boolean isFML = "FML".equals(xm.getDatatype()); if (isFML) { // extract the BML and send that along Element bml = XMLTool.needChildElementByLocalNameNS( xm.getDocument().getDocumentElement(), BML.E_BML, BML.namespaceURI); Document doc = XMLTool.newDocument(BML.E_BML, BML.namespaceURI); doc.adoptNode(bml); doc.replaceChild(bml, doc.getDocumentElement()); bmlSender.sendXML(doc, xm.getUsertime(), xm.getEventType()); } else { // BML -- send as is bmlSender.sendXML(xm.getDocument(), xm.getUsertime(), xm.getEventType()); } }
void doApply( Stylesheet stylesheet, QName mode, Node context, int pos, int len, Node parent, Node nextSibling) throws TransformerException { Node result = null; Document doc = (parent instanceof Document) ? (Document) parent : parent.getOwnerDocument(); short nodeType = source.getNodeType(); if (nodeType == Node.ATTRIBUTE_NODE && parent.getFirstChild() != null) { // Ignore attributes added after child elements } else { // Namespace aliasing if (nodeType == Node.ELEMENT_NODE) { String prefix = source.getPrefix(); if (prefix == null) prefix = "#default"; String resultPrefix = (String) stylesheet.namespaceAliases.get(prefix); if (resultPrefix != null) { if ("#default".equals(resultPrefix)) resultPrefix = null; String uri = source.lookupNamespaceURI(resultPrefix); String name = source.getNodeName(); // Create a new element node in the result document result = doc.createElementNS(uri, name); // copy attributes NamedNodeMap srcAttrs = source.getAttributes(); NamedNodeMap dstAttrs = result.getAttributes(); int l = srcAttrs.getLength(); for (int i = 0; i < l; i++) { Node attr = srcAttrs.item(i); if (!Stylesheet.XSL_NS.equals(attr.getNamespaceURI())) { attr = attr.cloneNode(true); attr = doc.adoptNode(attr); dstAttrs.setNamedItemNS(attr); } } } } if (result == null) { // Create result node result = source.cloneNode(false); // Remove any XSL attributes NamedNodeMap attrs = result.getAttributes(); if (attrs != null) { int l = attrs.getLength(); for (int i = 0; i < l; i++) { Node attr = attrs.item(i); if (Stylesheet.XSL_NS.equals(attr.getNamespaceURI())) { attrs.removeNamedItem(attr.getNodeName()); i--; l--; } } } Node result2 = doc.adoptNode(result); if (result2 == null) { String msg = "Error adopting node to result tree: " + result + " (" + result.getClass().getName() + ")"; DOMSourceLocator l = new DOMSourceLocator(context); throw new TransformerException(msg, l); } result = result2; } if (nextSibling != null) parent.insertBefore(result, nextSibling); else parent.appendChild(result); if (nodeType == Node.ELEMENT_NODE) stylesheet.addNamespaceNodes(source, result, doc, elementExcludeResultPrefixes); // children if (children != null) children.apply(stylesheet, mode, context, pos, len, result, null); } // next sibling if (next != null) next.apply(stylesheet, mode, context, pos, len, parent, nextSibling); }
@Override public Document clean(Reader originalHtmlContent, HTMLCleanerConfiguration configuration) { Document result; // Note: Instantiation of an HtmlCleaner object is cheap so there's no need to cache an instance // of it, // especially since this makes it extra safe with regards to multithreading (even though HTML // Cleaner is // already supposed to be thread safe). CleanerProperties cleanerProperties = getDefaultCleanerProperties(configuration); HtmlCleaner cleaner = new HtmlCleaner(cleanerProperties); cleaner.setTransformations(getDefaultCleanerTransformations(configuration)); TagNode cleanedNode; try { cleanedNode = cleaner.clean(originalHtmlContent); } catch (Exception e) { // This shouldn't happen since we're not doing any IO... I consider this a flaw in the design // of HTML // Cleaner. throw new RuntimeException("Unhandled error when cleaning HTML", e); } // Serialize the cleanedNode TagNode into a w3c dom. Ideally following code should be enough. // But SF's HTML Cleaner seems to omit the DocType declaration while serializing. // See // https://sourceforge.net/tracker/index.php?func=detail&aid=2062318&group_id=183053&atid=903696 // cleanedNode.setDocType(new DoctypeToken("html", "PUBLIC", "-//W3C//DTD XHTML 1.0 // Strict//EN", // "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd")); // try { // result = new DomSerializer(cleanerProperties, false).createDOM(cleanedNode); // } catch(ParserConfigurationException ex) { } // As a workaround, we must serialize the cleanedNode into a temporary w3c document, create a // new w3c document // with proper DocType declaration and move the root node from the temporary document to the new // one. try { // Since there's a bug in SF's HTML Cleaner in that it doesn't recognize CDATA blocks we need // to turn off // character escaping (hence the false value passed) and do the escaping in // XMLUtils.toString(). Note that // this can cause problem for code not serializing the W3C DOM to a String since it won't have // the // characters escaped. // See // https://sourceforge.net/tracker/index.php?func=detail&aid=2691888&group_id=183053&atid=903696 Document tempDoc = new XWikiDOMSerializer(cleanerProperties, false).createDOM(cleanedNode); DOMImplementation domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation(); DocumentType docType = domImpl.createDocumentType( QUALIFIED_NAME_HTML, "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"); result = domImpl.createDocument(null, QUALIFIED_NAME_HTML, docType); result.replaceChild( result.adoptNode(tempDoc.getDocumentElement()), result.getDocumentElement()); } catch (ParserConfigurationException ex) { throw new RuntimeException("Error while serializing TagNode into w3c dom.", ex); } // Finally apply filters. for (HTMLFilter filter : configuration.getFilters()) { filter.filter(result, configuration.getParameters()); } return result; }
private void enviarFicheroUnidadEnPorciones(EnvioErroneo envio, Document doc, Element unidad) throws TransformerException { // Creamos un nuevo nodo de unidad Element nuevaUnidad = doc.createElement("UNIDAD"); doc.getElementsByTagName("UNIDADES").item(0).appendChild(nuevaUnidad); // Le añadimos los parámetros Node xUnidad = unidad.getElementsByTagName("X_UNIDAD").item(0).cloneNode(true); doc.adoptNode(xUnidad); String codUnidad = xUnidad.getTextContent(); Node xNombre = unidad.getElementsByTagName("T_NOMBRE").item(0).cloneNode(true); doc.adoptNode(xNombre); nuevaUnidad.appendChild(xUnidad); nuevaUnidad.appendChild(xNombre); // Ahora añadimos los alumnos Element alumnos = doc.createElement("ALUMNOS"); nuevaUnidad.appendChild(alumnos); // Y vamos creando un fichero por cada alumno NodeList nl = unidad.getElementsByTagName("ALUMNOS").item(0).getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Object obj = nl.item(i); if (!(obj instanceof Element)) { continue; } Element al = (Element) obj; al = (Element) al.cloneNode(true); // Clonamos el documento Document docAlumno = (Document) doc.cloneNode(true); docAlumno.adoptNode(al); // Y le añadimos el docAlumno.getElementsByTagName("ALUMNOS").item(0).appendChild(al); // Guardamos el archivo y lo enviamos String contenido = docToString(docAlumno); File tmp = new File(getCarpetaFallidos(), "tmp_unidad_" + codUnidad + "_" + i + ".xml"); Archivo.setContenido(contenido, "latin1", tmp, false); String codigoOperacion = Cripto.md5(tmp.getName() + "" + Math.random()); int ret = enviarFichero(tmp, codigoOperacion); if (ret == GestorEnvioFaltas.RET_ERROR_PROCESANDO) { envio.getErroneos().add(tmp); // Cogemos el dato X_MATRICULA String datoMatricula = al.getElementsByTagName("X_MATRICULA").item(0).getTextContent(); Alumno a = Alumno.getAlumnoDesdeCodFaltas(datoMatricula); if (a != null) { AlumnoEnvioErroneo aee = new AlumnoEnvioErroneo(a); envio.getAlumnosFallidos().add(aee); // Ahora tenemos que localizar las fechas distintas donde falla NodeList nlf = al.getElementsByTagName("F_FALASI"); ArrayList<String> fechas = new ArrayList<String>(); for (int x = 0; x < nlf.getLength(); x++) { String sFecha = nlf.item(x).getTextContent(); if (!fechas.contains(sFecha)) { fechas.add(sFecha); } } aee.setInfo(Str.implode(fechas, "; ")); } } else if (ret == GestorEnvioFaltas.RET_ERROR_ENVIANDO) { envio.getFallidos().add(tmp); } else { tmp.delete(); } } }
public void enviarFicheroGeneralEnPorciones(EnvioErroneo envio) { try { // Tenemos que dividir el archivo por cursos y unidades DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(false); documentBuilderFactory.setValidating(false); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); File tmpX = new File(getCarpetaFallidos(), envio.getFicheroEnvio().getName() + ".tmp"); Archivo.setContenido( Archivo.getContenido(envio.getFicheroEnvio(), "latin1"), "UTF-8", tmpX, false); Document doc = documentBuilder.parse(tmpX); tmpX.delete(); // Ahore recorremos el documento generando un archivo nuevo por cada version Node nCursos = doc.getElementsByTagName("CURSOS").item(0); Node datosGenerales = doc.getElementsByTagName("DATOS_GENERALES").item(0); NodeList cursos = nCursos.getChildNodes(); for (int i = 0; i < cursos.getLength(); i++) { Object obj = cursos.item(i); if (!(obj instanceof Element)) { continue; } Element cursoActual = (Element) obj; // Creamos un nuevo documento Document nuevoDoc = documentBuilder.newDocument(); // Le añadimos un nodo de servicio Node servicio = nuevoDoc.createElement("SERVICIO"); nuevoDoc.appendChild(servicio); // A este le añadimos los datos generales (clonados) Node nuevoDatosGenerales = datosGenerales.cloneNode(true); nuevoDoc.adoptNode(nuevoDatosGenerales); servicio.appendChild(nuevoDatosGenerales); // Creamos un nodo de cursos y se lo añadimos Node nuevoCursos = nuevoDoc.createElement("CURSOS"); servicio.appendChild(nuevoCursos); // Creamos un nodo de curso y se lo añadimos Node nuevoCurso = nuevoDoc.createElement("CURSO"); nuevoCursos.appendChild(nuevoCurso); // Le añadimos los datos al curso Node el1 = cursoActual.getElementsByTagName("X_OFERTAMATRIG").item(0).cloneNode(true); nuevoDoc.adoptNode(el1); String nombreCurso = el1.getTextContent(); Node el2 = cursoActual.getElementsByTagName("D_OFERTAMATRIG").item(0).cloneNode(true); nuevoDoc.adoptNode(el2); nuevoCurso.appendChild(el1); nuevoCurso.appendChild(el2); // Creamos un nodo de unidades y se lo añadimos Node nuevoUnidades = nuevoDoc.createElement("UNIDADES"); nuevoCurso.appendChild(nuevoUnidades); // Ahora recorremos las unidades creando un documento nuevo por cada una Element nodoUnidadesActual = (Element) cursoActual.getElementsByTagName("UNIDADES").item(0); NodeList unidades = nodoUnidadesActual.getChildNodes(); for (int x = 0; x < unidades.getLength(); x++) { Node nObj = unidades.item(x); if (!(nObj instanceof Element)) { continue; } // Clonamos la unidad Node unidad = nObj.cloneNode(true); // Clonamos el documento completo Document docActual = (Document) nuevoDoc.cloneNode(true); // Adoptamos el nodo creado docActual.adoptNode(unidad); // Y se lo añadimos a las unidades docActual.getElementsByTagName("UNIDADES").item(0).appendChild(unidad); // Guardamos el documento y lo enviamos String contenido = docToString(docActual); File tmp = new File(getCarpetaFallidos(), "tmp_curso_" + nombreCurso + "_" + x + ".xml"); Archivo.setContenido(contenido, "latin1", tmp, false); String codigoOperacion = Cripto.md5(tmp.getName() + "" + Math.random()); int ret = enviarFichero(tmp, codigoOperacion); if (ret == GestorEnvioFaltas.RET_ERROR_PROCESANDO) { tmp.delete(); // Sobre ese archivo tenemos que hacer envíos alumno por alumno // Clonamos el documento docActual = (Document) nuevoDoc.cloneNode(true); // Y procesamos el envío enviarFicheroUnidadEnPorciones(envio, docActual, (Element) unidad); } else if (ret == GestorEnvioFaltas.RET_ERROR_ENVIANDO) { envio.getFallidos().add(tmp); } else { tmp.delete(); } } } } catch (Exception ex) { Logger.getLogger(GeneradorFicherosSeneca.class.getName()).log(Level.SEVERE, null, ex); } }