Example usage for org.jdom2 Element addNamespaceDeclaration

List of usage examples for org.jdom2 Element addNamespaceDeclaration

Introduction

In this page you can find the example usage for org.jdom2 Element addNamespaceDeclaration.

Prototype

public boolean addNamespaceDeclaration(final Namespace additionalNamespace) 

Source Link

Document

Adds a namespace declarations to this element.

Usage

From source file:cz.pecina.retro.memory.XML.java

License:Open Source License

/**
 * Writes a memory range to a file, with wrap-around.
 *
 * @param file               output file
 * @param startAddress       starting address
 * @param number             number of bytes
 * @param destinationAddress destination address
 *///from  w w  w . j  av  a  2s .com
public void write(final File file, final int startAddress, final int number, final int destinationAddress) {
    log.fine(
            String.format("Writing XML data to a file, file: %s, start address: %04x," + " number of bytes: %d",
                    file.getName(), startAddress, number));
    final Element tag = new Element("memory");
    Snapshot.buildBlockElement(sourceMemory, tag, startAddress, number);
    final Namespace namespace = Namespace.getNamespace("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
    tag.addNamespaceDeclaration(namespace);
    tag.setAttribute("noNamespaceSchemaLocation",
            Application.XSD_PREFIX + "memory-" + MEMORY_XML_FILE_VERSION + ".xsd", namespace);
    tag.setAttribute("version", MEMORY_XML_FILE_VERSION);
    tag.setAttribute("start", String.format("%04X", destinationAddress));
    final Document doc = new Document(tag);
    try (final PrintWriter writer = new PrintWriter(file)) {
        new XMLOutputter(Format.getPrettyFormat()).output(doc, writer);
    } catch (final Exception exception) {
        log.fine("Error, writing failed, exception: " + exception.getMessage());
        throw Application.createError(this, "XMLWrite");
    }
    log.fine("Writing completed");
}

From source file:cz.pecina.retro.trec.XML.java

License:Open Source License

/**
 * Writes the tape to an XML file./*  w  ww. java  2  s .com*/
 *
 * @param file output file
 */
public void write(final File file) {
    log.fine("Writing tape data to an XML file, file: " + file);
    final Element tag = new Element("tape");
    final Namespace namespace = Namespace.getNamespace("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
    tag.addNamespaceDeclaration(namespace);
    tag.setAttribute("noNamespaceSchemaLocation",
            Application.XSD_PREFIX + "tape-" + TAPE_XML_FILE_VERSION + ".xsd", namespace);
    tag.setAttribute("version", TAPE_XML_FILE_VERSION);
    tag.setAttribute("rate", String.valueOf(tapeRecorderInterface.tapeSampleRate));
    tag.setAttribute("unit", "per sec");
    try {
        long currPos = -1;
        for (long start : tape.navigableKeySet()) {
            final long duration = tape.get(start);
            log.finest(String.format("Fetched: (%d, %d)", start, duration));
            if ((start > currPos) && (duration > 0)) {
                final Element pulse = new Element("pulse");
                pulse.setAttribute("start", String.valueOf(start));
                pulse.setAttribute("duration", String.valueOf(duration));
                tag.addContent(pulse);
                log.finest(String.format("Write: (%d, %d)", start, duration));
                currPos = start + duration;
            }
        }
    } catch (final Exception exception) {
        log.fine("Error, writing failed, exception: " + exception.getMessage());
        throw Application.createError(this, "XMLWrite");
    }
    final Document doc = new Document(tag);
    try (final PrintWriter writer = new PrintWriter(file)) {
        new XMLOutputter(Format.getPrettyFormat()).output(doc, writer);
    } catch (final Exception exception) {
        log.fine("Error, writing failed, exception: " + exception.getMessage());
        throw Application.createError(this, "XMLWrite");
    }
    log.fine("Writing completed");
}

From source file:de.nava.informa.exporters.RSS_1_0_Exporter.java

License:Open Source License

public void write(ChannelIF channel) throws IOException {
    if (writer == null) {
        throw new RuntimeException("No writer has been initialized.");
    }/*from   w ww  . j ava  2s.c  om*/

    Element rootElem = new Element("RDF", NS_RDF);
    rootElem.addNamespaceDeclaration(NS_DEFAULT); // TODO
    rootElem.addNamespaceDeclaration(NS_DC);
    rootElem.addNamespaceDeclaration(NS_SY);
    // rootElem.setAttribute("version");
    Element channelElem = new Element("channel", NS_DEFAULT);
    if (channel.getLocation() != null) {
        channelElem.setAttribute("about", channel.getLocation().toString(), NS_RDF);
    }
    channelElem.addContent(new Element("title", NS_DEFAULT).setText(channel.getTitle()));
    if (channel.getSite() != null) {
        channelElem.addContent(new Element("link", NS_DEFAULT).setText(channel.getSite().toString()));
        channelElem.addContent(
                new Element("source", NS_DC).setAttribute("resource", channel.getSite().toString()));
    }

    channelElem.addContent(new Element("description", NS_DEFAULT).setText(channel.getDescription()));
    if (channel.getLanguage() != null) {
        channelElem.addContent(new Element("language", NS_DC).setText(channel.getLanguage()));
    }
    if (channel.getCopyright() != null) {
        channelElem.addContent(new Element("copyright", NS_DC).setText(channel.getCopyright()));
    }
    if (channel.getUpdateBase() != null) {
        channelElem.addContent(new Element("updateBase", NS_SY).setText(df.format(channel.getUpdateBase())));
    }
    if (channel.getUpdatePeriod() != null) {
        // don't put out frequency without specifying period
        channelElem.addContent(new Element("updateFrequency", NS_SY)
                .setText((new Integer(channel.getUpdateFrequency())).toString()));
        channelElem
                .addContent(new Element("updatePeriod", NS_SY).setText(channel.getUpdatePeriod().toString()));
    }
    // export channel image
    if (channel.getImage() != null) {
        Element imgElem = new Element("image", NS_DEFAULT);
        imgElem.addContent(new Element("title", NS_DEFAULT).setText(channel.getImage().getTitle()));
        imgElem.addContent(new Element("url", NS_DEFAULT).setText(channel.getImage().getLocation().toString()));
        imgElem.addContent(new Element("link", NS_DEFAULT).setText(channel.getImage().getLink().toString()));
        imgElem.addContent(new Element("height", NS_DEFAULT).setText("" + channel.getImage().getHeight()));
        imgElem.addContent(new Element("width", NS_DEFAULT).setText("" + channel.getImage().getWidth()));
        imgElem.addContent(new Element("description", NS_DEFAULT).setText(channel.getImage().getDescription()));
        channelElem.addContent(imgElem);
    }

    // TODO: add exporting textinput field
    //     if (channel.getTextInput() != null) {
    //       channelElem.addContent(channel.getTextInput().getElement());
    //     }

    // ===========================================
    Element itemsElem = new Element("items", NS_DEFAULT);
    Element seqElem = new Element("Seq", NS_RDF);
    Collection items = channel.getItems();
    Iterator it = items.iterator();
    while (it.hasNext()) {
        ItemIF item = (ItemIF) it.next();
        Element itemElem = new Element("li", NS_RDF);
        if (item.getLink() != null) {
            itemElem.setAttribute("resource", item.getLink().toString());
        }
        seqElem.addContent(itemElem);
    }
    itemsElem.addContent(seqElem);
    channelElem.addContent(itemsElem);
    rootElem.addContent(channelElem);

    // item-by-item en detail
    items = channel.getItems();
    it = items.iterator();
    while (it.hasNext()) {
        rootElem.addContent(getItemElement((ItemIF) it.next()));
    }

    // create XML outputter with indent: 2 spaces, print new lines.
    Format format = Format.getPrettyFormat();
    format.setEncoding(encoding);
    XMLOutputter outputter = new XMLOutputter(format);
    // write DOM to file
    Document doc = new Document(rootElem);
    outputter.output(doc, writer);
    writer.close();
}

From source file:de.nava.informa.exporters.RSS_2_0_Exporter.java

License:Open Source License

public void write(ChannelIF channel) throws IOException {
    if (writer == null) {
        throw new RuntimeException("No writer has been initialized.");
    }/*from   w  ww  .ja  v  a 2s.  co  m*/

    // create XML outputter with indent: 2 spaces, print new lines.
    Format format = Format.getPrettyFormat();
    format.setEncoding(encoding);
    XMLOutputter outputter = new XMLOutputter(format);

    Namespace dcNs = Namespace.getNamespace("dc", NS_DC);
    Namespace syNs = Namespace.getNamespace("sy", NS_SY);
    Namespace adminNs = Namespace.getNamespace("admin", NS_ADMIN);
    //Namespace rdfNs = Namespace.getNamespace("rdf", NS_RDF);

    Element rootElem = new Element("rss");
    rootElem.addNamespaceDeclaration(dcNs);
    rootElem.addNamespaceDeclaration(syNs);
    rootElem.addNamespaceDeclaration(adminNs);
    rootElem.setAttribute("version", RSS_VERSION);

    Element channelElem = new Element("channel");
    // rootElem.setAttribute("version");
    channelElem.addContent(new Element("title").setText(channel.getTitle()));
    if (channel.getSite() != null) {
        channelElem.addContent(new Element("link").setText(channel.getSite().toString()));
    }

    channelElem.addContent(new Element("description").setText(channel.getDescription()));
    if (channel.getLanguage() != null) {
        channelElem.addContent(new Element("language", dcNs).setText(channel.getLanguage()));
    }
    if (channel.getCopyright() != null) {
        channelElem.addContent(new Element("copyright", dcNs).setText(channel.getCopyright()));
    }
    if (channel.getPubDate() != null) {
        channelElem.addContent(new Element("pubDate").setText(ParserUtils.formatDate(channel.getPubDate())));
    }
    if (channel.getCategories() != null) {
        Collection categories = channel.getCategories();
        for (Object category : categories) {
            CategoryIF cat = (CategoryIF) category;
            channelElem = getCategoryElements(channelElem, cat, null);
        }
    }

    if (channel.getUpdateBase() != null) {
        channelElem.addContent(new Element("updateBase", syNs).setText(df.format(channel.getUpdateBase())));
    }
    if (channel.getUpdatePeriod() != null) {
        // don't put out frequency without specifying period
        channelElem.addContent(new Element("updateFrequency", syNs)
                .setText((new Integer(channel.getUpdateFrequency())).toString()));
        channelElem.addContent(new Element("updatePeriod", syNs).setText(channel.getUpdatePeriod().toString()));
    }
    // export channel image            
    if (channel.getImage() != null) {
        Element imgElem = new Element("image");
        imgElem.addContent(new Element("title").setText(channel.getImage().getTitle()));
        imgElem.addContent(new Element("url").setText(channel.getImage().getLocation().toString()));
        imgElem.addContent(new Element("link").setText(channel.getImage().getLink().toString()));
        imgElem.addContent(new Element("height").setText("" + channel.getImage().getHeight()));
        imgElem.addContent(new Element("width").setText("" + channel.getImage().getWidth()));
        imgElem.addContent(new Element("description").setText(channel.getImage().getDescription()));
        channelElem.addContent(imgElem);
    }

    // TODO: add exporting textinput field
    //     if (channel.getTextInput() != null) {
    //       channelElem.addContent(channel.getTextInput().getElement());
    //     }

    Collection items = channel.getItems();
    for (Object item : items) {
        channelElem.addContent(getItemElement((ItemIF) item));
    }

    rootElem.addContent(channelElem);

    // ---
    Document doc = new Document(rootElem);
    outputter.output(doc, writer);
    // ---
    writer.close();
}

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.
 * //from   w  w  w.  jav a 2  s. 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:fr.rt.acy.locapic.gps.TrackService.java

License:Open Source License

/**
 * Methode pour creer le document JDOM de base pour le fichier GPX
 * Prend en parametre des valeurs pour les metadonnees GPX (contenues dans la balise <metadata>)
 * @param name - Nom du fichier gpx (pour les metadonnees GPX)
 * @param desc - Description du fichier gpx (pour les metadonnees GPX)
 * @param authorsName - Nom de l'autheur de la trace (pour les metadonnees GPX)
 * @param authorsEmail - Email de l'autheur de la trace (pour les metadonnees GPX)
 * @param keywords - Mots-cle pour les metadonnees GPX
 * @return document - Le document JDOM servant de base GPX
 *///w  w w  .  j  a  va  2  s  .  co m
public Document createGpxDocTree(String name, String desc, String authorsName, String authorsEmail,
        String keywords) {
    /* Pour la date */
    Calendar calendar = Calendar.getInstance();
    Date date = calendar.getTime();
    // Format de la date
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
    StringBuilder dateBuilder = new StringBuilder(dateFormat.format(date));
    // Pour le format GPX, T apres la date et avant l'heure, et Z a la fin
    dateBuilder.append("Z");
    dateBuilder.insert(10, "T");
    // Conversion builder => string
    String formattedDate = dateBuilder.toString();
    Log.v(TAG, "TIME => " + formattedDate);

    /* Pour le reste des metadonnees perso */
    String mailId;
    String mailDomain;
    if (name == null)
        name = "LocaPic track";
    if (desc == null)
        desc = "GPS track logged on an Android device with an application from a project by Samuel Beaurepaire &amp; Virgile Beguin for IUT of Annecy (Fr), RT departement.";
    if (authorsName == null)
        authorsName = "Samuel Beaurepaire";
    if (authorsEmail == null) {
        mailId = "sjbeaurepaire";
        mailDomain = "orange.fr";
    } else {
        String[] mail = authorsEmail.split("@", 2);
        mailId = mail[0];
        mailDomain = mail[1];
    }

    // xsi du namespace a indique seulement pour la racine (addNamespaceDeclaratin())
    Namespace XSI = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    // Creation de la racine du fichier gpx (<gpx></gpx>) sous forme d'objet de classe Element avec le namespace gpx
    Element xml_gpx = new Element("gpx", ns);
    // Namespace XSI et attributs
    xml_gpx.addNamespaceDeclaration(XSI);
    xml_gpx.setAttribute(new Attribute("schemaLocation",
            "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd", XSI));
    xml_gpx.setAttribute(new Attribute("creator", "LocaPic"));
    xml_gpx.setAttribute(new Attribute("version", "1.1"));

    // On cree un nouveau Document JDOM base sur la racine que l'on vient de creer
    Document document = new Document(xml_gpx);
    // ~~~~~~~~~~~~~~~~ <metadata> ~~~~~~~~~~~~~~~~
    Element xml_metadata = new Element("metadata", ns);
    xml_gpx.addContent(xml_metadata);
    // ~~~~~~~~~~~~~~~~ <name> ~~~~~~~~~~~~~~~~
    Element xml_metadata_name = new Element("name", ns);
    xml_metadata_name.addContent(name);
    xml_metadata.addContent(xml_metadata_name);
    // ~~~~~~~~~~~~~~~~ <desc> ~~~~~~~~~~~~~~~~
    Element xml_metadata_desc = new Element("desc", ns);
    xml_metadata_desc.addContent(desc);
    xml_metadata.addContent(xml_metadata_desc);
    // ~~~~~~~~~~~~~~~~ <author> ~~~~~~~~~~~~~~~~
    Element xml_metadata_author = new Element("author", ns);
    // ~~~~~~~~~~~~~~~~ <author> ~~~~~~~~~~~~~~~~
    Element xml_metadata_author_name = new Element("name", ns);
    xml_metadata_author_name.addContent(authorsName);
    xml_metadata_author.addContent(xml_metadata_author_name);
    // ~~~~~~~~~~~~~~~~ <email> ~~~~~~~~~~~~~~~~
    Element xml_metadata_author_email = new Element("email", ns);
    xml_metadata_author_email.setAttribute("id", mailId);
    xml_metadata_author_email.setAttribute("domain", mailDomain);
    xml_metadata_author.addContent(xml_metadata_author_email);
    xml_metadata.addContent(xml_metadata_author);
    // ~~~~~~~~~~~~~~~~ <time> ~~~~~~~~~~~~~~~~
    Element xml_metadata_time = new Element("time", ns);
    xml_metadata_time.addContent(formattedDate);
    xml_metadata.addContent(xml_metadata_time);
    // ~~~~~~~~~~~~~~~~ <keywords> ~~~~~~~~~~~~~~~~
    if (keywords != null) {
        Element xml_keywords = new Element("keywords", ns);
        xml_keywords.addContent(keywords);
        xml_metadata.addContent(xml_keywords);
    }
    // ~~~~~~~~~~~~~~~~ <trk> ~~~~~~~~~~~~~~~~
    Element xml_trk = new Element("trk", ns);
    // ~~~~~~~~~~~~~~~~ <number> ~~~~~~~~~~~~~~~~
    Element xml_trk_number = new Element("number", ns);
    xml_trk_number.addContent("1");
    xml_trk.addContent(xml_trk_number);
    // ~~~~~~~~~~~~~~~~ <trkseg> ~~~~~~~~~~~~~~~~
    Element xml_trk_trkseg = new Element("trkseg", ns);
    xml_trk.addContent(xml_trk_trkseg);
    xml_gpx.addContent(xml_trk);

    return document;
}

From source file:io.wcm.maven.plugins.i18n.SlingI18nMap.java

License:Apache License

private Document getMixLanguageXmlDocument() {
    Document doc = new Document();
    Element root = new Element("root", NAMESPACE_JCR);
    root.addNamespaceDeclaration(NAMESPACE_JCR);
    root.addNamespaceDeclaration(NAMESPACE_MIX);
    root.addNamespaceDeclaration(NAMESPACE_NT);
    root.addNamespaceDeclaration(NAMESPACE_SLING);
    doc.setRootElement(root);//from w  ww  .  ja  v a  2 s.co m

    // add boiler plate
    root.setAttribute(JCR_PRIMARY_TYPE, JCR_NODETYPE_FOLDER, NAMESPACE_JCR);
    root.setAttribute(JCR_MIXIN_TYPES, "[" + StringUtils.join(JCR_MIX_LANGUAGE, ",") + "]", NAMESPACE_JCR);

    // add language
    root.setAttribute(JCR_LANGUAGE, languageKey, NAMESPACE_JCR);

    return doc;
}

From source file:lu.list.itis.dkd.assess.cloze.template.Template.java

License:Apache License

private Element layer() {
    Element layerElement = new Element("layer");
    Comment layerComment = new Comment(
            "this section represents an XML-QTI item with placeholders for variables");
    layerElement.addContent(layerComment);

    Namespace xmlnsNamespace = Namespace.getNamespace("http://www.imsglobal.org/xsd/imsqti_v2p0");
    Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    //        Namespace schemaLocation = Namespace.getNamespace("xsi:schemaLocation", "http://www.imsglobal.org/xsd/imsqti_v2p0 imsqti_v2p0.xsd");
    Element assessmentItem = new Element("assessmentItem", xmlnsNamespace);
    layerElement.addContent(assessmentItem);

    assessmentItem.addNamespaceDeclaration(xsi);
    //        assessmentItem.addNamespaceDeclaration(schemaLocation);
    assessmentItem.setAttribute("identifier", "ModalFeedback");
    assessmentItem.setAttribute("title", title);
    assessmentItem.setAttribute("adaptive", "false");
    assessmentItem.setAttribute("timeDependent", "false");

    assessmentItem.addContent(clozeItem.getCorrectResponseBlocks());
    if (useFeedback) {
        outcomeDeclarationFeedback(doc, assessmentItem);
    }//www  .j a va2 s. c  om

    //outcomeScoreDeclaration Score Element
    Element outcomeScoreDeclaration = new Element("outcomeDeclaration");
    assessmentItem.addContent(outcomeScoreDeclaration);
    outcomeScoreDeclaration.setAttribute("identifier", "SCORE");
    outcomeScoreDeclaration.setAttribute("cardinality", "single");
    outcomeScoreDeclaration.setAttribute("baseType", "float");

    //defaultScoreValue Element 
    Element defaultScoreValue = new Element("defaultValue");
    outcomeScoreDeclaration.addContent(defaultScoreValue);

    //scoreValue element
    Element scoreValue = new Element("value");
    scoreValue.setText("0");
    defaultScoreValue.addContent(scoreValue);

    Element itemBody = new Element("itemBody");
    assessmentItem.addContent(itemBody);

    Element blockquote = new Element("blockquote");
    itemBody.addContent(blockquote);

    //Add qti cloze text
    blockquote.addContent(clozeItem.getClozeBlock());

    Element responseProcessing = new Element("responseProcessing");
    assessmentItem.addContent(responseProcessing);

    //Add feedback
    if (useFeedback) {
        for (ClozeSentence clozeSentence : clozeItem.getClozeSentences()) {
            int keyIndex = 1;
            for (Key key : clozeSentence.getKeys()) {
                Element correctModalFeedback = new Element("modalFeedback");
                correctModalFeedback.setAttribute("outcomeIdentifier", "FEEDBACK_CORRECT" + keyIndex);
                correctModalFeedback.setAttribute("showHide", "show");
                correctModalFeedback.setAttribute("identifier", "correctFeedback");
                correctModalFeedback.setText(key.getFeedback());
                assessmentItem.addContent(correctModalFeedback);

                int distractorIndex = 2;
                for (Distractor distractor : key.getDistractors()) {
                    Element incorrectModalFeedback = new Element("modalFeedback");
                    incorrectModalFeedback.setAttribute("outcomeIdentifier",
                            "FEEDBACK_INCORRECT" + (distractorIndex));
                    incorrectModalFeedback.setAttribute("showHide", "show");
                    incorrectModalFeedback.setAttribute("identifier", "incorrectFeedback");
                    incorrectModalFeedback.setText(distractor.getFeedback());
                    assessmentItem.addContent(incorrectModalFeedback);
                    distractorIndex++;
                }
                distractorIndex++;
            }
        }
    }

    return layerElement;
}

From source file:net.instantcom.mm7.MM7Message.java

License:Open Source License

private Element toSOAP(MM7Context ctx) {
    Element env = new Element("Envelope", ENVELOPE);
    if (namespace != null) {
        env.addNamespaceDeclaration(namespace);
    }/*ww w. j  a v  a2 s .  c  om*/
    Element header = new Element("Header", ENVELOPE);
    if (transactionId != null) {
        header.addContent(new Element("TransactionID", namespace) //
                .setText(transactionId) //
                .setAttribute("mustUnderstand", "1", ENVELOPE));
    }
    env.addContent(header);

    Element body = new Element("Body", ENVELOPE);
    body.addContent(save(body));
    env.addContent(body);
    return env;
}

From source file:org.apache.wiki.rss.RSS10Feed.java

License:Apache License

/**
 * {@inheritDoc}/*from   w ww.  j  av  a 2s .c  o m*/
 */
@Override
public String getString() {
    Element root = new Element("RDF", NS_RDF);
    root.addContent(getChannelElement());
    root.addNamespaceDeclaration(NS_XMNLS);
    root.addNamespaceDeclaration(NS_RDF);
    root.addNamespaceDeclaration(NS_DC);
    root.addNamespaceDeclaration(NS_WIKI);
    addItemList(root);

    return XhtmlUtil.serialize(root, true);
}