public IXArchElement cloneElement(int depth) { synchronized (DOMUtils.getDOMLock(elt)) { Document doc = elt.getOwnerDocument(); if (depth == 0) { Element cloneElt = (Element) elt.cloneNode(false); cloneElt = (Element) doc.importNode(cloneElt, true); AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt); cloneImpl.setXArch(getXArch()); return cloneImpl; } else if (depth == 1) { Element cloneElt = (Element) elt.cloneNode(false); cloneElt = (Element) doc.importNode(cloneElt, true); AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt); cloneImpl.setXArch(getXArch()); NodeList nl = elt.getChildNodes(); int size = nl.getLength(); for (int i = 0; i < size; i++) { Node n = nl.item(i); Node cloneNode = (Node) n.cloneNode(false); cloneNode = doc.importNode(cloneNode, true); cloneElt.appendChild(cloneNode); } return cloneImpl; } else /* depth = infinity */ { Element cloneElt = (Element) elt.cloneNode(true); cloneElt = (Element) doc.importNode(cloneElt, true); AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt); cloneImpl.setXArch(getXArch()); return cloneImpl; } } }
private void parseQuestDropList(Node dropList, String questID) throws NullPointerException { if (DEBUG) _log.info("Parsing Droplist."); for (Node node = dropList.getFirstChild(); node != null; node = node.getNextSibling()) { if (isNodeName(node, "DROP")) { parseQuestDrop(node.cloneNode(true), questID); } } }
/** * Get style from parent node. from first paret 'firstF', we will traverse the tree up untile * reaching Document node, get all style node's, we may insert rules here to stop the search at a * before paricular node. Style nodes could <b>, <u>... * * @param children * @param firstF */ void assignFather(Vector children, Node firstF) { if (children.size() == 0) { return; } if (firstF != null && !isDocument(firstF)) { String name = firstF.getNodeName(); // To see whether it is a style node that is our anticipated node. if (name != null && HTML_STYLE_NODES.contains(name.toLowerCase())) { Node newParent = firstF.cloneNode(false); while (children.size() > 0) { newParent.appendChild((Node) children.remove(0)); } children.add(newParent); } assignFather(children, firstF.getParentNode()); } }
@Override public void parseScript(Node questNode, ScriptContext context) { if (DEBUG) _log.info("Parsing Quest."); String questID = attribute(questNode, "ID"); for (Node node = questNode.getFirstChild(); node != null; node = node.getNextSibling()) { if (isNodeName(node, "DROPLIST")) { parseQuestDropList(node.cloneNode(true), questID); } else if (isNodeName(node, "DIALOG WINDOWS")) { // parseDialogWindows(node.cloneNode(true)); } else if (isNodeName(node, "INITIATOR")) { // parseInitiator(node.cloneNode(true)); } else if (isNodeName(node, "STATE")) { // parseState(node.cloneNode(true)); } } }
/** * Transform the DOM tree using the configuration. * * @param configuration the transformation configuration. * @param doc the DOM tree to be updated. */ protected void applyTransformation(XmlConfiguration configuration, Document doc) { List<Parameter> parameters = configuration.getParameters(); for (Parameter parameter : parameters) { displayMessageln("\t" + parameter.getKey() + " (mode:" + parameter.getMode() + ")"); Node rootXpathNode = getMatchingNode(parameter.getKey(), doc); if (rootXpathNode != null) { for (Value value : parameter.getValues()) { switch (value.getMode()) { case XmlTreeHandler.MODE_INSERT: { createNewNode(doc, rootXpathNode, value); } break; case XmlTreeHandler.MODE_DELETE: { Node deletedNode = getMatchingNode(value.getLocation(), rootXpathNode); rootXpathNode.removeChild(deletedNode); } break; case XmlTreeHandler.MODE_UPDATE: { Node oldNode = getMatchingNode(value.getLocation(), rootXpathNode); if (oldNode == null) { createNewNode(doc, rootXpathNode, value); } else { if (rootXpathNode.equals(oldNode)) { rootXpathNode = rootXpathNode.getParentNode(); } Node newNode = oldNode.cloneNode(true); if (oldNode instanceof Element) { ((Element) newNode).setTextContent(value.getValue()); rootXpathNode.replaceChild(newNode, oldNode); } else { ((Attr) newNode).setValue(value.getValue()); rootXpathNode.getAttributes().setNamedItem(newNode); } } break; } } } } } }
/** * Decodes the given XML node. The optional "into" argument specifies an existing object to be * used. If no object is given, then a new instance is created using the constructor from the * codec. * * <p>The function returns the passed in object or the new instance if no object was given. * * @param node XML node to be decoded. * @param into Optional object to be decodec into. * @return Returns an object that represents the given node. */ public Object decode(Node node, Object into) { Object obj = null; if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { mxObjectCodec codec = mxCodecRegistry.getCodec(node.getNodeName()); try { if (codec != null) { obj = codec.decode(this, node, into); } else { obj = node.cloneNode(true); ((Element) obj).removeAttribute("as"); } } catch (Exception e) { System.err.println("Cannot decode " + node.getNodeName() + ": " + e.getMessage()); e.printStackTrace(); } } return obj; }
/** * Constructs an overview-node in the pre-html where all steps are described. Also, information * about valid and non-valid form-schema's are placed in the steps-overview. * * <p>The node looks like this: * * <pre> * <steps-validator valid="false" allowsave="false" allowcancel="true"> * <step form-schema="schema-id" valid="true" /> * <step form-schema="schema-id" valid="false" /> * </steps-validator> * </pre> * * THis method creates a steps-overview which can be used by the html to show what forms are valid * and what are not. * * @param prehtml the prehtml data node * @param schema the original wizardschema */ public static void createStepsOverview(Document prehtml, Document schema) { // remove a "steps-validator" node if it exists. Node overview = Utils.selectSingleNode(prehtml, "/*/steps-overview"); if (overview != null) prehtml.getDocumentElement().removeChild(overview); // create new overview node overview = prehtml.createElement("steps-validator"); Utils.setAttribute(overview, "allowcancel", "true"); int invalidforms = 0; // iterate through all defined steps NodeList steps = Utils.selectNodeList(schema, "/*/steps/step"); for (int i = 0; i < steps.getLength(); i++) { Node step = steps.item(i); String schemaid = Utils.getAttribute(step, "form-schema", ""); if (!schemaid.equals("")) { // find the referred form and check if the form is valid. Node form = Utils.selectSingleNode(prehtml, "/*/form[@id='" + schemaid + "']"); if (form != null) { Node validationerror = Utils.selectSingleNode(form, ".//field/validator[@valid='false']"); boolean valid = (validationerror == null); // copy step information to overview node and store validation results. Node newstep = prehtml.importNode(step.cloneNode(true), true); overview.appendChild(newstep); Utils.setAttribute(newstep, "valid", valid + ""); if (!valid) invalidforms++; } } } // store global information about validationresults Utils.setAttribute(overview, "allowsave", (invalidforms == 0) + ""); Utils.setAttribute(overview, "valid", (invalidforms == 0) + ""); // store new overview node in the prehtml. prehtml.getDocumentElement().appendChild(overview); }
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); }
public void doLoad(Widget frmModel, JXPathContext jctx) throws BindingException { // (There should be a general widget type checker for all the bindings to use, // coupled with a general informative exception class to throw if the widget is // of the wrong type or null.) Repeater repeater = (Repeater) selectWidget(frmModel, this.repeaterId); if (repeater == null) { String fullId = frmModel.getRequestParameterName(); if (fullId == null || fullId.length() == 0) { fullId = ""; } else { fullId = fullId + "."; } throw new RuntimeException( "TempRepeaterJXPathBinding: Repeater \"" + fullId + this.repeaterId + "\" does not exist (" + frmModel.getLocation() + ")"); } // Start by clearing the repeater, if necessary. if (this.clearOnLoad) { repeater.clear(); } // Find the location of the repeater data. Pointer repeaterPointer = jctx.getPointer(this.repeaterPath); // Check if there is data present. // // (Otherwise, should we check the leniency config option // to decide whether to be silent or throw an exception?) if (repeaterPointer != null) { // Narrow to repeater context. JXPathContext repeaterContext = jctx.getRelativeContext(repeaterPointer); // Build a jxpath iterator for the repeater row pointers. Iterator rowPointers = repeaterContext.iteratePointers(this.rowPath); // Iterate through the rows of data. int rowNum = 0; while (rowPointers.hasNext()) { // Get or create a row widget. Repeater.RepeaterRow thisRow; if (repeater.getSize() > rowNum) { thisRow = repeater.getRow(rowNum); } else { thisRow = repeater.addRow(); } rowNum++; // Narrow to the row context. Pointer rowPointer = (Pointer) rowPointers.next(); JXPathContext rowContext = repeaterContext.getRelativeContext(rowPointer); // If virtual rows are requested, place a deep clone of the row data // into a temporary node, and narrow the context to this virtual row. // // (A clone of the data is used to prevent modifying the source document. // Otherwise, the appendChild method would remove the data from the source // document. Is this protection worth the penalty of a deep clone?) // // (This implementation of virtual rows currently only supports DOM // bindings, but could easily be extended to support other bindings.) if (virtualRows) { Node repeaterNode = (Node) repeaterPointer.getNode(); Node virtualNode = repeaterNode.getOwnerDocument().createElementNS(null, "virtual"); Node node = (Node) rowPointer.getNode(); Node clone = node.cloneNode(true); Node fakeDocElement = node.getOwnerDocument().getDocumentElement().cloneNode(false); virtualNode.appendChild(clone); fakeDocElement.appendChild(virtualNode); rowContext = JXPathContext.newContext(repeaterContext, fakeDocElement); rowContext = rowContext.getRelativeContext(rowContext.getPointer("virtual")); } // Finally, perform the load row binding. this.rowBinding.loadFormFromModel(thisRow, rowContext); } } if (getLogger().isDebugEnabled()) getLogger().debug("done loading rows " + this); }
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); } }
public Object put(Object key, Object value) { try { if (key.toString().equalsIgnoreCase("XmlNsPrefix")) { String oldPrefix = null; try { oldPrefix = nodeData.getPrefix(); } catch (DOMException ex) { // Just log it com.nary.Debug.printStackTrace(ex); } nodeData.setPrefix(((cfData) value).toString()); return oldPrefix; } else if (key.toString().equalsIgnoreCase("XmlNsURI")) { // Do nothing return null; } else if (key.toString().equalsIgnoreCase("XmlText") || key.toString().equalsIgnoreCase("XmlCData")) { boolean isCDATA = key.toString().equalsIgnoreCase("XmlCData"); // Remove all text and CDATA nodes, and add 1 new one at the top remove("XmlText"); remove("XmlCData"); if (!((cfData) value).toString().trim().equals("")) { Node t = null; if (isCDATA) t = nodeData.getOwnerDocument().createCDATASection(((cfData) value).toString()); else t = nodeData.getOwnerDocument().createTextNode(((cfData) value).toString()); nodeData.insertBefore(t, nodeData.getFirstChild()); } nodeData.normalize(); return null; } else if (key.toString().equalsIgnoreCase("XmlComment")) { // Remove all comment nodes, and add 1 new one at the top remove(key); if (!((cfData) value).toString().trim().equals("")) { Comment c = nodeData.getOwnerDocument().createComment(((cfData) value).toString()); nodeData.insertBefore(c, nodeData.getFirstChild()); } nodeData.normalize(); return null; } else if (key.toString().equalsIgnoreCase("XmlAttributes")) { // Overwrite any existing xml attributes with these new ones if (value instanceof cfStructData) { cfXmlDataAttributeStruct attribs = (cfXmlDataAttributeStruct) getXmlAttributes(); cfStructData attribsToAdd = (cfStructData) value; Object[] keys = attribsToAdd.keys(); for (int i = 0; i < keys.length; i++) { String str = keys[i].toString(); cfData valueData = attribsToAdd.getData(str); attribs.setData(str, valueData); } } return null; } else if (key.toString().equalsIgnoreCase("XmlChildren")) { // Do nothing return null; } else if (key.toString().equalsIgnoreCase("XmlParent")) { // Do nothing return null; } else if (key.toString().equalsIgnoreCase("XmlNodes")) { // Do nothing return null; } else { if (value instanceof cfXmlData) { Node n = ((cfXmlData) value).getXMLNode(); if (n.getParentNode() != null) n = n.cloneNode(true); cfData d = (cfData) get(key); if (d != null) { if (d instanceof cfXmlData) return nodeData.replaceChild(n, ((cfXmlData) d).getXMLNode()); else if (d instanceof cfXmlDataArray) ((cfXmlDataArray) d) .setData(1, new cfXmlData(n, ((cfXmlData) value).isCaseSensitive())); } else { nodeData.appendChild(n); } nodeData.normalize(); } else if (value instanceof cfStructData) { Element e = nodeData.getOwnerDocument().createElement((String) key); nodeData.appendChild(e); buildParentElement((cfStructData) value, e); nodeData.normalize(); } else if (value instanceof cfStringData) { if (((cfData) value).toString().trim().equals("")) { cfData d = (cfData) get(key); if (d != null) { if (d instanceof cfXmlData) nodeData.removeChild(((cfXmlData) d).getXMLNode()); else if (d instanceof cfXmlDataArray) ((cfXmlDataArray) d).removeAllElements(); nodeData.normalize(); } } } else { super.put(key, value); } return null; } } catch (cfmRunTimeException ex) { // Nothing else we can do here com.nary.Debug.printStackTrace(ex); } catch (DOMException ex) { // Nothing else we can do here com.nary.Debug.printStackTrace(ex); } return null; }