List of usage examples for org.dom4j Document add
void add(Node node);
Node
or throws IllegalAddException if the given node is not of a valid type. From source file:at.jabberwocky.impl.core.io.PacketReader.java
private Document parseDocument() throws DocumentException, IOException, XmlPullParserException { DocumentFactory df = docFactory;// www. ja v a 2 s . c o m Document document = df.createDocument(); Element parent = null; XmlPullParser pp = parser; int count = 0; while (true) { int type = -1; type = pp.nextToken(); switch (type) { case XmlPullParser.PROCESSING_INSTRUCTION: { String text = pp.getText(); int loc = text.indexOf(" "); if (loc >= 0) { document.addProcessingInstruction(text.substring(0, loc), text.substring(loc + 1)); } else { document.addProcessingInstruction(text, ""); } break; } case XmlPullParser.COMMENT: { if (parent != null) { parent.addComment(pp.getText()); } else { document.addComment(pp.getText()); } break; } case XmlPullParser.CDSECT: { String text = pp.getText(); if (parent != null) { parent.addCDATA(text); } else { if (text.trim().length() > 0) { throw new DocumentException("Cannot have text content outside of the root document"); } } break; } case XmlPullParser.ENTITY_REF: { String text = pp.getText(); if (parent != null) { parent.addText(text); } else { if (text.trim().length() > 0) { throw new DocumentException("Cannot have an entityref outside of the root document"); } } break; } case XmlPullParser.END_DOCUMENT: { return document; } case XmlPullParser.START_TAG: { QName qname = (pp.getPrefix() == null) ? df.createQName(pp.getName(), pp.getNamespace()) : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace()); Element newElement = null; // Do not include the namespace if this is the start tag of a new packet // This avoids including "jabber:client", "jabber:server" or // "jabber:component:accept" if ("jabber:client".equals(qname.getNamespaceURI()) || "jabber:server".equals(qname.getNamespaceURI()) || "jabber:component:accept".equals(qname.getNamespaceURI()) || "http://jabber.org/protocol/httpbind".equals(qname.getNamespaceURI())) { newElement = df.createElement(pp.getName()); } else { newElement = df.createElement(qname); } int nsStart = pp.getNamespaceCount(pp.getDepth() - 1); int nsEnd = pp.getNamespaceCount(pp.getDepth()); for (int i = nsStart; i < nsEnd; i++) { if (pp.getNamespacePrefix(i) != null) { newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i)); } } for (int i = 0; i < pp.getAttributeCount(); i++) { QName qa = (pp.getAttributePrefix(i) == null) ? df.createQName(pp.getAttributeName(i)) : df.createQName(pp.getAttributeName(i), pp.getAttributePrefix(i), pp.getAttributeNamespace(i)); newElement.addAttribute(qa, pp.getAttributeValue(i)); } if (parent != null) { parent.add(newElement); } else { document.add(newElement); } parent = newElement; count++; break; } case XmlPullParser.END_TAG: { if (parent != null) { parent = parent.getParent(); } count--; if (count < 1) { return document; } break; } case XmlPullParser.TEXT: { String text = pp.getText(); if (parent != null) { parent.addText(text); } else { if (text.trim().length() > 0) { throw new DocumentException("Cannot have text content outside of the root document"); } } break; } default: } } }
From source file:bio.pih.genoogle.io.Output.java
public static Element genoogleXmlHeader() { DocumentFactory factory = DocumentFactory.getInstance(); Document doc = factory.createDocument(); doc.setName("genoogle"); Map<String, String> xslProcessing = Maps.newHashMap(); xslProcessing.put("type", "text/xsl"); xslProcessing.put("href", "results.xsl"); ProcessingInstruction xsltInstruction = DocumentHelper.createProcessingInstruction("xml-stylesheet", xslProcessing);/*from w w w . ja v a2 s .c o m*/ doc.add(xsltInstruction); Element output = doc.addElement("genoogle"); output.addElement("references").addAttribute("program", Genoogle.SOFTWARE_NAME) .addAttribute("version", Double.toString(Genoogle.VERSION)) .addAttribute("copyright", Genoogle.COPYRIGHT); return output; }
From source file:com.chingo247.structureapi.plan.io.export.StructurePlanExporter.java
License:Open Source License
public void export(IStructurePlan plan, File destinationDirectory, String fileName, boolean prettyPrint) throws IOException, UnsupportedPlacementException { Preconditions.checkArgument(destinationDirectory.isDirectory()); IPlacement placement = plan.getPlacement(); if (!(placement instanceof IExportablePlacement)) { throw new UnsupportedPlacementException("Placement does not implement IWriteablePlacement"); }//from w w w.j ava2 s.c om Document d = DocumentHelper.createDocument(); Element root = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_ROOT_ELEMENT); d.add(root); Element nameElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_NAME_ELEMENT); nameElement.setText(plan.getName()); root.add(nameElement); Element priceElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_PRICE_ELEMENT); priceElement.setText(String.valueOf(plan.getPrice())); root.add(priceElement); Element categoryElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_CATEGORY_ELEMENT); categoryElement.setText(plan.getCategory() == null ? "None" : plan.getCategory()); root.add(categoryElement); Element descriptionElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_DESCRIPTION_ELEMENT); descriptionElement.setText(plan.getDescription() == null ? "None" : plan.getDescription()); root.add(descriptionElement); Element placementElement = PlacementAPI.getInstance().handle((IExportablePlacement) plan.getPlacement()); root.add(placementElement); // if (plan instanceof SubStructuresPlan) { // SubStructuresPlan ssp = (SubStructuresPlan) plan; // // Element substructuresElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_SUBSTRUCTURES); // root.add(substructuresElement); // // for(Placement p : ssp.getSubPlacements()) { // try { // Element e = PlacementAPI.getInstance().handle(p); // e.setName(StructurePlanXMLConstants.STRUCTURE_PLAN_SUBSTRUCTURE); // substructuresElement.add(e); // } catch (PlacementException ex) { // System.err.println(ex.getMessage()); // } // } // // int index = 0; // for(StructurePlan p : ssp.getSubStructurePlans()) { // File exportPlan = new File(destinationDirectory, p.getFile().getName() + "-" + index); // // try { // export(plan, destinationDirectory, exportPlan.getName(), prettyPrint); // } catch (Exception e){ // continue; // } // // Element substructureElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_SUBSTRUCTURE); // // // TODO add position + direction // // Element typeElement = new BaseElement(PlacementXMLConstants.PLACEMENT_TYPE_ELEMENT); // typeElement.setText(PlacementTypes.EMBEDDED); // substructureElement.add(typeElement); // // Element pathElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_RELATIVE_PATH_ELEMENT); // pathElement.setText(exportPlan.getName()); // substructureElement.add(pathElement); // // substructuresElement.add(substructureElement); // // } // // } OutputFormat format; if (prettyPrint) { format = OutputFormat.createPrettyPrint(); } else { format = OutputFormat.createCompactFormat(); } XMLWriter writer = new XMLWriter(new FileWriter(new File(destinationDirectory, fileName)), format); writer.write(d); writer.close(); }
From source file:com.chingo247.structureapi.plan.PlanGenerator.java
License:Open Source License
private static void generatePlanFromSchematic(File file, File rootDirectory) throws IOException { String name = FilenameUtils.getBaseName(file.getName()); File directory = file.getParentFile(); Document d = DocumentHelper.createDocument(); Element root = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_ROOT_ELEMENT); d.add(root); Element nameElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_NAME_ELEMENT); nameElement.setText(name);/* ww w . j av a2 s.c o m*/ root.add(nameElement); Element priceElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_PRICE_ELEMENT); priceElement.setText("0"); root.add(priceElement); Element description = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_DESCRIPTION_ELEMENT); description.setText("None"); root.add(description); Element categoryElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_CATEGORY_ELEMENT); String category = rootDirectory.getName().equals(directory.getName()) ? "Default" : directory.getName(); categoryElement.setText(category); root.add(categoryElement); Element placementElment = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_PLACEMENT); Element typeElement = new BaseElement(PlacementXMLConstants.TYPE_ELEMENT); typeElement.setText(PlacementTypes.SCHEMATIC); Element schematicElement = new BaseElement(PlacementXMLConstants.SCHEMATIC_ELEMENT); schematicElement.setText(file.getName()); placementElment.add(typeElement); placementElment.add(schematicElement); root.add(placementElment); File planFile = new File(directory, name + ".xml"); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(planFile), format); writer.write(d); writer.close(); }
From source file:com.flaptor.hounder.indexer.DocumentConverter.java
License:Apache License
/** * @todo refactor this method, is too long *//*from www .ja v a2 s. co m*/ private org.apache.lucene.document.Document processAdd(final Element e) throws IllegalDocumentException { // TODO: This method is too long, refactor. logger.debug("Processing Add"); float documentBoost; Node node = e.selectSingleNode("boost"); if (null == node) { documentBoost = 1.0F; } else { documentBoost = Float.parseFloat(node.getText()); if (logger.isEnabledFor(Level.DEBUG)) { logger.debug("Using non-default document boost of " + documentBoost); } } if (Float.isNaN(documentBoost) || Float.isInfinite(documentBoost) || documentBoost <= 0) { throw new IllegalDocumentException("Document with invalid boost (" + documentBoost + ") received."); } org.apache.lucene.document.Document ldoc = new org.apache.lucene.document.Document(); ldoc.setBoost(documentBoost); // For comparison with the required fields we keep track of the added // fields. HashSet<String> providedFields = new HashSet<String>(); //First, we add the documentId as a field under the name provided in the configuration (docIdName) node = e.selectSingleNode("documentId"); if (null == node) { throw new IllegalDocumentException("Add document missing documentId."); } String docIdText = node.getText(); //now we add the documentId as another field, using the name provided in the configuration (docIdName) Field lfield = new Field(docIdName, docIdText, Field.Store.YES, Field.Index.NOT_ANALYZED); ldoc.add(lfield); providedFields.add(docIdName); if (logger.isEnabledFor(Level.DEBUG)) { logger.debug("Writer - adding documentId field:" + docIdName + ", index: true, store: true, token: false, text: " + docIdText); } // Now we add the regular fields for (Iterator iter = e.elementIterator("field"); iter.hasNext();) { Element field = (Element) iter.next(); String fieldName, storedS, indexedS, tokenizedS, boostS, fieldText; boolean stored, tokenized, indexed; float boost = 1; fieldName = field.valueOf("@name"); if (fieldName.equals("")) { throw new IllegalDocumentException("Field without name."); } //There cannot be a field with the name used to store the documentId (docIdName) //as it would collide with the documentId per se when saved to the lucene index. fieldText = field.getText(); if (fieldName.equals(docIdName)) { throw new IllegalDocumentException( "This document contains a field with the same name as the configured name " + "to save the documentId( " + docIdName + ")."); } storedS = field.valueOf("@stored"); if (storedS.equals("")) { throw new IllegalDocumentException("Field without stored attribute."); } stored = Boolean.valueOf(storedS); indexedS = field.valueOf("@indexed"); if (indexedS.equals("")) { throw new IllegalDocumentException("Field without indexed attribute."); } indexed = Boolean.valueOf(indexedS); //Lucene complains of an unindexed unstored field with a runtime exception //and it makes no sense anyway if (!(indexed || stored)) { throw new IllegalDocumentException("processAdd: unindexed unstored field \"" + fieldName + "\"."); } tokenizedS = field.valueOf("@tokenized"); if (tokenizedS.equals("")) { throw new IllegalDocumentException("Field without tokenized attribute."); } tokenized = Boolean.valueOf(tokenizedS); boostS = field.valueOf("@boost"); if (!boostS.equals("")) { try { boost = new Float(boostS).floatValue(); } catch (NumberFormatException exception) { throw new IllegalDocumentException( "Unparsable boost value (" + boostS + ") for field \"" + fieldName + "\"."); } } // Now we add the fields. Depending on the parameter stored, indexed // and tokenized we call a different field constructor. lfield = null; Field.Index indexType = (indexed ? (tokenized ? Field.Index.ANALYZED : Field.Index.NOT_ANALYZED) : Field.Index.NO); Field.Store storeType; if (!stored) { storeType = Field.Store.NO; } else { if (compressedFields.contains(fieldName)) { storeType = Field.Store.COMPRESS; } else { storeType = Field.Store.YES; } } lfield = new Field(fieldName, fieldText, storeType, indexType); lfield.setBoost(boost); providedFields.add(fieldName); // for later comparison with the required fields ldoc.add(lfield); if (logger.isEnabledFor(Level.DEBUG)) { logger.debug("Writer - adding field:" + fieldName + ", index:" + indexed + ", store:" + stored + ", token:" + tokenized + " ,boost: " + boost + ", text: " + fieldText); } } // for (field iterator) HashSet<String> providedPayloads = new HashSet<String>(); // Now we add the payloads for (Iterator iter = e.elementIterator("payload"); iter.hasNext();) { Element payload = (Element) iter.next(); String payloadName = payload.valueOf("@name"); if (payloadName.equals("")) { throw new IllegalDocumentException("Payload without name."); } providedPayloads.add(payloadName); try { Long payloadValue = Long.parseLong(payload.getText()); ldoc.add(new Field(payloadName, new FixedValueTokenStream(payloadName, payloadValue))); logger.debug("Adding payload \"" + payloadName + "\" to document \"" + docIdText + "\" with value " + payloadValue); } catch (NumberFormatException nfe) { throw new IllegalDocumentException( "Writer - while parsing Long payload \"" + payloadName + "\": " + nfe.getMessage()); } } // no we test for the presence of the required fields if (!providedFields.containsAll(requiredFields) || !providedPayloads.containsAll(requiredPayloads)) { StringBuffer sb = new StringBuffer(); sb.append("Document with missing required fields or payloads. Ignoring addition.\n"); sb.append("Provided fields are: \n"); for (String field : providedFields) { sb.append(field + "\n"); } sb.append("The fields required are: \n"); for (String field : requiredFields) { sb.append(field + "\n"); } sb.append("Provided payloads are: \n"); for (String payload : providedPayloads) { sb.append(payload + "\n"); } sb.append("Required payloads are: \n"); for (String payload : requiredPayloads) { sb.append(payload + "\n"); } throw new IllegalDocumentException(sb.toString()); } return ldoc; }
From source file:com.haulmont.cuba.gui.components.filter.UserSetHelper.java
License:Apache License
public static String generateSetFilter(Set ids, String entityClass, String componentId, String entityAlias) { Document document = DocumentHelper.createDocument(); Element root = DocumentHelper.createElement("filter"); Element or = root.addElement("and"); Element condition = or.addElement("c"); condition.addAttribute("name", "set"); condition.addAttribute("inExpr", "true"); condition.addAttribute("hidden", "true"); condition.addAttribute("locCaption", "Set filter"); condition.addAttribute("entityAlias", entityAlias); condition.addAttribute("class", entityClass); condition.addAttribute("type", ConditionType.CUSTOM.name()); String listOfId = createIdsString(ids); String randomName = RandomStringUtils.randomAlphabetic(10); condition.addText(entityAlias + ".id in :component$" + componentId + "." + randomName); Element param = condition.addElement("param"); param.addAttribute("name", "component$" + componentId + "." + randomName); param.addText(listOfId);//from w w w . j a va 2 s . c o m document.add(root); return Dom4j.writeDocument(document, true); }
From source file:com.liferay.alloy.tools.builder.base.BaseBuilder.java
License:Open Source License
protected List<Component> getAllComponents() throws Exception { DocumentFactory factory = SAXReaderUtil.getDocumentFactory(); Document doc = factory.createDocument(); String taglibsXML = "<components></components>"; Document taglibsDoc = SAXReaderUtil .read(new InputSource(new ByteArrayInputStream(taglibsXML.getBytes("utf-8")))); Element root = taglibsDoc.getRootElement(); for (Document currentDoc : getComponentDefinitionDocs()) { currentDoc = _getExtendedDocument(currentDoc); Element currentRoot = currentDoc.getRootElement(); String defaultPackage = currentRoot.attributeValue("short-name"); List<Element> extComponentNodes = currentRoot.elements("component"); for (Element extComponent : extComponentNodes) { String extComponentPackage = Convert.toString(extComponent.attributeValue("package"), defaultPackage);/* w w w. j av a2s. c om*/ extComponent.addAttribute("package", extComponentPackage); } Element authors = currentRoot.element("author"); List<Element> components = currentRoot.elements("component"); for (Element component : components) { Element copy = component.createCopy(); Element componentAuthors = copy.element("authors"); if ((authors != null) && (componentAuthors == null)) { copy.add(authors.createCopy()); } root.add(copy); } List<org.dom4j.Attribute> attributes = currentRoot.attributes(); for (org.dom4j.Attribute attribute : attributes) { root.addAttribute(attribute.getName(), attribute.getValue()); } } doc.add(root.createCopy()); return getComponents(doc); }
From source file:com.orange.atk.atkUI.corecli.reportGenerator.ReportGenerator.java
License:Apache License
/** * Create a temporary file which contains only the report part * of the security profile./*www . ja v a 2s. c om*/ * @throws DocumentException */ protected Document getReportPartOfProfile() { Document document = profileParser.getDoc(); Element doElem = (Element) document.getRootElement().selectSingleNode("//do"); Document documentReport = DocumentHelper.createDocument(); documentReport.add(doElem.createCopy()); return documentReport; }
From source file:com.orange.atk.atkUI.corecli.reportGenerator.resultLink.ResultLink.java
License:Apache License
/** * Create <code>Resultvalue</code> object from result element * @param elem//from w w w . ja v a 2 s . c o m * @return the created <code>Resultvalue</code> object. */ public static Resultvalue getResultvalue(Element elem, Unmarshaller unmarshaller) { String kind = elem.attributeValue("kind"); Resultvalue resultvalue = null; if (kind == null || !kind.equals("use")) { Element resultvalueElem = (Element) elem.elements().get(0); Document documentResultvalue = DocumentHelper.createDocument(); documentResultvalue.add(resultvalueElem.createCopy()); DOMWriter d4Writer = new org.dom4j.io.DOMWriter(); try { org.w3c.dom.Document doc = d4Writer.write(documentResultvalue); // Unmarshal the data resultvalue = (Resultvalue) unmarshaller.unmarshal(doc); } catch (Exception e) { Logger.getLogger(ResultLink.class).debug(e); e.printStackTrace(); } } return resultvalue; }
From source file:com.stratumsoft.xmlgen.SchemaTypeXmlGenerator.java
License:Open Source License
/** * Generate an xml representation of the dom structure of the schema element * * @param elName the QName of the element for which the XML should be generated * @param isPrettyPrint if true formats and indents the generated xml * @return the xml instance for the schema element, or empty string if no element with the given qname was found *//*from w w w . jav a 2s. co m*/ public String generateXml(QName elName, boolean isPrettyPrint) { String xml = ""; if (elName != null && schemaColl != null) { Document doc = factory.createDocument("utf-8"); //NON-NLS Element el = generateElement(elName); if (el != null) { doc.add(el); } else { logger.warn("got null for element generated for qname: {}", elName); } if (isPrettyPrint) outputFormat = OutputFormat.createPrettyPrint(); StringWriter sw = new StringWriter(); writer = new XMLWriter(sw, outputFormat); try { writer.write(doc); xml = sw.toString(); logger.trace("Serialized dom4j doc to xml string: {}", xml); } catch (IOException e) { logger.error("dom4j Document to xml creation error", e); } } return xml; }