List of usage examples for org.jdom2.filter Filters element
public static final Filter<Element> element(String name, Namespace ns)
From source file:AIR.Common.xml.XmlHelper.java
License:Open Source License
public static List<Element> getElements(Parent doc, final String name, Namespace ns) { IteratorIterable<Element> matches = doc.<Element>getDescendants(Filters.element(name, ns)); List<Element> returnList = new ArrayList<Element>(); while (matches.hasNext()) returnList.add(matches.next());/*from w w w.j a v a 2 s. co m*/ return returnList; }
From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.JSONTypesExtractorImpl.java
License:Apache License
/** * This method sets a given namespace to the given element and any of its descendants whose * name is a provided one and have no namespace. * @param name the name of the searched elements * @param rootElement the root element to begin the search at * @param namespace the namespace to set */// w w w .ja v a2 s . c om private void setNamespaceToElementsByName(String name, Element rootElement, Namespace namespace) { IteratorIterable<Element> descendants = rootElement .getDescendants(Filters.element(name, Namespace.NO_NAMESPACE)); for (Element descendant : descendants) { descendant.setNamespace(namespace); } if (rootElement.getName().equals(name) && rootElement.getNamespace().equals(Namespace.NO_NAMESPACE)) { rootElement.setNamespace(namespace); } }
From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java
License:Apache License
/** * It generates the XSD file of the targetNamespace given at the constructor, taking into account that * the main namespace is the one given at the constructor. * /* w ww. j a v a 2s . c o m*/ * @param schema the schema object * @param configuration the inference configuration * * @return a JDOM2 {@link Document} object containing the XSD contents. * * @see SchemaDocumentGenerator#generateSchemaDocument(Schema, XSDInferenceConfiguration) */ @Override public Document generateSchemaDocument(Schema schema, XSDInferenceConfiguration configuration) { // if(!configuration.getElementsGlobal()==false || // !configuration.getComplexTypesGlobal()==true || // !configuration.getSimpleTypesGlobal()==true // ) // throw new UnsupportedOperationException("Not implemented yet."); // checkArgument(schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(mainNamespace), "The main namespace must be a known namespace"); checkArgument(schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(targetNamespace), "The target namespace must be a known namespace"); // checkArgument(!schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(XSD_NAMESPACE_URI),"The XSD namespace must not be a known namespace"); // checkArgument(!schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(XSI_NAMESPACE_URI),"The XSI namespace must not be a known namespace"); Map<String, String> namespaceURIToPrefixMappings = schema.getSolvedNamespaceMappings(); if (configuration.getSkipNamespaces().contains(targetNamespace)) { throw new IllegalArgumentException("This is an skipped namespace, so its XSD should not be generated"); } if (targetNamespace.equals(XSD_NAMESPACE_URI)) System.err.println( "The XML Schema namespace is being considered as a target namespace in your documents. Independing of the inferred schemas, the only valid XSD for an XSD would be the normative one present at its first RFC"); Namespace xsdNamespace = Namespace.getNamespace(XSD_NAMESPACE_PREFIX.replace(":", ""), XSD_NAMESPACE_URI); List<Namespace> namespaceDeclarations = getNamespaceDeclarations(namespaceURIToPrefixMappings, xsdNamespace); Element elementSchema = new Element("schema", xsdNamespace); for (int i = 0; i < namespaceDeclarations.size(); i++) { Namespace currentNamespace = namespaceDeclarations.get(i); elementSchema.addNamespaceDeclaration(currentNamespace); String currentNamespaceUri = currentNamespace.getURI(); if (!targetNamespace.equals(mainNamespace) && !currentNamespaceUri.equals(mainNamespace)) continue; if (currentNamespace.equals(Namespace.XML_NAMESPACE) && (!schema.getAttributes().containsRow(XSDInferenceConfiguration.XML_NAMESPACE_URI) && !schema.getElements().containsRow(XSDInferenceConfiguration.XML_NAMESPACE_URI))) { continue; } if (currentNamespaceUri.equals(XSD_NAMESPACE_URI) && !namespaceURIToPrefixMappings.containsKey(XSD_NAMESPACE_URI)) continue; if (targetNamespace.equals(currentNamespaceUri) || (currentNamespaceUri.equals("") && (fileNameGenerator == null))) continue; if (currentNamespaceUri.equals("") && !currentNamespaceUri.equals(mainNamespace) && !schema.getElements().containsRow("")) continue; Element importElement = new Element("import", xsdNamespace); if (!currentNamespaceUri.equals("")) { Attribute namespaceAttr = new Attribute("namespace", currentNamespaceUri); importElement.setAttribute(namespaceAttr); } if (fileNameGenerator != null && !configuration.getSkipNamespaces().contains(currentNamespaceUri)) { String fileName = fileNameGenerator.getSchemaDocumentFileName(currentNamespaceUri, namespaceURIToPrefixMappings); Attribute schemaLocationAttr = new Attribute("schemaLocation", fileName); importElement.setAttribute(schemaLocationAttr); } elementSchema.addContent(importElement); } if (!targetNamespace.equals("")) { Attribute targetNamespaceAttr = new Attribute("targetNamespace", targetNamespace); elementSchema.setAttribute(targetNamespaceAttr); } SortedSet<SimpleType> sortedSimpleTypes = new TreeSet<>(new SimpleTypeComparator()); sortedSimpleTypes.addAll(schema.getSimpleTypes().values()); SortedSet<ComplexType> sortedComplexTypes = new TreeSet<>(new ComplexTypeComparator()); sortedComplexTypes.addAll(schema.getComplexTypes().values()); //CONTINUE FROM HERE: Generate sorted sets for SchemaElement and SchemaAttribute objects and use them where needed. Attribute elementFormDefault = new Attribute("elementFormDefault", "qualified"); elementSchema.setAttribute(elementFormDefault); Document resultingDocument = new Document(elementSchema); if (targetNamespace.equals(mainNamespace)) { //First, we declare global SimpleTypes. //If simpleTypesGlobal is true, any enumeration will be declared as a global simple type. //if not, simple types of complex types which have attributes but not children will be declared globally //(due to limitations of XSD, they may not be declared locally together with the attributes info) if (configuration.getSimpleTypesGlobal()) { for (SimpleType simpleType : sortedSimpleTypes) { if (!simpleType.isEnum() || simpleType.isEmpty()) continue; Element simpleTypeElement = generateSimpleType(simpleType, false, configuration, xsdNamespace); elementSchema.addContent(simpleTypeElement); } } else { for (ComplexType complexType : sortedComplexTypes) { SimpleType simpleType = complexType.getTextSimpleType(); if (complexType.getAttributeList().isEmpty() || !(complexType.getAutomaton().nodeCount() == 0) || !simpleType.isEnum() || simpleType.isEmpty()) continue; Element simpleTypeElement = generateSimpleType(simpleType, false, configuration, xsdNamespace); elementSchema.addContent(simpleTypeElement); } } //Global complexType elements are only generated in the main schema (i.e. the one whose targetNamespace is equal to mainNamespace) if (configuration.getComplexTypesGlobal()) { for (ComplexType complexType : sortedComplexTypes) { boolean hasNoChildren = complexType.getRegularExpression().equals(new EmptyRegularExpression()); boolean hasNoAttributes = complexType.getAttributeList().size() == 0; boolean hasNoComments = complexType.getComments().size() == 0; // boolean simpleTypeIsNotEmpty = !complexType.getTextSimpleType().isEmpty(); boolean simpleTypeIsWhiteSpaceOnlyOrEmpty = !(complexType.getTextSimpleType().isEmpty() || complexType.getTextSimpleType().consistOnlyOfWhitespaceCharacters()); if (hasNoChildren && hasNoAttributes && simpleTypeIsWhiteSpaceOnlyOrEmpty && hasNoComments) continue; //Because the elements which are linked to this ComplexType at our internal model //will be linked to an XSD simple type elsewhere, either a builtin or a custom one. Element complexTypeElement = generateComplexType(configuration, complexType, false, targetNamespace, namespaceURIToPrefixMappings, mainNamespace, xsdNamespace); elementSchema.addContent(complexTypeElement); } } } //If there are many namespaces and the workaround is disabled, we must declare global attributes. //If the targetNamespace is not the mainNamespace, we must declare all the attributes. //if the target namespace is the main namespace, we do not need to declare anything, because the complex types which hold the attributes //are also in the main namespace. if ((namespaceURIToPrefixMappings.size() - configuration.getSkipNamespaces().size()) > 1) { SortedMap<String, SchemaAttribute> globalAttributeCandidates = new TreeMap<>( schema.getAttributes().row(targetNamespace)); if (!targetNamespace.equals(mainNamespace) && !targetNamespace.equals("")) { globalAttributesLoop: for (Map.Entry<String, SchemaAttribute> schemaAttributeEntry : globalAttributeCandidates .entrySet()) { SchemaAttribute schemaAttribute = schemaAttributeEntry.getValue(); //First, we check if the attribute has been already declared when the workaround is disabled. //If so, we update the "use" property. //The type should have been already merged. if (!configuration.getStrictValidRootDefinitionWorkaround()) { List<Element> alreadyGeneratedAttributeElements = elementSchema.getChildren("attribute", xsdNamespace); for (int i = 0; i < alreadyGeneratedAttributeElements.size(); i++) { Element currentAttributeElement = alreadyGeneratedAttributeElements.get(i); if (currentAttributeElement.getAttributeValue("name") .equals(schemaAttribute.getName())) { continue globalAttributesLoop; } } } Element attributeOrAttributeGroupElement = generateAttribute(schemaAttribute, true, configuration, namespaceURIToPrefixMappings, targetNamespace, mainNamespace, schemaAttributeEntry.getKey(), xsdNamespace); elementSchema.addContent(attributeOrAttributeGroupElement); } } } //Now, we declare global elements. //An element will be declared globally if and only if: //1-elementsGlobal is true in the configuration //2-The element is a valid root //3-The element is in a namespace other than the main namespace. Note that the element WILL be surrounded by the corresponding group if the workaround is enabled. //Another important remark: Iterating over a set copy implies iterating over DISTINCT SchemaElements, so if two keys pointed to equal SchemaElements, we would generate it only once- SortedSet<SchemaElement> schemaElementsAtTargetNamespace = new TreeSet<>(new SchemaElementComparator()); schemaElementsAtTargetNamespace.addAll(schema.getElements().row(targetNamespace).values()); globalSchemaElementsLoop: for (SchemaElement schemaElement : schemaElementsAtTargetNamespace) { // if(!configuration.getElementsGlobal()&& // !schemaElement.isValidRoot()&& // (targetNamespace.equals(mainNamespace)||configuration.getStrictValidRootDefinitionWorkaround())) if (!configuration.getElementsGlobal() && !schemaElement.isValidRoot() && (targetNamespace.equals(mainNamespace))) continue; // for(Element currentElement:elementSchema.getContent(Filters.element("element",xsdNamespace))){ // if(schemaElement.getName().equals(currentElement.getAttributeValue("name"))) // continue globalSchemaElementsLoop; // } String possibleGroupName = schemaElement.getName() + configuration.getTypeNamesAncestorsSeparator() + schemaElement.getType().getName(); for (Element currentElement : elementSchema.getContent(Filters.element("group", xsdNamespace))) { if (possibleGroupName.equals(currentElement.getAttributeValue("name"))) continue globalSchemaElementsLoop; } Element elementOrGroupElement = generateElement(schemaElement, true, configuration, targetNamespace, mainNamespace, null, namespaceURIToPrefixMappings, xsdNamespace); if (elementOrGroupElement.getName().equals("element")) { for (Element currentElement : elementSchema.getChildren("element", xsdNamespace)) { if (schemaElement.getName().equals(currentElement.getAttributeValue("name"))) continue globalSchemaElementsLoop; } } elementSchema.addContent(elementOrGroupElement); } return resultingDocument; }
From source file:jodtemplate.pptx.postprocessor.StylePostprocessor.java
License:Apache License
@Override public Document process(final Map<String, Object> context, final Document document, final Slide slide, final Resources resources, final Configuration configuration) throws JODTemplateException { final IteratorIterable<Element> atElements = document .getDescendants(Filters.element(PPTXDocument.T_ELEMENT, getNamespace())); final List<Element> atElementsList = new ArrayList<>(); while (atElements.hasNext()) { atElementsList.add(atElements.next()); }/*from ww w.ja va 2s . co m*/ for (Element at : atElementsList) { if (at.getContentSize() != 0) { final Content content = at.getContent(0); if (content instanceof Comment) { final Comment comment = (Comment) content; processComment(comment, at, slide, configuration); } } } return document; }
From source file:jodtemplate.pptx.postprocessor.StylePostprocessor.java
License:Apache License
private Element getArPrElement(final Element ar) { final List<Element> arPrElements = ar.getContent(Filters.element(PPTXDocument.RPR_ELEMENT, getNamespace())); Element arPr = null;//w w w . ja v a2 s .co m if (CollectionUtils.isNotEmpty(arPrElements)) { arPr = arPrElements.get(0).clone(); arPr.removeAttribute("b", getNamespace()); arPr.removeAttribute("i", getNamespace()); arPr.removeAttribute("u", getNamespace()); } return arPr; }
From source file:jodtemplate.pptx.postprocessor.StylePostprocessor.java
License:Apache License
private Element getApPrElement(final Element ap) { final List<Element> apPrElements = ap.getContent(Filters.element(PPTXDocument.PPR_ELEMENT, getNamespace())); if (CollectionUtils.isNotEmpty(apPrElements)) { return apPrElements.get(0).clone(); }//from w w w .j av a 2s . c om return null; }
From source file:jodtemplate.pptx.preprocessor.FormatTagsPreprocessor.java
License:Apache License
@Override public Document process(final Map<String, Object> context, final Document document, final Slide slide, final Resources resources, final Configuration configuration) { final IteratorIterable<Element> apElements = document .getDescendants(Filters.element(PPTXDocument.P_ELEMENT, getNamespace())); final List<Element> apElementsList = new ArrayList<>(); while (apElements.hasNext()) { apElementsList.add(apElements.next()); }//from w w w .j av a 2s .c o m for (Element ap : apElementsList) { final List<Element> apChildrenList = ap.getChildren(); if (apChildrenList.size() != 0) { final List<Element> arabrElementsListResult = processArAndABrElements(apChildrenList, configuration.getParserFactory().createParser()); int firstArElementIndex = ap.indexOf(ap.getChild(PPTXDocument.R_ELEMENT, getNamespace())); if (firstArElementIndex < 0) { firstArElementIndex = 0; } ap.removeChildren(PPTXDocument.R_ELEMENT, getNamespace()); ap.removeChildren(PPTXDocument.BR_ELEMENT, getNamespace()); ap.addContent(firstArElementIndex, arabrElementsListResult); } } return document; }
From source file:jodtemplate.pptx.preprocessor.PicPreprocessor.java
License:Apache License
public Document process(final Map<String, Object> context, final Document document, final Slide slide, final Resources resources, final Configuration configuration) throws JODTemplateException { final ExpressionHandler expressionHandler = configuration.getExpressionHandler(); final IteratorIterable<Element> picElements = document .getDescendants(Filters.element(PPTXDocument.PIC_ELEMENT, getPresentationmlNamespace())); final List<Element> picElementsList = new ArrayList<>(); while (picElements.hasNext()) { picElementsList.add(picElements.next()); }/*from ww w. j av a 2s. c om*/ for (Element pic : picElementsList) { final Attribute descr = pic.getChild(PPTXDocument.NVPICPR_ELEMENT, getPresentationmlNamespace()) .getChild(PPTXDocument.CNVPR_ELEMENT, getPresentationmlNamespace()) .getAttribute(PPTXDocument.DESCR_ATTR); if (descr != null && expressionHandler.isExpression(descr.getValue())) { final VariableExpression expression = expressionHandler.createVariableExpression(descr.getValue()); Object value; try { value = PropertyUtils.getNestedProperty(context, expression.getVariable()); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new JODTemplateException("Unable to get value: " + expression.getVariable()); } if (value instanceof ImageField) { final ImageField imageField = (ImageField) value; imageService.insertImage(imageField, slide, resources, pic); } else { throw new JODTemplateException("Field " + expression.getVariable() + " should contain image."); } } } return document; }
From source file:jodtemplate.pptx.preprocessor.ShortListPreprocessor.java
License:Apache License
@Override public Document process(final Map<String, Object> context, final Document document, final Slide slide, final Resources resources, final Configuration configuration) throws JODTemplateException { final IteratorIterable<Element> parentElements = document .getDescendants(Filters.element(parentElement, getNamespace())); final List<Element> parentElementsList = new ArrayList<>(); while (parentElements.hasNext()) { parentElementsList.add(parentElements.next()); }//from www .j a v a 2 s. co m for (final Element parent : parentElementsList) { final IteratorIterable<Element> atElements = parent .getDescendants(Filters.element(PPTXDocument.T_ELEMENT, getNamespace())); final List<Element> atElementsList = new ArrayList<>(); while (atElements.hasNext()) { atElementsList.add(atElements.next()); } final ExpressionHandler expressionHandler = configuration.getExpressionHandler(); boolean isLoop = false; InlineListExpression expression = null; for (final Element at : atElementsList) { final String text = at.getText(); if (configuration.getExpressionHandler().isInlineList(text)) { expression = expressionHandler.createInlineListExpression(text); at.setText(expressionHandler.createVariable(expression.getVariable())); isLoop = true; } } if (isLoop) { int apIndex = parent.getParent().indexOf(parent); final String beginList = expressionHandler.createBeginList(expression.getWhat(), expression.getAs()); final String endList = expressionHandler.createEndList(); parent.getParent().addContent(apIndex, new Comment(beginList)); apIndex++; parent.getParent().addContent(apIndex + 1, new Comment(endList)); } } return document; }
From source file:org.mycore.mods.MCRMODSMetadataShareAgent.java
License:Open Source License
@Override public void distributeMetadata(MCRObject holder) throws MCRPersistenceException, MCRAccessException { MCRMODSWrapper holderWrapper = new MCRMODSWrapper(holder); List<MCRMetaLinkID> children = holder.getStructure().getChildren(); if (!children.isEmpty()) { LOGGER.info("Update inherited metadata"); for (MCRMetaLinkID childIdRef : children) { LOGGER.info("Update: " + childIdRef); MCRObject child = MCRMetadataManager.retrieveMCRObject(childIdRef.getXLinkHrefID()); MCRMODSWrapper childWrapper = new MCRMODSWrapper(child); inheritToChild(holderWrapper, childWrapper); LOGGER.info("Saving: " + childIdRef); try { MCRMetadataManager.update(child); } catch (MCRActiveLinkException e) { throw new MCRPersistenceException("Error while updating inherited metadata", e); }/*from www . j av a2s . c o m*/ } } Collection<String> recipientIds = MCRLinkTableManager.instance().getSourceOf(holder.getId(), MCRLinkTableManager.ENTRY_TYPE_REFERENCE); for (String rId : recipientIds) { LOGGER.info("distribute metadata to " + rId); MCRObjectID recipientId = MCRObjectID.getInstance(rId); MCRObject recipient = MCRMetadataManager.retrieveMCRObject(recipientId); MCRMODSWrapper recipientWrapper = new MCRMODSWrapper(recipient); for (Element relatedItem : recipientWrapper.getLinkedRelatedItems()) { String holderId = relatedItem.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE); if (holder.getId().toString().equals(holderId)) { @SuppressWarnings("unchecked") Filter<Content> sharedMetadata = (Filter<Content>) Filters .element("part", MCRConstants.MODS_NAMESPACE).negate(); relatedItem.removeContent(sharedMetadata); relatedItem.addContent(holderWrapper.getMODS().cloneContent()); LOGGER.info("Saving: " + recipientId); try { MCRMetadataManager.update(recipient); } catch (MCRActiveLinkException e) { throw new MCRPersistenceException("Error while updating shared metadata", e); } } } } }