Example usage for org.jdom2 Document Document

List of usage examples for org.jdom2 Document Document

Introduction

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

Prototype

public Document() 

Source Link

Document

Creates a new empty document.

Usage

From source file:org.openflexo.foundation.fml.rm.ViewPointResourceImpl.java

License:Open Source License

private static void convertDiagramSpecification16ToVirtualModel17(File file, Document diagram,
        List<File> oldPaletteFiles, List<File> oldExampleDiagramFiles, ViewPointResource viewPointResource) {

    // Create the diagram specification and a virtual model with a diagram typed model slot referencing this diagram specification

    final String ADDRESSED_DIAGRAM_MODEL_SLOT = "AddressedDiagramModelSlot";
    final String MODELSLOT_VIRTUAL_MODEL_MODEL_SLOT = "ModelSlot_VirtualModelModelSlot";
    final String MODELSLOT_TYPED_DIAGRAM_MODEL_SLOT = "ModelSlot_TypedDiagramModelSlot";

    try {//ww  w  . j a  v  a2s  .  c  o  m
        String diagramName = file.getName().replace(".xml", "");
        // Create a folder that contains the diagram specification
        File diagramSpecificationFolder = new File(
                file.getParentFile() + "/" + diagramName + ".diagramspecification");
        diagramSpecificationFolder.mkdir();

        // Retrieve diagram drop schemes
        Iterator<Element> dropSchemeElements = diagram.getDescendants(new ElementFilter("DropScheme"));
        List<Element> dropSchemes = IteratorUtils.toList(dropSchemeElements);

        // Retrieve Diagram Model slots references
        Iterator<? extends Content> thisModelSlotsIterator = diagram.getDescendants(
                new ElementFilter("DiagramModelSlot").or(new ElementFilter(ADDRESSED_DIAGRAM_MODEL_SLOT)));
        List<Element> thisModelSlots = IteratorUtils.toList(thisModelSlotsIterator);

        // Retrieve the DiagramModelSlot (this), and transform it to a virtual model slot with a virtual model uri
        int thisID = 0;
        String newThisUri = viewPointResource.getURI() + "/" + diagramName;
        String diagramSpecificationURI = newThisUri + "/" + diagramName + ".diagramspecification";
        Element typedDiagramModelSlot = null;
        boolean foundThis = false;
        for (Element thisMs : thisModelSlots) {
            // Retriev the ID and URI of this DiagramModelSlot
            if (thisMs.getAttribute("name") != null && thisMs.getAttributeValue("name").equals("this")
                    && !foundThis) {
                // Store its ID and its URI
                thisID = thisMs.getAttribute("id").getIntValue();
                if (thisMs.getAttributeValue("virtualModelURI") != null) {
                    newThisUri = thisMs.getAttributeValue("virtualModelURI");
                    thisMs.removeAttribute("virtualModelURI");
                    thisMs.removeAttribute("name");
                    thisMs.getAttribute("id").setName("idref");
                    thisMs.setAttribute("idref", Integer.toString(thisID));
                }
                // Replace by a Typed model slot
                typedDiagramModelSlot = new Element(MODELSLOT_TYPED_DIAGRAM_MODEL_SLOT);
                typedDiagramModelSlot.setAttribute("metaModelURI", diagramSpecificationURI);
                typedDiagramModelSlot.setAttribute("name", "typedDiagramModelSlot");
                typedDiagramModelSlot.setAttribute("id", Integer.toString(computeNewID(diagram)));
                foundThis = true;
            }
        }
        // Replace the Diagram Model Slot by a Virtual Model Model slot
        for (Element thisMs : thisModelSlots) {
            if (hasSameID(thisMs, thisID) && thisMs.getName().equals("DiagramModelSlot")) {
                thisMs.setName("FMLRTModelSlot");
                thisMs.getAttributes().add(new Attribute("virtualModelURI", newThisUri));
                thisMs.getAttributes().add(new Attribute("name", "virtualModelInstance"));
                thisMs.getAttributes().add(new Attribute("id", Integer.toString(thisID)));
                thisMs.removeAttribute("idref");
            }
        }
        // Update ids for all model slots
        Iterator<? extends Content> diagramModelSlotsIterator = diagram.getDescendants(
                new ElementFilter("DiagramModelSlot").or(new ElementFilter(ADDRESSED_DIAGRAM_MODEL_SLOT)));
        List<Element> thisDiagramModelSlots = IteratorUtils.toList(diagramModelSlotsIterator);
        for (Element diagramMs : thisDiagramModelSlots) {
            if (diagramMs.getAttribute("id") != null && typedDiagramModelSlot != null) {
                diagramMs.setAttribute("id", typedDiagramModelSlot.getAttributeValue("id"));
            }
            if (diagramMs.getAttribute("idref") != null) {
                // Change to TypedDiagramModelSlot
                if (diagramMs.getParentElement().getName().equals("AddShape")
                        || diagramMs.getParentElement().getName().equals("AddConnector")
                        || diagramMs.getParentElement().getName().equals("AddDiagram")
                        || diagramMs.getParentElement().getName().equals("ContainedShapePatternRole")
                        || diagramMs.getParentElement().getName().equals("ContainedConnectorPatternRole")
                        || diagramMs.getParentElement().getName().equals("ContainedDiagramPatternRole")) {
                    if (typedDiagramModelSlot.getAttributeValue("id") != null) {
                        diagramMs.setAttribute("idref", typedDiagramModelSlot.getAttributeValue("id"));
                        diagramMs.setName("TypedDiagramModelSlot");
                    }
                } else {
                    diagramMs.setName(MODELSLOT_VIRTUAL_MODEL_MODEL_SLOT);
                }
            }
        }
        for (Content content : diagram.getDescendants()) {
            if (content instanceof Element) {
                Element element = (Element) content;
                if (element.getName().equals("AddShape") || element.getName().equals("AddConnector")
                        || element.getName().equals("AddDiagram")) {
                    if (element.getChild("TypedDiagramModelSlot") == null
                            && element.getChild("AddressedDiagramModelSlot") == null) {
                        Element adressedMsElement = new Element("TypedDiagramModelSlot");
                        Attribute newIdRefAttribute = new Attribute("idref",
                                typedDiagramModelSlot.getAttributeValue("id"));
                        adressedMsElement.getAttributes().add(newIdRefAttribute);
                        element.addContent(adressedMsElement);
                    }
                }
            }
        }

        // Update DiagramSpecification URI
        for (Content content : diagram.getDescendants()) {
            if (content instanceof Element) {
                Element element = (Element) content;
                if (element.getAttribute("diagramSpecificationURI") != null) {
                    String oldDiagramSpecificationUri = element.getAttributeValue("diagramSpecificationURI");
                    String diagramSpecificationName = oldDiagramSpecificationUri
                            .substring(oldDiagramSpecificationUri.lastIndexOf("/"));
                    String newDiagramSpecificationUri = oldDiagramSpecificationUri + diagramSpecificationName
                            + ".diagramspecification";
                    element.getAttribute("diagramSpecificationURI").setValue(newDiagramSpecificationUri);
                }
            }
        }

        // Change all the "diagram" binding with "this", and "toplevel" with typedDiagramModelSlot.topLevel" in case of not
        // DropSchemeAction
        for (Content content : diagram.getDescendants()) {
            if (content instanceof Element) {
                Element element = (Element) content;
                for (Attribute attribute : element.getAttributes()) {
                    if (attribute.getValue().startsWith("diagram")) {
                        attribute.setValue(attribute.getValue().replace("diagram", "this"));
                    }
                    if (attribute.getValue().startsWith("topLevel")) {
                        boolean diagramScheme = false;
                        Element parentElement = element.getParentElement();
                        while (parentElement != null) {
                            if (parentElement.getName().equals("DropScheme")
                                    || parentElement.getName().equals("LinkScheme")) {
                                diagramScheme = true;
                            }
                            parentElement = parentElement.getParentElement();
                        }
                        if (!diagramScheme) {
                            attribute.setValue(attribute.getValue().replace("topLevel",
                                    "virtualModelInstance.typedDiagramModelSlot"));
                        }
                    }
                }
            }
        }

        // Create the diagram specificaion xml file
        File diagramSpecificationFile = new File(diagramSpecificationFolder, file.getName());
        Document diagramSpecification = new Document();
        Element rootElement = new Element("DiagramSpecification");
        Attribute name = new Attribute("name", diagramName);
        Attribute diagramSpecificationURIAttribute = new Attribute("uri", diagramSpecificationURI);
        diagramSpecification.addContent(rootElement);
        rootElement.getAttributes().add(name);
        rootElement.getAttributes().add(diagramSpecificationURIAttribute);
        XMLUtils.saveXMLFile(diagramSpecification, diagramSpecificationFile);

        // Copy the palette files inside diagram specification repository
        ArrayList<File> newPaletteFiles = new ArrayList<File>();
        for (File paletteFile : oldPaletteFiles) {
            File newFile = new File(diagramSpecificationFolder + "/" + paletteFile.getName());
            FileUtils.rename(paletteFile, newFile);
            newPaletteFiles.add(newFile);
            Document palette = XMLUtils.readXMLFile(newFile);
            Attribute diagramSpecUri = new Attribute("diagramSpecificationURI", diagramSpecificationURI);
            palette.getRootElement().getAttributes().add(diagramSpecUri);
            convertNames16ToNames17(palette);
            XMLUtils.saveXMLFile(palette, newFile);
        }

        // Copy the example diagram files inside diagram specification repository
        ArrayList<File> newExampleDiagramFiles = new ArrayList<File>();
        for (File exampleDiagramFile : oldExampleDiagramFiles) {
            File newFile = new File(diagramSpecificationFolder + "/" + exampleDiagramFile.getName());
            FileUtils.rename(exampleDiagramFile, newFile);
            newExampleDiagramFiles.add(newFile);
            Document exampleDiagram = XMLUtils.readXMLFile(newFile);
            exampleDiagram.getRootElement().setAttribute("uri",
                    diagramSpecificationURI + "/" + exampleDiagram.getRootElement().getAttributeValue("name"));
            Attribute diagramSpecUri = new Attribute("diagramSpecificationURI", diagramSpecificationURI);
            exampleDiagram.getRootElement().getAttributes().add(diagramSpecUri);
            exampleDiagram.getRootElement().setAttribute("uri",
                    diagramSpecificationURI + "/" + exampleDiagram.getRootElement().getAttributeValue("name"));
            convertNames16ToNames17(exampleDiagram);
            XMLUtils.saveXMLFile(exampleDiagram, newFile);
        }

        // Update the diagram palette element bindings
        ArrayList<Element> paletteElementBindings = new ArrayList<Element>();
        for (File paletteFile : newPaletteFiles) {
            Document palette = XMLUtils.readXMLFile(paletteFile);
            String paletteUri = diagramSpecificationURI + "/"
                    + palette.getRootElement().getAttribute("name").getValue() + ".palette";
            Iterator<? extends Content> paletteElements = palette
                    .getDescendants(new ElementFilter("DiagramPaletteElement"));
            while (paletteElements.hasNext()) {
                Element paletteElement = (Element) paletteElements.next();
                Element binding = createPaletteElementBinding(paletteElement, paletteUri, dropSchemes);
                if (binding != null) {
                    paletteElementBindings.add(binding);
                }
            }
            XMLUtils.saveXMLFile(palette, paletteFile);
        }
        // Add the Palette Element Bindings to the TypedDiagramModelSlot
        if (!paletteElementBindings.isEmpty()) {
            typedDiagramModelSlot.addContent(paletteElementBindings);
        }
        if (typedDiagramModelSlot != null) {
            diagram.getRootElement().addContent(typedDiagramModelSlot);
        }

        // Update names
        convertNames16ToNames17(diagram);
        convertOldNameToNewNames("DiagramSpecification", "VirtualModel", diagram);

        // Save the files
        XMLUtils.saveXMLFile(diagram, file);

    } catch (JDOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.openflexo.foundation.viewpoint.rm.ViewPointResourceImpl.java

License:Open Source License

private static void convertDiagramSpecification16ToVirtualModel17(File file, Document diagram,
        List<File> oldPaletteFiles, List<File> oldExampleDiagramFiles, ViewPointResource viewPointResource) {

    // Create the diagram specification and a virtual model with a diagram typed model slot referencing this diagram specification

    final String ADDRESSED_DIAGRAM_MODEL_SLOT = "AddressedDiagramModelSlot";
    final String MODELSLOT_VIRTUAL_MODEL_MODEL_SLOT = "ModelSlot_VirtualModelModelSlot";
    final String MODELSLOT_TYPED_DIAGRAM_MODEL_SLOT = "ModelSlot_TypedDiagramModelSlot";

    try {//  ww w .  j  a  v  a 2s . c  o  m
        String diagramName = file.getName().replace(".xml", "");
        // Create a folder that contains the diagram specification
        File diagramSpecificationFolder = new File(
                file.getParentFile() + "/" + diagramName + ".diagramspecification");
        diagramSpecificationFolder.mkdir();

        // Retrieve diagram drop schemes
        Iterator<Element> dropSchemeElements = diagram.getDescendants(new ElementFilter("DropScheme"));
        List<Element> dropSchemes = IteratorUtils.toList(dropSchemeElements);

        // Retrieve Diagram Model slots references
        Iterator<? extends Content> thisModelSlotsIterator = diagram.getDescendants(
                new ElementFilter("DiagramModelSlot").or(new ElementFilter(ADDRESSED_DIAGRAM_MODEL_SLOT)));
        List<Element> thisModelSlots = IteratorUtils.toList(thisModelSlotsIterator);

        // Retrieve the DiagramModelSlot (this), and transform it to a virtual model slot with a virtual model uri
        int thisID = 0;
        String newThisUri = viewPointResource.getURI() + "/" + diagramName;
        String diagramSpecificationURI = newThisUri + "/" + diagramName + ".diagramspecification";
        Element typedDiagramModelSlot = null;
        boolean foundThis = false;
        for (Element thisMs : thisModelSlots) {
            // Retriev the ID and URI of this DiagramModelSlot
            if (thisMs.getAttribute("name") != null && thisMs.getAttributeValue("name").equals("this")
                    && !foundThis) {
                // Store its ID and its URI
                thisID = thisMs.getAttribute("id").getIntValue();
                if (thisMs.getAttributeValue("virtualModelURI") != null) {
                    newThisUri = thisMs.getAttributeValue("virtualModelURI");
                    thisMs.removeAttribute("virtualModelURI");
                    thisMs.removeAttribute("name");
                    thisMs.getAttribute("id").setName("idref");
                    thisMs.setAttribute("idref", Integer.toString(thisID));
                }
                // Replace by a Typed model slot
                typedDiagramModelSlot = new Element(MODELSLOT_TYPED_DIAGRAM_MODEL_SLOT);
                typedDiagramModelSlot.setAttribute("metaModelURI", diagramSpecificationURI);
                typedDiagramModelSlot.setAttribute("name", "typedDiagramModelSlot");
                typedDiagramModelSlot.setAttribute("id", Integer.toString(computeNewID(diagram)));
                foundThis = true;
            }
        }
        // Replace the Diagram Model Slot by a Virtual Model Model slot
        for (Element thisMs : thisModelSlots) {
            if (hasSameID(thisMs, thisID) && thisMs.getName().equals("DiagramModelSlot")) {
                thisMs.setName("VirtualModelModelSlot");
                thisMs.getAttributes().add(new Attribute("virtualModelURI", newThisUri));
                thisMs.getAttributes().add(new Attribute("name", "virtualModelInstance"));
                thisMs.getAttributes().add(new Attribute("id", Integer.toString(thisID)));
                thisMs.removeAttribute("idref");
            }
        }
        // Update ids for all model slots
        Iterator<? extends Content> diagramModelSlotsIterator = diagram.getDescendants(
                new ElementFilter("DiagramModelSlot").or(new ElementFilter(ADDRESSED_DIAGRAM_MODEL_SLOT)));
        List<Element> thisDiagramModelSlots = IteratorUtils.toList(diagramModelSlotsIterator);
        for (Element diagramMs : thisDiagramModelSlots) {
            if (diagramMs.getAttribute("id") != null && typedDiagramModelSlot != null) {
                diagramMs.setAttribute("id", typedDiagramModelSlot.getAttributeValue("id"));
            }
            if (diagramMs.getAttribute("idref") != null) {
                // Change to TypedDiagramModelSlot
                if (diagramMs.getParentElement().getName().equals("AddShape")
                        || diagramMs.getParentElement().getName().equals("AddConnector")
                        || diagramMs.getParentElement().getName().equals("AddDiagram")
                        || diagramMs.getParentElement().getName().equals("ContainedShapePatternRole")
                        || diagramMs.getParentElement().getName().equals("ContainedConnectorPatternRole")
                        || diagramMs.getParentElement().getName().equals("ContainedDiagramPatternRole")) {
                    if (typedDiagramModelSlot.getAttributeValue("id") != null) {
                        diagramMs.setAttribute("idref", typedDiagramModelSlot.getAttributeValue("id"));
                        diagramMs.setName("TypedDiagramModelSlot");
                    }
                } else {
                    diagramMs.setName(MODELSLOT_VIRTUAL_MODEL_MODEL_SLOT);
                }
            }
        }
        for (Content content : diagram.getDescendants()) {
            if (content instanceof Element) {
                Element element = (Element) content;
                if (element.getName().equals("AddShape") || element.getName().equals("AddConnector")
                        || element.getName().equals("AddDiagram")) {
                    if (element.getChild("TypedDiagramModelSlot") == null
                            && element.getChild("AddressedDiagramModelSlot") == null) {
                        Element adressedMsElement = new Element("TypedDiagramModelSlot");
                        Attribute newIdRefAttribute = new Attribute("idref",
                                typedDiagramModelSlot.getAttributeValue("id"));
                        adressedMsElement.getAttributes().add(newIdRefAttribute);
                        element.addContent(adressedMsElement);
                    }
                }
            }
        }

        // Update DiagramSpecification URI
        for (Content content : diagram.getDescendants()) {
            if (content instanceof Element) {
                Element element = (Element) content;
                if (element.getAttribute("diagramSpecificationURI") != null) {
                    String oldDiagramSpecificationUri = element.getAttributeValue("diagramSpecificationURI");
                    String diagramSpecificationName = oldDiagramSpecificationUri
                            .substring(oldDiagramSpecificationUri.lastIndexOf("/"));
                    String newDiagramSpecificationUri = oldDiagramSpecificationUri + diagramSpecificationName
                            + ".diagramspecification";
                    element.getAttribute("diagramSpecificationURI").setValue(newDiagramSpecificationUri);
                }
            }
        }

        // Change all the "diagram" binding with "this", and "toplevel" with typedDiagramModelSlot.topLevel" in case of not
        // DropSchemeAction
        for (Content content : diagram.getDescendants()) {
            if (content instanceof Element) {
                Element element = (Element) content;
                for (Attribute attribute : element.getAttributes()) {
                    if (attribute.getValue().startsWith("diagram")) {
                        attribute.setValue(attribute.getValue().replace("diagram", "this"));
                    }
                    if (attribute.getValue().startsWith("topLevel")) {
                        boolean diagramScheme = false;
                        Element parentElement = element.getParentElement();
                        while (parentElement != null) {
                            if (parentElement.getName().equals("DropScheme")
                                    || parentElement.getName().equals("LinkScheme")) {
                                diagramScheme = true;
                            }
                            parentElement = parentElement.getParentElement();
                        }
                        if (!diagramScheme) {
                            attribute.setValue(attribute.getValue().replace("topLevel",
                                    "virtualModelInstance.typedDiagramModelSlot"));
                        }
                    }
                }
            }
        }

        // Create the diagram specificaion xml file
        File diagramSpecificationFile = new File(diagramSpecificationFolder, file.getName());
        Document diagramSpecification = new Document();
        Element rootElement = new Element("DiagramSpecification");
        Attribute name = new Attribute("name", diagramName);
        Attribute diagramSpecificationURIAttribute = new Attribute("uri", diagramSpecificationURI);
        diagramSpecification.addContent(rootElement);
        rootElement.getAttributes().add(name);
        rootElement.getAttributes().add(diagramSpecificationURIAttribute);
        XMLUtils.saveXMLFile(diagramSpecification, diagramSpecificationFile);

        // Copy the palette files inside diagram specification repository
        ArrayList<File> newPaletteFiles = new ArrayList<File>();
        for (File paletteFile : oldPaletteFiles) {
            File newFile = new File(diagramSpecificationFolder + "/" + paletteFile.getName());
            FileUtils.rename(paletteFile, newFile);
            newPaletteFiles.add(newFile);
            Document palette = XMLUtils.readXMLFile(newFile);
            Attribute diagramSpecUri = new Attribute("diagramSpecificationURI", diagramSpecificationURI);
            palette.getRootElement().getAttributes().add(diagramSpecUri);
            convertNames16ToNames17(palette);
            XMLUtils.saveXMLFile(palette, newFile);
        }

        // Copy the example diagram files inside diagram specification repository
        ArrayList<File> newExampleDiagramFiles = new ArrayList<File>();
        for (File exampleDiagramFile : oldExampleDiagramFiles) {
            File newFile = new File(diagramSpecificationFolder + "/" + exampleDiagramFile.getName());
            FileUtils.rename(exampleDiagramFile, newFile);
            newExampleDiagramFiles.add(newFile);
            Document exampleDiagram = XMLUtils.readXMLFile(newFile);
            exampleDiagram.getRootElement().setAttribute("uri",
                    diagramSpecificationURI + "/" + exampleDiagram.getRootElement().getAttributeValue("name"));
            Attribute diagramSpecUri = new Attribute("diagramSpecificationURI", diagramSpecificationURI);
            exampleDiagram.getRootElement().getAttributes().add(diagramSpecUri);
            exampleDiagram.getRootElement().setAttribute("uri",
                    diagramSpecificationURI + "/" + exampleDiagram.getRootElement().getAttributeValue("name"));
            convertNames16ToNames17(exampleDiagram);
            XMLUtils.saveXMLFile(exampleDiagram, newFile);
        }

        // Update the diagram palette element bindings
        ArrayList<Element> paletteElementBindings = new ArrayList<Element>();
        for (File paletteFile : newPaletteFiles) {
            Document palette = XMLUtils.readXMLFile(paletteFile);
            String paletteUri = diagramSpecificationURI + "/"
                    + palette.getRootElement().getAttribute("name").getValue() + ".palette";
            Iterator<? extends Content> paletteElements = palette
                    .getDescendants(new ElementFilter("DiagramPaletteElement"));
            while (paletteElements.hasNext()) {
                Element paletteElement = (Element) paletteElements.next();
                Element binding = createPaletteElementBinding(paletteElement, paletteUri, dropSchemes);
                if (binding != null) {
                    paletteElementBindings.add(binding);
                }
            }
            XMLUtils.saveXMLFile(palette, paletteFile);
        }
        // Add the Palette Element Bindings to the TypedDiagramModelSlot
        if (!paletteElementBindings.isEmpty()) {
            typedDiagramModelSlot.addContent(paletteElementBindings);
        }
        if (typedDiagramModelSlot != null) {
            diagram.getRootElement().addContent(typedDiagramModelSlot);
        }

        // Update names
        convertNames16ToNames17(diagram);
        convertOldNameToNewNames("DiagramSpecification", "VirtualModel", diagram);

        // Save the files
        XMLUtils.saveXMLFile(diagram, file);

    } catch (JDOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.opengroup.archimate.xmlexchange.XMLModelExporter.java

License:Open Source License

/**
 * @return A JDOM Document
 */
Document createDocument() {
    return new Document();
}

From source file:org.openkennel.model.filemngr.XMLFileHandler.java

License:Open Source License

/**
 * Creates a XMLFileHandler to handle specific XML files.
 *///  w  w  w  .  jav a2  s. c o  m
public XMLFileHandler() {
    docBuilder = new SAXBuilder();
    xmlRoot = null;
    xmlFile = new Document();
}

From source file:org.optaconf.benchmark.examples.common.persistence.AbstractXmlSolutionExporter.java

License:Apache License

public void writeSolution(Solution solution, File outputFile) {
    OutputStream out = null;// www  .  j  ava2s  .  c  o m
    try {
        out = new FileOutputStream(outputFile);
        Document document = new Document();
        XmlOutputBuilder xmlOutputBuilder = createXmlOutputBuilder();
        xmlOutputBuilder.setDocument(document);
        xmlOutputBuilder.setSolution(solution);
        xmlOutputBuilder.writeSolution();
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        outputter.output(document, out);
    } catch (IOException e) {
        throw new IllegalArgumentException("Could not write the file (" + outputFile.getName() + ").", e);
    } catch (JDOMException e) {
        throw new IllegalArgumentException("Could not format the XML file (" + outputFile.getName() + ").", e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    logger.info("Exported: {}", outputFile);
}

From source file:org.polago.deployconf.DeploymentWriter.java

License:Open Source License

/**
 * Write the given DeploymentConfig to persistent storage.
 *
 * @param deploymentConfig the DeploymentConfig to persist
 * @throws IOException indicating IO problems
 *//*from  w w  w.j  a  v  a 2 s .  co m*/
public void persist(DeploymentConfig deploymentConfig) throws IOException {
    Format format = Format.getPrettyFormat();
    format.setLineSeparator(LineSeparator.UNIX);
    format.setExpandEmptyElements(true);
    XMLOutputter outputter = new XMLOutputter(format);

    Element root = new Element(DOM_ROOT);
    String name = deploymentConfig.getName();
    if (name != null) {
        root.setAttribute(ATTR_NAME, name);
    }
    Document document = new Document();
    document.setRootElement(root);

    for (Task task : deploymentConfig.getTasks()) {
        Element node = new Element(task.getSerializedName());
        root.addContent(node);
        task.serialize(node, groupManager);
    }

    outputter.output(document, outputStream);
}

From source file:org.t3.metamediamanager.FieldsConfig.java

License:Apache License

public FieldsConfig(String baseName) {
    String filename = M3Config.getInstance().getUserConfDirectory() + baseName + ".xml";

    _configFile = new File(filename);
    if (!_configFile.exists())
        M3Config.getInstance().copyResourceToUserDir(baseName + ".xml", baseName + ".xml");

    Document document = new Document();
    Element root;//from ww  w.  j a v a  2s.co m
    //On cre une instance de SAXBuilder
    SAXBuilder sxb = new SAXBuilder();
    try {
        //On cre un nouveau document JDOM avec en argument le fichier XML
        //Le parsing est termin ;)
        document = sxb.build(_configFile);
    } catch (Exception e) {
        System.out.println("Erreur lors de l'ouverture du fichier de configuration de " + baseName);
    }

    //On initialise un nouvel lment racine avec l'lment racine du document.
    root = document.getRootElement();

    //Remplissage des paramtres de provider           
    List<Element> listFields = root.getChildren("field");

    Iterator<Element> i2 = listFields.iterator();
    while (i2.hasNext()) {
        Element currentField = i2.next();
        _fieldsAssociation.put(currentField.getAttributeValue("name"),
                currentField.getAttributeValue("markup"));
    }
}

From source file:org.xflatdb.xflat.convert.converters.JavaBeansPojoConverter.java

License:Apache License

private static <U> Converter<Element, U> getDecoder(Class<U> clazz) {
    return new Converter<Element, U>() {

        final String version = System.getProperty("java.version");

        @Override//  w w  w.jav a  2 s  . co  m
        public U convert(Element source) throws ConversionException {
            byte[] bytes;
            try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {

                Document doc = new Document();
                doc.setRootElement(new Element("java").setAttribute("version", version).setAttribute("class",
                        "java.beans.XMLDecoder"));

                doc.getRootElement().addContent(source.detach());

                XMLOutputter outputter = new XMLOutputter();
                outputter.output(doc, os);

                bytes = os.toByteArray();
            } catch (IOException ex) {
                throw new ConversionException("Error reading object of class " + source.getClass(), ex);
            }

            try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {

                try (XMLDecoder decoder = new XMLDecoder(is)) {
                    return (U) decoder.readObject();
                }
            } catch (IOException ex) {
                throw new ConversionException("Error reading object of class " + source.getClass(), ex);
            }
        }
    };
}

From source file:org.xflatdb.xflat.db.TableMetadataFactory.java

License:Apache License

/**
 * Saves the given metadata to disk.//w ww. j  ava2s  .co  m
 * @param metadata The metadata to save.
 * @throws IOException 
 */
public void saveTableMetadata(TableMetadata metadata) throws IOException {
    Document doc = new Document();
    doc.setRootElement(new Element("metadata", XFlatConstants.xFlatNs));

    //save config
    if (metadata.config != null) {
        Element cfg;
        try {
            cfg = TableConfig.ToElementConverter.convert(metadata.config);
        } catch (ConversionException ex) {
            throw new XFlatException("Cannot serialize table metadata", ex);
        }
        doc.getRootElement().addContent(cfg);
    }

    //save generator
    if (metadata.idGenerator != null) {
        Element g = new Element("generator", XFlatConstants.xFlatNs);
        g.setAttribute("class", metadata.idGenerator.getClass().getName(), XFlatConstants.xFlatNs);
        metadata.idGenerator.saveState(g);

        doc.getRootElement().addContent(g);
    }

    //save engine
    Element e = metadata.engineMetadata.clone();

    doc.getRootElement().addContent(e);

    this.wrapper.writeFile(metadata.name + ".config.xml", doc);
}

From source file:org.xflatdb.xflat.engine.CachedDocumentEngine.java

License:Apache License

/**
 * Dumps the cache immediately, on this thread.
 * @param required true if a dump is absolutely required, false to allow this
 * method to choose not to dump if it feels that a dump is unnecessary.
 */// w w  w.  j  ava 2s  .  com
private void dumpCacheNow(boolean required) {
    synchronized (dumpSyncRoot) {
        if (!required && lastModified.get() < lastDump.get()) {
            //no need to dump
            return;
        }

        long lastDump = System.currentTimeMillis();

        Document doc = new Document();
        Element root = new Element("table", XFlatConstants.xFlatNs).setAttribute("name", this.getTableName(),
                XFlatConstants.xFlatNs);
        doc.setRootElement(root);

        for (Row row : this.cache.values()) {
            synchronized (row) {
                Element rowEl = null;

                int nonDeleteData = 0;

                //put ALL committed data to disk, even some that might otherwise
                //be cleaned up, because we may be in the process of committing
                //one of N engines and will need all previous values if we revert.
                for (RowData rData : row.rowData.values()) {
                    if (rData == null)
                        continue;

                    if (rData.commitId == -1)
                        //uncommitted data is not put to disk
                        continue;

                    if (rowEl == null) {
                        rowEl = new Element("row", XFlatConstants.xFlatNs);
                        setId(rowEl, row.rowId);
                    }

                    Element dataEl;
                    if (rData.data == null) {
                        //the data was deleted - make sure we mark that on the row
                        dataEl = new Element("delete", XFlatConstants.xFlatNs);
                    } else {
                        dataEl = rData.data.clone();
                        nonDeleteData++;
                    }

                    dataEl.setAttribute("tx", Long.toString(rData.transactionId, TRANSACTION_ID_RADIX),
                            XFlatConstants.xFlatNs);
                    dataEl.setAttribute("commit", Long.toString(rData.commitId, TRANSACTION_ID_RADIX),
                            XFlatConstants.xFlatNs);

                    rowEl.addContent(dataEl);
                }

                //doublecheck - only write out an element if there's actually
                //any data to write.  Delete marker elements don't count.
                if (rowEl != null && nonDeleteData > 0) {
                    root.addContent(rowEl);
                }
            }
        }

        try {
            this.file.writeFile(doc);
        } catch (FileNotFoundException ex) {
            //this is a transient issue that may be caused by another process opening the file quickly,
            //the message is generally "The requested operation cannot be performed on a file with a user-mapped section open"
            int failures = dumpFailures.incrementAndGet();
            if (failures > 3)
                throw new XFlatException("Unable to dump cache to file", ex);

            try {
                Thread.sleep(50);
            } catch (InterruptedException interruptedEx) {
            }

            //try again
            dumpCacheNow(required);
            return;
        } catch (Exception ex) {
            dumpFailures.incrementAndGet();
            throw new XFlatException("Unable to dump cache to file", ex);
        } finally {
            scheduledDump.set(null);
            this.lastDump.set(lastDump);
        }

        //success!
        dumpFailures.set(0);
    }
}