List of usage examples for org.jdom2 Attribute setValue
public Attribute setValue(final String value)
Attribute
. From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java
License:Apache License
/** * It a generates a XSD representation of a {@link RegularExpression}. It is called recursively to generate * subexpressions until one of them is a {@link SchemaElement}, then, {@link XMLSchemaDocumentGenerator#generateElement(SchemaElement, boolean, XSDInferenceConfiguration, String, String, ComplexType, Map, Namespace)} * is called (so it is not possible to recures infinitely if the {@link RegularExpression} is well defined. * This method is built in a way that allows to append its results directly to a <i>complexType</i> tag without errors. * @param regexp the regular expression to represent * @param configuration the inference configuration * @param targetNamespace the target namespace of the XSD that is currently being generated * @param mainNamespace the main namespace * @param complexType the complex type that contains the regular expression * @param namespaceURIToPrefixMappings solved mappings between namespace URIs and prefixes * @param xsdNamespace XSD namespace//from w w w.j ava 2 s. c o m * @return a JDOM2 {@link Element} that describes the given {@link RegularExpression} */ private Element generateRegexpRepresentation(RegularExpression regexp, XSDInferenceConfiguration configuration, String targetNamespace, String mainNamespace, ComplexType complexType, Map<String, String> namespaceURIToPrefixMappings, Namespace xsdNamespace) { boolean isSchemaElement = regexp instanceof SchemaElement; boolean isMultipleRegularExpression = regexp instanceof MultipleRegularExpression; boolean isSingularRegularExpression = regexp instanceof SingularRegularExpression; boolean isEmptyRegularExpression = regexp instanceof EmptyRegularExpression; if (isSchemaElement) { return generateElement((SchemaElement) regexp, false, configuration, targetNamespace, mainNamespace, complexType, namespaceURIToPrefixMappings, xsdNamespace); } else if (isMultipleRegularExpression) { String elementName; if (regexp instanceof All) { elementName = "all"; } else if (regexp instanceof Choice) { elementName = "choice"; } else if (regexp instanceof Sequence) { elementName = "sequence"; } else { throw new IllegalArgumentException("Unknown kind of MultipleRegularExpression: " + regexp); } Element currentElement = new Element(elementName, xsdNamespace); for (int i = 0; i < regexp.elementCount(); i++) { Element currentElementChild = generateRegexpRepresentation(regexp.getElement(i), configuration, targetNamespace, mainNamespace, complexType, namespaceURIToPrefixMappings, xsdNamespace); if (regexp instanceof All && currentElementChild != null) { All regexpAsAll = (All) regexp; // If a test fails due to children order diferences unde <all/> tags, modify code around here to ensure that elements inside <all/> elements follow the same order. if (regexpAsAll.getMinOccurs() == 0) { Attribute minOccursAttribute = new Attribute("minOccurs", "0"); currentElementChild.setAttribute(minOccursAttribute); } } if (currentElementChild != null) { currentElement.addContent(currentElementChild); } } return currentElement; } else if (isSingularRegularExpression) { RegularExpression regexpChild = regexp.getElement(0); if (!((regexpChild instanceof MultipleRegularExpression) || (regexpChild instanceof SchemaElement))) { throw new IllegalArgumentException( "A child of a SingularRegularExpression may only be an SchemaElement or a MultipleRegularExpression. \nPrevious optimization steps should have avoided other combinations."); } Element generatedChild = generateRegexpRepresentation(regexpChild, configuration, targetNamespace, mainNamespace, complexType, namespaceURIToPrefixMappings, xsdNamespace); Attribute minOccursAttr = new Attribute("minOccurs", ""); Attribute maxOccursAttr = new Attribute("maxOccurs", ""); if (regexp instanceof Optional) { minOccursAttr.setValue("0"); maxOccursAttr.setValue("1"); } else if (regexp instanceof Repeated) { minOccursAttr.setValue("0"); maxOccursAttr.setValue("unbounded"); } else if (regexp instanceof RepeatedAtLeastOnce) { minOccursAttr.setValue("1"); maxOccursAttr.setValue("unbounded"); } else { throw new IllegalArgumentException("Unknown kind of SingularRegularExpression: " + regexp); } generatedChild.setAttribute(maxOccursAttr); generatedChild.setAttribute(minOccursAttr); return generatedChild; } else if (isEmptyRegularExpression) { return null; } throw new IllegalArgumentException("Unknown kind of RegularExpression: " + regexp); }
From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java
License:Apache License
/** * Generates an {@link Element} that describes the {@link SchemaElement} given. * @param schemaElement the schema element to be represented * @param isGlobal whether this element is being declared globally * @param configuration the inference configuration * @param targetNamespace the target namespace of the XSD that is currently being generated * @param mainNamespace the main namespace * @param parentComplexType the complex type under which this element may occur (if any). If it may not occur under any complex type (because it is a root element, for example), null must be passed. * @param namespaceURIToPrefixMappings solved mappings between namespace URIs and prefixes * @param xsdNamespace XSD namespace//from w w w . j av a 2 s .co m * @return a JDOM2 {@link Element} that describes the given {@link SchemaElement} */ private Element generateElement(SchemaElement schemaElement, boolean isGlobal, XSDInferenceConfiguration configuration, String targetNamespace, String mainNamespace, ComplexType parentComplexType, Map<String, String> namespaceURIToPrefixMappings, Namespace xsdNamespace) { //This variables and the isGlobal parameter will be used to calculate the conditions which will determine what element (of the future schema document) should be generated. boolean elementsGlobal = configuration.getElementsGlobal(); boolean namespacesDiffer = !mainNamespace.equals(schemaElement.getNamespace()); boolean workaround = configuration.getStrictValidRootDefinitionWorkaround(); boolean isValidRoot = schemaElement.isValidRoot(); boolean belongsToSkippedNamespace = configuration.getSkipNamespaces() .contains(schemaElement.getNamespace()); //These are the conditions boolean avoidWorkaround = isValidRoot || belongsToSkippedNamespace; boolean normalElement = (elementsGlobal && isGlobal) || (!elementsGlobal && isGlobal && namespacesDiffer && (!(workaround && !avoidWorkaround))) || (!elementsGlobal && !isGlobal && !namespacesDiffer) || (isGlobal && isValidRoot); boolean referencingAnElement = (elementsGlobal && !isGlobal) || (!elementsGlobal && !isGlobal && namespacesDiffer && (!(workaround && !avoidWorkaround))); boolean referencingAGroup = (!elementsGlobal && !isGlobal && namespacesDiffer && (workaround && !avoidWorkaround)); boolean grouppedElement = (!elementsGlobal && isGlobal && namespacesDiffer && (workaround && !avoidWorkaround)); if (referencingAnElement) { Element elementElement = new Element("element", xsdNamespace); Attribute elementRefAttr = new Attribute("ref", ""); String refValue = schemaElement.getName(); String prefix = namespaceURIToPrefixMappings.get(schemaElement.getNamespace()); if (!prefix.equals("")) { refValue = prefix + ":" + refValue; } elementRefAttr.setValue(refValue); elementElement.setAttribute(elementRefAttr); return elementElement; } else { String possibleGroupName = schemaElement.getName() + configuration.getTypeNamesAncestorsSeparator() + schemaElement.getType().getName(); if (normalElement || grouppedElement) { Element elementElement = new Element("element", xsdNamespace); Attribute elementNameAttr = new Attribute("name", ""); elementNameAttr.setValue(schemaElement.getName()); elementElement.setAttribute(elementNameAttr); boolean isSimpleElement = (schemaElement.getType() .getRegularExpression() instanceof EmptyRegularExpression); isSimpleElement = isSimpleElement && schemaElement.getType().getAttributeList().isEmpty(); isSimpleElement = isSimpleElement && !schemaElement.getType().getTextSimpleType().isEmpty(); if (isSimpleElement) { if (configuration.getSimpleTypesGlobal() || !schemaElement.getType().getTextSimpleType().isEnum()) { Attribute elementTypeAttr = new Attribute("type", ""); String typeStr = schemaElement.getType().getTextSimpleType() .getRepresentationName(configuration.getTypeNamesAncestorsSeparator()); if (!namespaceURIToPrefixMappings.get(mainNamespace).equals("") && !(typeStr.startsWith(XSD_NAMESPACE_PREFIX))) { typeStr = namespaceURIToPrefixMappings.get(mainNamespace) + ":" + typeStr; } elementTypeAttr.setValue(typeStr); elementElement.setAttribute(elementTypeAttr); } else { Element elementSimpleTypeElement = generateSimpleType( schemaElement.getType().getTextSimpleType(), true, configuration, xsdNamespace); elementElement.addContent(elementSimpleTypeElement); } } else { if (configuration.getComplexTypesGlobal()) { Attribute elementTypeAttr = new Attribute("type", ""); String typeStr = schemaElement.getType().getName(); if (!namespaceURIToPrefixMappings.get(mainNamespace).equals("")) { typeStr = namespaceURIToPrefixMappings.get(mainNamespace) + ":" + typeStr; } elementTypeAttr.setValue(typeStr); elementElement.setAttribute(elementTypeAttr); } else { Element elementComplexTypeElement = generateComplexType(configuration, schemaElement.getType(), true, targetNamespace, namespaceURIToPrefixMappings, mainNamespace, xsdNamespace); elementElement.addContent(elementComplexTypeElement); } } if (grouppedElement) { Element elementGroup = new Element("group", xsdNamespace); Attribute groupNameAttr = new Attribute("name", ""); groupNameAttr.setValue(possibleGroupName); elementGroup.setAttribute(groupNameAttr); Element sequenceInGroupElement = new Element("sequence", xsdNamespace); sequenceInGroupElement.addContent(elementElement); elementGroup.addContent(sequenceInGroupElement); return elementGroup; } else { return elementElement; } } else if (referencingAGroup) { Element elementGroup = new Element("group", xsdNamespace); Attribute groupRefAttr = new Attribute("ref", ""); String groupQName = possibleGroupName; String namespacePrefix = namespaceURIToPrefixMappings.get(schemaElement.getNamespace()); if (!namespacePrefix.equals("")) groupQName = namespacePrefix + ":" + groupQName; groupRefAttr.setValue(groupQName); elementGroup.setAttribute(groupRefAttr); return elementGroup; } else { throw new IllegalArgumentException("The parameters given have lead to an invalid situation"); } } }
From source file:jodtemplate.pptx.ImageService.java
License:Apache License
public void insertImage(final ImageField imageField, final Slide slide, final Resources resources, final Element pic) throws JODTemplateException { try {/* ww w . j a v a 2 s . c o m*/ final InputStream is = imageField.getInputStream(); if (is != null) { try (final InputStream bis = new BufferedInputStream(is)) { final byte[] imageContents = IOUtils.toByteArray(bis); final Image image = getImage(imageContents, slide.getPresentation(), resources); final Relationship imageRel = getImageRelationship(image, slide); final Attribute embed = pic .getChild(PPTXDocument.BLIPFILL_ELEMENT, getPresentationmlNamespace()) .getChild(PPTXDocument.BLIP_ELEMENT, getDrawingmlNamespace()) .getAttribute(PPTXDocument.EMBED_ATTR, getRelationshipsNamespace()); embed.setValue(imageRel.getId()); setPicSize(pic, image); } } else { pic.getParent().removeContent(pic); } } catch (IOException | DataConversionException e) { throw new JODTemplateException(e); } }
From source file:jodtemplate.pptx.ImageService.java
License:Apache License
private void setPicSize(final Element pic, final Image image) throws DataConversionException { final Element ext = pic.getChild(PPTXDocument.SPPR_ELEMENT, getPresentationmlNamespace()) .getChild(PPTXDocument.XFRM_ELEMENT, getDrawingmlNamespace()) .getChild(PPTXDocument.EXT_ELEMENT, getDrawingmlNamespace()); final Attribute cxAttr = ext.getAttribute("cx"); final Attribute cyAttr = ext.getAttribute("cy"); final int cx = cxAttr.getIntValue(); final int cy = cyAttr.getIntValue(); final ImageSize newSize = calculateNewImageSize(cx, cy, image.getWidth(), image.getHeight()); cxAttr.setValue(String.valueOf(newSize.width)); cyAttr.setValue(String.valueOf(newSize.height)); }
From source file:org.artifactory.mime.version.converter.v1.XmlIndexedConverter.java
License:Open Source License
@Override public void convert(Document doc) { Element rootElement = doc.getRootElement(); Namespace namespace = rootElement.getNamespace(); List mimetypes = rootElement.getChildren("mimetype", namespace); // make sure there are no more 'xml' attributes for (Object mimetype : mimetypes) { Element mimeTypeElement = (Element) mimetype; Attribute xmlAttribute = mimeTypeElement.getAttribute("xml", namespace); if (xmlAttribute != null) { // rename to index xmlAttribute.setName("index"); // change to false unless maven of ivy String type = mimeTypeElement.getAttributeValue("type"); if (!"application/x-maven-pom+xml".equals(type) && !"application/x-ivy+xml".equals(type)) { xmlAttribute.setValue("false"); }//from w w w . ja va2s.c o m } } }
From source file:org.jumpmind.metl.core.runtime.component.XmlFormatter.java
License:Open Source License
private void addModelAttributeXml(Stack<DocElement> parentStack, String attributeId, Object modelAttrValue, Document generatedXml, String entityId) { DocElement templateDocElement = entityAttributeDtls.get(attributeId); String value = modelAttrValue == null ? null : modelAttrValue.toString(); Element newElement = null;//from ww w. j a va 2 s . co m Element templateParentElement = null; String templateParentXPath = null; Attribute newAttribute = null; Map<Element, Namespace> generatedDocNamespaces = null; Map<Element, Namespace> templateNamespaces = null; Stack<Element> parentsToAdd = new Stack<Element>(); DocElement entityDocElement = entityAttributeDtls.get(entityId); generatedDocNamespaces = removeNamespaces(generatedXml); templateNamespaces = removeNamespaces(templateDoc); // we can be passed elements in the model that don't reside in the // template. If so, just ignore the field and do nothing if (templateDocElement != null) { // at this point, our stack should always currently have the entity // for this attribute as the top level of the stack // set up our new element or attribute to add if (templateDocElement.xmlElement != null) { // we have to add an element newElement = templateDocElement.xmlElement.clone(); newElement.removeContent(); removeAllAttributes(newElement); if (StringUtils.isEmpty(value)) { if (nullHandling.equalsIgnoreCase(NULL_HANDLING_XML_NIL)) { newElement.setAttribute("nil", "true", getXmlNamespace()); } } else { newElement.setText(value); } } else { // we have to add an attribute newAttribute = templateDocElement.xmlAttribute.clone(); if (value != null) { newAttribute.setValue(value); } } // in this case the attribute is one lower than the entity and // should simply be attached to the entity if (templateDocElement.level - 1 == parentStack.peek().level) { if (newElement != null) { applyAttributeXPath(generatedXml, templateDocElement.xpath, value); } else { parentStack.peek().xmlElement.setAttribute(newAttribute); } } else { // the attribute doesn't hang directly off the entity // we must find its parent in the existing doc or fill static // content as appropriate // first get the parent element for this model attribute, and // gets its xpath XPathExpression<Element> expression = XPathFactory.instance().compile(templateDocElement.xpath, Filters.element()); List<Element> matches = expression.evaluate(templateDoc.getRootElement()); if (matches.size() != 0) { templateParentElement = matches.get(0).getParentElement(); } else { // throw an exception, we should always find the element in // the template } // now look for parent elements in the generated xml until we // find one // or we hit the entity itself boolean parentFound = false; do { templateParentXPath = XPathHelper.getRelativePath(entityDocElement.xmlElement, templateParentElement); expression = XPathFactory.instance().compile(templateParentXPath, Filters.element()); matches = expression.evaluate(parentStack.peek().xmlElement); if (matches.size() == 0) { Element elementToAdd = templateParentElement.clone(); elementToAdd.removeContent(); removeAllAttributes(elementToAdd); parentsToAdd.push(elementToAdd); templateParentElement = templateParentElement.getParentElement(); } else { parentFound = true; } } while (parentFound == false); // add every parent we couldn't find up to the entity level Element elementToAddTo = matches.get(0); while (!parentsToAdd.isEmpty()) { elementToAddTo.addContent(0, parentsToAdd.peek()); elementToAddTo = parentsToAdd.pop(); } // add our model attribute to the latest level if (newElement != null) { applyAttributeXPath(generatedXml, templateDocElement.xpath, value); } else { elementToAddTo.setAttribute(newAttribute); } } } restoreNamespaces(templateDoc, templateNamespaces); restoreNamespaces(generatedXml, generatedDocNamespaces); }
From source file:org.jumpmind.metl.core.runtime.component.XmlFormatter.java
License:Open Source License
private void applyAttributeXPath(Document generatedXml, String xpath, String value) { List<Object> matches = XPathFactory.instance().compile(xpath).evaluate(generatedXml.getRootElement()); if (matches.size() == 0) { log(LogLevel.WARN, "XPath expression " + xpath + " did not find any matches"); return;// ww w . j av a 2 s . c o m } Object object = matches.get(0); if (object instanceof Element) { Element element = (Element) object; if (value != null) { element.setText(value.toString()); } else { if (nullHandling.equals(NULL_HANDLING_REMOVE)) { Element parent = element.getParentElement(); parent.removeContent(element); } else if (nullHandling.equalsIgnoreCase(NULL_HANDLING_XML_NIL)) { element.setAttribute("nil", "true", getXmlNamespace()); } } } else if (object instanceof Attribute) { Attribute attribute = (Attribute) object; if (value != null) { attribute.setValue(value); } } }
From source file:org.kdp.word.transformer.AttributeTransformer.java
License:Apache License
private void transformInternal(Parser parser, Element el, Set<Replace> replace) { String elname = el.getName(); for (Attribute att : new ArrayList<Attribute>(el.getAttributes())) { String attname = att.getName(); String attvalue = att.getValue(); String attid = elname + "." + attname; for (Replace rep : replace) { if (attid.equals(rep.attid)) { if (rep.substr == null || attvalue.contains(rep.substr)) { if (rep.newval == null || rep.newval.length() == 0) { log.debug("Remote attribute: {}", att); el.getAttributes().remove(att); } else { log.debug("Replace attribute: {}", att); att.setValue(rep.newval); }//from ww w . j ava2 s.c o m break; } } } } for (Element ch : el.getChildren()) { transformInternal(parser, ch, replace); } }
From source file:org.kdp.word.transformer.MetadataTransformer.java
License:Apache License
@Override public void transform(Context context) { Element root = context.getSourceRoot(); Element el = JDOMUtils.findElement(root, "meta", "name", "Generator"); if (el != null) { Attribute att = el.getAttribute("content"); String attval = att.getValue(); att.setValue(attval + " - word2mobi"); }/* ww w . ja v a 2s . c o m*/ }
From source file:org.kdp.word.transformer.StyleTransformer.java
License:Apache License
private void classStyleReplace(Context context, Element element, Attribute attClass) { String value = null;//w w w . j av a 2 s . com String attname = attClass.getName(); String attvalue = attClass.getValue(); for (Replacement rep : replacements) { if (attname.equals(rep.attname)) { if (isWhitelisted(attvalue)) { value = attvalue; } else if (rep.pattern.matcher(attvalue).matches()) { value = rep.value; break; } } } if (value != null) { attClass.setValue(value); } else { element.removeAttribute(attClass); } }