List of usage examples for org.dom4j Attribute getValue
String getValue();
From source file:com.cladonia.xml.XMLFormatter.java
License:Mozilla Public License
protected void writePreservedElement(Element element) throws IOException { if (DEBUG)/*from w ww . j av a2 s .c om*/ System.out.println("XMLFormatter.writePreservedElement( " + element + ")"); int size = element.nodeCount(); String qualifiedName = element.getQualifiedName(); boolean previousTrim = format.isTrimText(); boolean previousWrapText = wrapText; format.setTrimText(false); wrapText = false; boolean hasElement = false; boolean hasText = false; // first test to see if this element has mixed content, // if whitespace is significant ... for (int i = 0; i < size; i++) { Node node = element.node(i); if (node instanceof Element) { hasElement = true; } else if (node instanceof Text) { String text = node.getText(); if (text != null && text.trim().length() > 0) { hasText = true; } } } Attribute space = element.attribute("space"); boolean defaultSpace = false; if (space != null) { String prefix = space.getNamespacePrefix(); String value = space.getValue(); // System.out.println( "prefix = "+prefix+" value = "+value); if (prefix != null && "xml".equals(prefix) && "default".equals(value)) { defaultSpace = true; } } writer.write("<"); writer.write(qualifiedName); int previouslyDeclaredNamespaces = namespaceStack.size(); Namespace ns = element.getNamespace(); if (isNamespaceDeclaration(ns)) { namespaceStack.push(ns); writeNamespace(ns); } // Print out additional namespace declarations for (int i = 0; i < size; i++) { Node node = element.node(i); if (node instanceof Namespace) { Namespace additional = (Namespace) node; if (isNamespaceDeclaration(additional)) { namespaceStack.push(additional); writeNamespace(additional); } } } writeAttributes(element); lastOutputNodeType = Node.ELEMENT_NODE; if (size <= 0) { writeEmptyElementClose(qualifiedName); } else { writer.write(">"); if (preserveMixedContent && hasElement && hasText) { // mixed content // System.out.println( "writeMixedElementContent ..."); Node lastNode = writeMixedElementContent(element); } else if (!defaultSpace) { // preserve space // System.out.println( "writePreservedElementContent ..."); Node lastNode = writePreservedElementContent(element); } else { // System.out.println( "writeElementContent ..."); format.setTrimText(isTrimText()); boolean prevWrapText = wrapText; wrapText = true; writeElementContent(element); wrapText = prevWrapText; format.setTrimText(false); } writer.write("</"); writer.write(qualifiedName); writer.write(">"); } // remove declared namespaceStack from stack while (namespaceStack.size() > previouslyDeclaredNamespaces) { namespaceStack.pop(); } lastOutputNodeType = Node.ELEMENT_NODE; format.setTrimText(previousTrim); wrapText = previousWrapText; }
From source file:com.cladonia.xml.XMLFormatter.java
License:Mozilla Public License
/** Writes the attributes of the given element */*from w w w .j ava 2 s .c o m*/ */ // protected void writeAttributes( Element element ) throws IOException { // if (DEBUG) System.out.println( "XMLFormatter.writeAttributes( "+element+")"); // if (indentMixed) { // super.writeAttributes( element); // } else { // I do not yet handle the case where the same prefix maps to // two different URIs. For attributes on the same element // this is illegal; but as yet we don't throw an exception // if someone tries to do this // for ( int i = 0, size = element.attributeCount(); i < size; i++ ) { // Attribute attribute = element.attribute(i); // Namespace ns = attribute.getNamespace(); // if (ns != null && ns != Namespace.NO_NAMESPACE && ns != Namespace.XML_NAMESPACE) { // String prefix = ns.getPrefix(); // String uri = namespaceStack.getURI(prefix); // if (!ns.getURI().equals(uri)) { // output a new namespace declaration // writeNamespace(ns); // namespaceStack.push(ns); // } // } // // writer.write(" "); // writer.write(attribute.getQualifiedName()); // writer.write("=\""); // writeEscapeAttributeEntities(attribute.getValue()); // writer.write("\""); // } //// } // } protected void writeAttribute(Attribute attribute) throws IOException { XAttribute a = (XAttribute) attribute; // if ( attributeOnNewLine) { // ++indentLevel; // // format.setNewlines( true); // format.setIndent( indentString); // // writePrintln(); // indent(); // } else { writer.write(" "); // } writer.write(attribute.getQualifiedName()); writer.write("="); String value = attribute.getValue(); if (format.isTrimText() && value != null && value.trim().length() > 0) { StringTokenizer tokenizer = new StringTokenizer(value); StringBuffer buffer = new StringBuffer(); boolean first = true; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (!first) { buffer.append(" "); } buffer.append(token); first = false; } value = buffer.toString(); } boolean hasQuote = value.indexOf("\"") != -1; if (hasQuote) { writer.write("'"); writeEscapeAttributeEntities(value); writer.write("'"); } else { writer.write("\""); writeEscapeAttributeEntities(value); writer.write("\""); } lastOutputNodeType = Node.ATTRIBUTE_NODE; // reset... // if ( attributeOnNewLine) { // --indentLevel; // // format.setNewlines( false); // format.setIndent( ""); // } }
From source file:com.cladonia.xml.XMLUtilities.java
License:Open Source License
/** * Sets the Schema Location attribute on the root element * * @param document The Exchanger document * @param schemaType The schema type (either schemaLocation or noNamespaceSchemaLocation) * @param namespace The namespace/*from w w w . j ava 2 s . c o m*/ * @param schemaURL The URL or the schema * */ public static void setSchemaLocation(ExchangerDocument document, String schemaType, String namespace, String schemaURL) { schemaURL = URLUtilities.encodeURL(schemaURL); XDocument xdoc = document.getDocument(); Element root = xdoc.getRootElement(); if (schemaType.equals(SCHEMALOCATION)) { Attribute attrNoNS = root.attribute(NOSCHEMALOCATION); if (attrNoNS != null) { root.remove(attrNoNS); } // need to set both namspace and url Attribute attr = root.attribute(SCHEMALOCATION); if (attr == null) { // does the schema instance already exist Namespace ns = root.getNamespaceForURI(SCHEMAINSTANCE); if (ns != null) { String schemaInstancePrefix = ns.getPrefix(); StringBuffer name = new StringBuffer(); name.append(schemaInstancePrefix); name.append(":"); name.append(SCHEMALOCATION); StringBuffer value = new StringBuffer(); value.append(namespace); value.append(" "); value.append(schemaURL); root.addAttribute(name.toString(), value.toString()); } else { root.addNamespace("xsi", SCHEMAINSTANCE); StringBuffer name = new StringBuffer(); name.append("xsi"); name.append(":"); name.append(SCHEMALOCATION); StringBuffer value = new StringBuffer(); value.append(namespace); value.append(" "); value.append(schemaURL); root.addAttribute(name.toString(), value.toString()); } } else { String attrValue = attr.getValue(); // break up all the namespace and url pairs ArrayList stringValues = new ArrayList(); StringTokenizer st = new StringTokenizer(attrValue); while (st.hasMoreTokens()) { stringValues.add(st.nextToken()); } // update existing attribute, Note: it may have multiple attribute pairs StringBuffer value = new StringBuffer(); value.append(namespace); value.append(" "); value.append(schemaURL); //need to start at the third value (i.e we only replace the first namespace-url pair) for (int i = 2; i < stringValues.size(); i++) { value.append(" "); value.append((String) stringValues.get(i)); } attr.setValue(value.toString()); } } else { // is of type "no schema location" Attribute attrSchema = root.attribute(SCHEMALOCATION); if (attrSchema != null) { root.remove(attrSchema); } // just need to set the url Attribute attr = root.attribute(NOSCHEMALOCATION); if (attr == null) { // does the schema instance already exist Namespace ns = root.getNamespaceForURI(SCHEMAINSTANCE); if (ns != null) { String schemaInstancePrefix = ns.getPrefix(); StringBuffer name = new StringBuffer(); name.append(schemaInstancePrefix); name.append(":"); name.append(NOSCHEMALOCATION); root.addAttribute(name.toString(), schemaURL); } else { root.addNamespace("xsi", SCHEMAINSTANCE); StringBuffer name = new StringBuffer(); name.append("xsi"); name.append(":"); name.append(NOSCHEMALOCATION); root.addAttribute(name.toString(), schemaURL); } } else { // update existing attribute attr.setValue(schemaURL); } } }
From source file:com.cladonia.xngreditor.SchemaLocationDialog.java
License:Open Source License
/** * Sets the original values displayed by the dialog, plus what should be enabled\disabled *///from ww w .ja v a2 s . c om private void setCurrentValues() { XDocument xdoc = document.getDocument(); Element ele = xdoc.getRootElement(); Attribute attr = ele.attribute(SCHEMALOCATION); if (attr == null) { // check for no namespace schema Attribute attr2 = ele.attribute(NOSCHEMALOCATION); if (attr2 == null) { // set the defaults schemaButton.setSelected(true); Namespace ns = ele.getNamespace(); if (ns != Namespace.NO_NAMESPACE) { namespaceField.setText(ns.getURI()); } else { namespaceField.setText(""); } urlField.setText(""); } else { // we have a "no namespace schema" schemaNoNSButton.setSelected(true); namespaceField.setText(""); namespaceField.setEnabled(false); namespaceLabel.setEnabled(false); urlField.setText(attr2.getValue()); } } else { // we hava a namepace schema schemaButton.setSelected(true); // we have namespace schema, set the namespace and the URL String attrValue = attr.getValue(); // break up all the namespace and url pairs ArrayList stringValues = new ArrayList(); StringTokenizer st = new StringTokenizer(attrValue); while (st.hasMoreTokens()) { stringValues.add(st.nextToken()); } String namespaceValue = (String) stringValues.get(0); if (namespaceValue != null) { namespaceField.setText(namespaceValue); } else { namespaceField.setText(""); } String urlValue = (String) stringValues.get(1); if (urlValue != null) { urlField.setText(urlValue); } else { urlField.setText(""); } } }
From source file:com.devoteam.srit.xmlloader.core.operations.basic.OperationParameter.java
License:Open Source License
/** * Executes the operation/*from ww w . j a v a 2 s.c o m*/ */ @Override public Operation execute(Runner runner) throws Exception { try { if (runner instanceof ScenarioRunner) { GlobalLogger.instance().getSessionLogger().info(runner, TextEvent.Topic.PARAM, this); } else { GlobalLogger.instance().getApplicationLogger().info(TextEvent.Topic.PARAM, this); } if (this.parameterOperatorName.isDeprecated()) { GlobalLogger.instance().logDeprecatedMessage( "parameter ... operation=\"" + this.parameterOperatorName.getName() + "\" .../", "parameter ... operation=\"" + this.parameterOperatorName.deprecatedBy() + "\" .../"); } String text = ""; if (null != this.getRootElement().getText() && this.getRootElement().getText().trim().length() != 0) { // Replace elements in XMLTree try { lockAndReplace(runner); GlobalLogger.instance().getSessionLogger().debug(runner, TextEvent.Topic.CORE, "Operation after pre-parsing \n", this); text = this.getRootElement().getText(); } finally { unlockAndRestore(); } } /* * Parse the resultant parameter in case it is in format: "[myParam([indexParam])]" to get it in format: "[myParam(10)] */ String resultant = this.resultantAttribute; resultant = ParameterPool.unbracket(resultant); List<String> res = runner.getParameterPool().parse(resultant); if (res.size() != 1) { throw new ParameterException("error parsing resultant, final size is not 1"); } resultant = res.get(0); resultant = ParameterPool.bracket(resultant); /* * Extract the namen level and index (if there is one) of the resultant param - resultantName - resultantIndex (-1 if no index present, will override parameter) - resultantLevel (null if * no level defined, will be current level) */ String resultantName = ParameterPool.getName(resultant); int resultantIndex = -1; if (ParameterPool.hasIndex(resultant)) { resultantIndex = ParameterPool.getIndex(resultant); } /* * Populate the HashMap of operands we will give to the ParameterOperator */ HashMap<String, Parameter> operands = new HashMap<String, Parameter>(); for (Object object : this.getRootElement().attributes()) { Attribute attribute = (Attribute) object; String attributeName = attribute.getName().toLowerCase(); if (attributeName.equals("operation") || attributeName.equals("state") || attributeName.equals("name") || attributeName.equals("editable") || attributeName.equals("description")) { continue; } String attributeValue = attribute.getValue(); /* * The first case gets a parameter or a parameter item while trying to preserve the type of the object saved into the parameter. */ if (Parameter.matchesParameter(attributeValue)) { attributeValue = ParameterPool.unbracket(attributeValue); List<String> aRes = runner.getParameterPool().parse(attributeValue); if (aRes.size() != 1) { throw new ParameterException("error parsing a variable name or index in operands (" + attribute.getValue() + "), final size is not 1"); } attributeValue = aRes.get(0); attributeValue = ParameterPool.bracket(attributeValue); String myParameterName = ParameterPool.getName(attributeValue); int myParameterIndex = -1; if (ParameterPool.hasIndex(attributeValue)) { myParameterIndex = ParameterPool.getIndex(attributeValue); } Parameter parameter; if (runner.getParameterPool().exists(myParameterName)) { parameter = runner.getParameterPool().get(myParameterName); if (-1 != myParameterIndex) { Object myObject = parameter.get(myParameterIndex); parameter = new Parameter(); parameter.add(myObject); } } else { parameter = new Parameter(); parameter.add(attributeValue); } operands.put(attributeName, parameter); } else { LinkedList<String> parsedValue = runner.getParameterPool().parse(attributeValue); Parameter parameter = new Parameter(); for (String value : parsedValue) { parameter.add(value); } operands.put(attributeName, parameter); } } /* * If there is no "value" operand, try to get it from the tag "text()" */ if (null == operands.get("value")) { Parameter parameter = new Parameter(); if (text.length() > 0) { parameter.add(text); operands.put("value", parameter); } } /* * Execute the Parameter operator */ Parameter result = this.parameterOperator.operate(runner, operands, this.operatorAttribute, resultant); if (null == result) { return null; } /* * Go write the result */ if (-1 == resultantIndex) { runner.getParameterPool().set(resultantName, result); } else { if (1 != result.length()) { throw new ParameterException( "we should write the result in one cell, but the size of the result is greater than 1 (!)"); } Parameter param; if (runner.getParameterPool().exists(resultantName)) { param = runner.getParameterPool().get(resultantName); } else { param = new Parameter(); runner.getParameterPool().set(resultantName, param); } param.set(resultantIndex, result.get(0)); } return null; } catch (Exception e) { throw new ParameterException("Error in parameter operation : " + getRootElement().asXML(), e); } }
From source file:com.devoteam.srit.xmlloader.core.utils.XMLElementAVPParser.java
License:Open Source License
public List<Element> replace(Element element, ParameterPool parameterPool) throws Exception { List<Element> result; if (element.getName().equalsIgnoreCase("header") || element.getName().startsWith("send")) { result = xmlElementDefaultParser.replace(element, parameterPool); } else // <avp .../> {/*from w w w . j a v a2 s .c o m*/ LinkedList list = new LinkedList<Element>(); List<Attribute> attributes; attributes = element.attributes(); int allowedParameterLength = -1; boolean hasParameter = false; for (Attribute attribute : attributes) { String value = attribute.getValue(); Matcher matcher = Parameter.pattern.matcher(value); while (matcher.find()) { String variableStr = matcher.group(); if (false == parameterPool.isConstant(variableStr)) { Parameter variable = parameterPool.get(variableStr); hasParameter = true; if (variable != null) { if (allowedParameterLength == -1 || allowedParameterLength == 1) { allowedParameterLength = variable.length(); } else if (variable.length() != 1 && allowedParameterLength != variable.length()) { throw new ExecutionException("Invalid length of variables : a variable of length " + allowedParameterLength + " has been found but " + variableStr + " has a length of " + variable.length()); } } } } } if (!hasParameter) { allowedParameterLength = 1; } for (int i = 0; i < allowedParameterLength; i++) { Element newElement = element.createCopy(); List<Attribute> newElementAttributes; newElementAttributes = newElement.attributes(); for (Attribute newAttribute : newElementAttributes) { String value = newAttribute.getValue(); Pattern pattern = Pattern.compile(Parameter.EXPRESSION); Matcher matcher = pattern.matcher(value); int offset = 0; while (matcher.find()) { String before = value.substring(0, matcher.end() + offset - 1); String after = value.substring(matcher.end() + offset - 1); if (parameterPool.exists(matcher.group())) { int index = i; if (parameterPool.get(matcher.group()).length() == 1) { index = 0; } value = before + "(" + index + ")" + after; offset += ((String) "(" + index + ")").length(); } } newAttribute.setValue(value); } List<Element> tempList = xmlElementDefaultParser.replace(newElement, parameterPool); try { for (Element e : tempList) { // MsgDiameterParser.getInstance().doDictionnary(e, "0", false); list.addAll(xmlElementTextOnlyParser.replace(e, parameterPool)); } } catch (Exception e) { throw new ExecutionException("Error while checking parsed variables against dictionary", e); } } result = list; } return result; }
From source file:com.devoteam.srit.xmlloader.core.utils.XMLElementDefaultParser.java
License:Open Source License
public List<Element> replace(Element element, ParameterPool parameterPool) throws Exception { List<Element> list = new LinkedList<Element>(); Element newElement = element.createCopy(); list.add(newElement);/* w w w . j a v a 2 s . c o m*/ List<Attribute> attributes = newElement.attributes(); for (Attribute attribute : attributes) { String value = attribute.getValue(); LinkedList<String> parsedValue = parameterPool.parse(value); if (parsedValue.size() != 1) { throw new ExecutionException("Invalid size of variables in attribute " + value); } attribute.setValue(parsedValue.getFirst()); } return list; }
From source file:com.devoteam.srit.xmlloader.core.utils.XMLElementRTPFLOWParser.java
License:Open Source License
public List<Element> replace(Element element, ParameterPool parameterPool) throws Exception { List<Element> result = new LinkedList(); //do classic replacement of attribute and save it in result Element newElement = element.createCopy(); result.add(newElement);//from w w w . j a v a 2 s . co m List<Attribute> attributes = newElement.attributes(); for (Attribute attribute : attributes) { if (!attribute.getName().equalsIgnoreCase("timestamp") && !attribute.getName().equalsIgnoreCase("seqnum") && !attribute.getName().equalsIgnoreCase("deltaTime") && !attribute.getName().equalsIgnoreCase("mark")) { String value = attribute.getValue(); LinkedList<String> parsedValue = parameterPool.parse(value); if (parsedValue.size() != 1) { throw new ExecutionException("Invalid size of variables in attribute " + value); } attribute.setValue(parsedValue.getFirst()); } } return result; }
From source file:com.devoteam.srit.xmlloader.core.utils.XMLTree.java
License:Open Source License
private void listMatchingElements(Element element, String regex, boolean recurse) { ///*w w w . j av a2 s.c o m*/ // First check attributes // List<Attribute> namedNodeMap = element.attributes(); if (null != namedNodeMap) { for (Attribute attribute : namedNodeMap) { String value = attribute.getValue(); if (Utils.containsRegex(value, regex)) { if (false == elementsMap.containsKey(element)) { elementsMap.put(element, null); elementsOrder.addFirst(element); } } } } // // Then check text // if (Utils.containsRegex(element.getText(), regex)) { if (false == elementsMap.containsKey(element)) { elementsMap.put(element, null); elementsOrder.addFirst(element); } } // // Finally elements // if (recurse) { List<Element> childrens = element.elements(); for (Element child : childrens) { listMatchingElements(child, regex, recurse); } } }
From source file:com.devoteam.srit.xmlloader.sigtran.fvo.FvoMessage.java
License:Open Source License
public void parseElement(Element root) throws Exception { Element header = (Element) root.selectSingleNode("./header"); Attribute messageTypeValue = (Attribute) root .selectSingleNode("./header/field[@name='Message_Type']/@value"); //header/*from w ww . j ava2 s.c om*/ if (header != null) { _header = new FvoParameter(_msg); _header.setLittleEndian(_dictionary.getHeader().isLittleEndian()); _header.parseElement(header); } //typeCode if (messageTypeValue != null) { try { setMessageType(Integer.decode(messageTypeValue.getValue())); } catch (Exception e) { // TODO: handle exception recherche dans dictionnaire throw e; } } else { throw new ExecutionException("The Message_Type field must be set in the header\n" + root.asXML()); } //parameters parseParametersFromXml(root.selectNodes("./parameter")); }