Example usage for org.dom4j.io XMLWriter write

List of usage examples for org.dom4j.io XMLWriter write

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter write.

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

From source file:fr.gouv.culture.vitam.command.VitamCommand.java

License:Open Source License

public static void computeDigest() {
    XMLWriter writer = null;
    try {// ww  w .j ava  2 s. c o m
        writer = new XMLWriter(outputStream, StaticValues.defaultOutputFormat);
    } catch (UnsupportedEncodingException e1) {
        System.err.println(StaticValues.LBL.error_writer.get() + ": " + e1.toString());
        return;
    }
    File basedir = new File(checkDigest);
    List<File> files;
    try {
        files = DroidHandler.matchedFiled(new File[] { basedir }, extensions,
                StaticValues.config.argument.recursive);
    } catch (CommandExecutionException e1) {
        System.err.println(StaticValues.LBL.error_error.get() + e1.toString());
        return;
    }
    System.out.println("Digest...");
    Element root = null;
    VitamResult vitamResult = new VitamResult();
    if (basedir.isFile()) {
        basedir = basedir.getParentFile();
    }
    if (StaticValues.config.argument.outputModel == VitamOutputModel.OneXML) {
        root = XmlDom.factory.createElement("digests");
        root.addAttribute("source", basedir.getAbsolutePath());
        vitamResult.unique = XmlDom.factory.createDocument(root);
    }
    int currank = 0;
    int error = 0;
    for (File file : files) {
        currank++;
        String shortname;
        shortname = StaticValues.getSubPath(file, basedir);
        FileInputStream inputstream;
        try {
            inputstream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            System.err.println(StaticValues.LBL.error_computedigest.get() + ": " + shortname);
            continue;
        }
        String[] shas = DigestCompute.computeDigest(inputstream, StaticValues.config.argument);
        //SEDA type since already configured
        Element result = XmlDom.factory.createElement(StaticValues.config.DOCUMENT_FIELD);
        Element attachment = XmlDom.factory.createElement(StaticValues.config.ATTACHMENT_FIELD);
        attachment.addAttribute(StaticValues.config.FILENAME_ATTRIBUTE.substring(1), shortname);
        result.add(attachment);
        if (shas[0] != null) {
            Element integrity = XmlDom.factory.createElement(StaticValues.config.INTEGRITY_FIELD);
            integrity.addAttribute(StaticValues.config.ALGORITHME_ATTRIBUTE.substring(1),
                    StaticValues.XML_SHA1);
            integrity.setText(shas[0]);
            result.add(integrity);
        }
        if (shas[1] != null) {
            Element integrity = XmlDom.factory.createElement(StaticValues.config.INTEGRITY_FIELD);
            integrity.addAttribute(StaticValues.config.ALGORITHME_ATTRIBUTE.substring(1),
                    StaticValues.XML_SHA256);
            integrity.setText(shas[1]);
            result.add(integrity);
        }
        if (shas[2] != null) {
            Element integrity = XmlDom.factory.createElement(StaticValues.config.INTEGRITY_FIELD);
            integrity.addAttribute(StaticValues.config.ALGORITHME_ATTRIBUTE.substring(1),
                    StaticValues.XML_SHA512);
            integrity.setText(shas[2]);
            result.add(integrity);
        }
        if ((shas[0] == null && StaticValues.config.argument.sha1)
                || (shas[1] == null && StaticValues.config.argument.sha256)
                || (shas[2] == null && StaticValues.config.argument.sha512)) {
            result.addAttribute("status", "error");
            error++;
        } else {
            result.addAttribute("status", "ok");
        }
        XmlDom.addDate(StaticValues.config.argument, StaticValues.config, result);
        if (root != null) {
            root.add(result);
        } else {
            // multiple
            root = XmlDom.factory.createElement("digests");
            root.addAttribute("source", basedir.getAbsolutePath());
            root.add(result);
            try {
                writer.write(root);
            } catch (IOException e) {
                System.err.println(StaticValues.LBL.error_error.get() + e.toString());
            }
            root = null;
        }
    }
    if (root != null) {
        if (error == 0) {
            root.addAttribute("status", "ok");
        } else {
            root.addAttribute("status", "error on " + error + " / " + currank + " file checks");
        }
        XmlDom.addDate(StaticValues.config.argument, StaticValues.config, root);
        try {
            writer.write(vitamResult.unique);
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_analysis.get() + e);
        }
    }
    System.out.println(StaticValues.LBL.action_digest.get() + " [ " + currank
            + (error > 0 ? " (" + StaticValues.LBL.error_error.get() + error + " ) " : "") + " ]");
}

From source file:fr.gouv.culture.vitam.command.VitamCommand.java

License:Open Source License

public static void convertPdfa() {
    XMLWriter writer = null;
    try {//  w  w  w  .j a  va2  s .co m
        writer = new XMLWriter(outputStream, StaticValues.defaultOutputFormat);
    } catch (UnsupportedEncodingException e1) {
        System.err.println(StaticValues.LBL.error_writer.get() + ": " + e1.toString());
        return;
    }
    File basedir = new File(fromPdfA);
    List<File> files;
    try {
        files = DroidHandler.matchedFiled(new File[] { basedir }, extensions,
                StaticValues.config.argument.recursive);
    } catch (CommandExecutionException e1) {
        System.err.println(StaticValues.LBL.error_error.get() + e1.toString());
        return;
    }
    if (basedir.isFile()) {
        basedir = basedir.getParentFile();
    }
    File baseoutdir = new File(toPdfA);
    if (!baseoutdir.exists()) {
        baseoutdir.mkdirs();
    }
    if (baseoutdir.isFile()) {
        baseoutdir = baseoutdir.getParentFile();
    }
    int errorcpt = 0;
    boolean checkDroid = false;
    try {
        StaticValues.config.initDroid();
        checkDroid = true;
    } catch (CommandExecutionException e) {
        System.err.println(StaticValues.LBL.error_initdroid.get() + e.toString());
    }
    System.out.println("\nTransform PDF/A-1B\n");
    Element root = null;
    Element temp = null;
    VitamResult vitamResult = new VitamResult();
    if (StaticValues.config.argument.outputModel == VitamOutputModel.OneXML) {
        root = XmlDom.factory.createElement("transform");
        root.addAttribute("source", basedir.getAbsolutePath());
        root.addAttribute("target", baseoutdir.getAbsolutePath());
        vitamResult.unique = XmlDom.factory.createDocument(root);
    } else {
        // force multiple
        vitamResult.multiples = new ArrayList<Document>();
    }
    for (File file : files) {
        String basename = file.getName();
        File rootdir;
        String subpath = null;
        if (file.getParentFile().equals(basedir)) {
            rootdir = basedir;
            subpath = File.separator;
        } else {
            rootdir = file.getParentFile();
            subpath = rootdir.getAbsolutePath().replace(basedir.getAbsolutePath(), "") + File.separator;
        }
        String fullname = subpath + basename;
        String puid = null;
        if (checkDroid) {
            try {
                List<DroidFileFormat> list = StaticValues.config.droidHandler.checkFileFormat(file,
                        StaticValues.config.argument);
                if (list == null || list.isEmpty()) {
                    System.err.println("Ignore: " + fullname);
                    Element pdfa = XmlDom.factory.createElement("convert");
                    Element newElt = XmlDom.factory.createElement("file");
                    newElt.addAttribute("filename", fullname);
                    pdfa.add(newElt);
                    addPdfaElement(root, pdfa, basedir, baseoutdir, true, "Error: filetype not found", null,
                            vitamResult);
                    errorcpt++;
                    continue;
                }
                DroidFileFormat type = list.get(0);
                puid = type.getPUID();
                if (puid.startsWith(StaticValues.FORMAT_XFMT) || puid.equals("fmt/411")) { // x-fmt or RAR
                    System.err.println("Ignore: " + fullname + " " + puid);
                    Element pdfa = XmlDom.factory.createElement("convert");
                    Element newElt = XmlDom.factory.createElement("file");
                    newElt.addAttribute("filename", fullname);
                    pdfa.add(newElt);
                    addPdfaElement(root, pdfa, basedir, baseoutdir, true, "Error: filetype not allowed", puid,
                            vitamResult);
                    errorcpt++;
                    continue;
                }
            } catch (CommandExecutionException e) {
                // ignore
            }
        }
        System.out.println("PDF/A-1B convertion... " + fullname);
        long start = System.currentTimeMillis();
        Element pdfa = PdfaConverter.convertPdfA(subpath, basename, basedir, baseoutdir, StaticValues.config);
        long end = System.currentTimeMillis();
        boolean error = false;
        if (pdfa.selectSingleNode(".[@status='ok']") == null) {
            error = true;
            errorcpt++;
        }
        if (error) {
            System.err.println(StaticValues.LBL.error_pdfa.get() + " PDF/A-1B KO: " + fullname + " "
                    + ((end - start) * 1024 / file.length()) + " ms/KB " + (end - start) + " ms " + "\n");
        } else {
            System.out.println("PDF/A-1B OK: " + fullname + " " + ((end - start) * 1024 / file.length())
                    + " ms/KB " + (end - start) + " ms " + "\n");
        }
        temp = addPdfaElement(root, pdfa, basedir, baseoutdir, error, "error", puid, vitamResult);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
        }
    }
    if (root != null) {
        XmlDom.addDate(StaticValues.config.argument, StaticValues.config, root);
        if (errorcpt > 0) {
            root.addAttribute("status", "error found");
        } else {
            root.addAttribute("status", "ok");
        }
        try {
            writer.write(vitamResult.unique);
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_analysis.get() + e);
        }
    } else {
        XmlDom.addDate(StaticValues.config.argument, StaticValues.config, temp);
        try {
            writer.write(temp);
        } catch (IOException e) {
        }
    }
    if (errorcpt < files.size()) {
        System.out.println(StaticValues.LBL.action_pdfa.get() + " [ " + files.size()
                + (errorcpt > 0 ? " (" + StaticValues.LBL.error_error.get() + errorcpt + " )" : "") + " ]");
    } else {
        System.err.println(StaticValues.LBL.error_pdfa.get() + " [ " + StaticValues.LBL.error_error.get()
                + errorcpt + " ]");
    }
}

From source file:fr.gouv.culture.vitam.command.VitamCommand.java

License:Open Source License

public static void checkFilesType() {
    File fic = new File(FILEarg);
    if (!fic.exists()) {
        System.err.println(StaticValues.LBL.error_filenotfile.get() + ": " + FILEarg);
        return;/*from  w w  w.  j a v a  2 s .com*/
    } else {
        System.out.println("\n" + StaticValues.LBL.tools_dir_format_output.get() + "\n");
        Document global = null;
        Element root = null;
        XMLWriter writer = null;
        try {
            writer = new XMLWriter(outputStream, StaticValues.defaultOutputFormat);
        } catch (UnsupportedEncodingException e1) {
            System.err.println(StaticValues.LBL.error_writer.get() + ": " + e1.toString());
            return;
        }
        if (StaticValues.config.argument.outputModel == VitamOutputModel.OneXML) {
            root = XmlDom.factory.createElement("checkfiles");
            root.addAttribute("source", FILEarg);
            global = XmlDom.factory.createDocument(root);
            EmlExtract.filEmls.clear();
        }
        if (showFormat) {
            if (StaticValues.config.droidHandler == null && StaticValues.config.exif == null
                    && StaticValues.config.jhove == null) {
                System.err.println(StaticValues.LBL.error_initfits.get());
                return;
            }
            try {
                List<File> files = DroidHandler.matchedFiled(new File[] { fic }, extensions,
                        StaticValues.config.argument.recursive);
                for (File file : files) {
                    String shortname;
                    if (fic.isDirectory()) {
                        shortname = StaticValues.getSubPath(file, fic);
                    } else {
                        shortname = FILEarg;
                    }
                    Element result = Commands.showFormat(shortname, null, null, file, StaticValues.config,
                            StaticValues.config.argument);
                    XmlDom.addDate(StaticValues.config.argument, StaticValues.config, result);
                    if (root != null) {
                        root.add(result);
                    } else {
                        writer.write(result);
                        System.out.println("\n========================================================");
                    }
                }
            } catch (CommandExecutionException e) {
                System.err.println(StaticValues.LBL.error_analysis.get() + e);
                e.printStackTrace();
            } catch (IOException e) {
                System.err.println(StaticValues.LBL.error_analysis.get() + e);
            }
        } else {
            if (StaticValues.config.droidHandler == null) {
                System.err.println(StaticValues.LBL.error_initdroid.get());
                return;
            }
            if (root != null) {
                Element newElt = XmlDom.factory.createElement("toolsversion");
                if (StaticValues.config.droidHandler != null) {
                    newElt.addAttribute("pronom", StaticValues.config.droidHandler.getVersionSignature());
                }
                if (StaticValues.config.droidHandler != null) {
                    newElt.addAttribute("droid", "6.1");
                }
                root.add(newElt);
            }
            List<DroidFileFormat> list;
            try {
                VitamArgument argument = new VitamArgument(StaticValues.config.argument.archive,
                        StaticValues.config.argument.recursive, true, true, true,
                        StaticValues.config.argument.outputModel, StaticValues.config.argument.checkSubFormat,
                        StaticValues.config.argument.extractKeyword);
                List<File> files = DroidHandler.matchedFiled(new File[] { fic }, extensions,
                        argument.recursive);
                list = StaticValues.config.droidHandler.checkFilesFormat(files, argument, null);
                String pathBeforeArg = fic.getCanonicalPath();
                pathBeforeArg = pathBeforeArg.substring(0, pathBeforeArg.indexOf(FILEarg));
                for (DroidFileFormat droidFileFormat : list) {
                    Element fileformat = droidFileFormat.toElement(true);
                    Attribute filename = fileformat.attribute("filename");
                    if (filename != null) {
                        String value = filename.getText();
                        filename.setText(value.replace(pathBeforeArg, ""));
                    }
                    XmlDom.addDate(StaticValues.config.argument, StaticValues.config, fileformat);
                    if (root != null) {
                        root.add(fileformat);
                    } else {
                        writer.write(fileformat);
                        System.out.println("\n========================================================");
                    }
                }
            } catch (CommandExecutionException e) {
                System.err.println(StaticValues.LBL.error_analysis.get() + e);
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                System.err.println(StaticValues.LBL.error_analysis.get() + e);
            } catch (IOException e) {
                System.err.println(StaticValues.LBL.error_analysis.get() + e);
            }
        }
        if (global != null) {
            XmlDom.addDate(StaticValues.config.argument, StaticValues.config, root);
            if (!EmlExtract.filEmls.isEmpty()) {
                Element sortEml = XmlDom.factory.createElement("emlsort");
                for (String parent : EmlExtract.filEmls.keySet()) {
                    Element eparent = XmlDom.factory.createElement("parent");
                    String fil = EmlExtract.filEmls.get(parent);
                    eparent.addAttribute("messageId", parent);
                    String[] fils = fil.split(",");
                    for (String mesg : fils) {
                        if (mesg != null && mesg.length() > 1) {
                            Element elt = XmlDom.factory.createElement("descendant");
                            elt.addAttribute("messageId", mesg);
                            eparent.add(elt);
                        }
                    }
                    sortEml.add(eparent);
                }
                root.add(sortEml);
            }
            try {
                writer.write(global);
            } catch (IOException e) {
                System.err.println(StaticValues.LBL.error_analysis.get() + e);
            }
        }
    }
}

From source file:fr.gouv.culture.vitam.digest.DigestCompute.java

License:Open Source License

public static int createDigest(File src, File dst, File ftar, File fglobal, boolean oneDigestPerFile,
        List<File> filesToScan) {
    try {/* w  w w  . j  av a 2s .  com*/
        Element global = null;
        Document globalDoc = null;
        if (fglobal != null) {
            global = XmlDom.factory.createElement("digests");
            global.addAttribute("source", src.getAbsolutePath());
            globalDoc = XmlDom.factory.createDocument(global);
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(StaticValues.CURRENT_OUTPUT_ENCODING);
        XMLWriter writer = new XMLWriter(format);
        int error = 0;
        int currank = 0;
        for (File file : filesToScan) {
            currank++;
            Element result = DigestCompute.checkDigest(StaticValues.config, src, file);
            if (result.selectSingleNode(".[@status='ok']") == null) {
                System.err.println(StaticValues.LBL.error_error.get()
                        + StaticValues.LBL.error_computedigest.get() + StaticValues.getSubPath(file, src));
                error++;
            } else if (oneDigestPerFile) {
                Element rootElement = XmlDom.factory.createElement("digest");
                Document unique = XmlDom.factory.createDocument(rootElement);
                rootElement.add(result);
                FileOutputStream out = null;
                String shortname = StaticValues.getSubPath(file, src);
                String shortnameWithoutFilename = shortname.substring(0, shortname.lastIndexOf(file.getName()));
                File fdirout = new File(dst, shortnameWithoutFilename);
                fdirout.mkdirs();
                File fout = new File(fdirout, file.getName() + "_digest.xml");
                try {
                    out = new FileOutputStream(fout);
                    writer.setOutputStream(out);
                    writer.write(unique);
                    writer.close();
                } catch (FileNotFoundException e) {
                    System.err.println(
                            StaticValues.LBL.error_error.get() + fout.getAbsolutePath() + " " + e.toString());
                    error++;
                } catch (IOException e) {
                    System.err.println(
                            StaticValues.LBL.error_error.get() + fout.getAbsolutePath() + " " + e.toString());
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e1) {
                        }
                    }
                    error++;
                }
                result.detach();
            }
            if (fglobal != null) {
                global.add(result);
            }
        }
        if (ftar != null) {
            currank++;
            Element result = DigestCompute.checkDigest(StaticValues.config, src, ftar);
            if (result.selectSingleNode(".[@status='ok']") == null) {
                System.err.println(StaticValues.LBL.error_error.get()
                        + StaticValues.LBL.error_computedigest.get() + ftar.getAbsolutePath());
                error++;
            } else if (oneDigestPerFile) {
                Element rootElement = XmlDom.factory.createElement("digest");
                Document unique = XmlDom.factory.createDocument(rootElement);
                rootElement.add(result);
                FileOutputStream out = null;
                File fout = new File(dst, ftar.getName() + "_tar_digest.xml");
                try {
                    out = new FileOutputStream(fout);
                    writer.setOutputStream(out);
                    writer.write(unique);
                    writer.close();
                } catch (FileNotFoundException e) {
                    System.err.println(
                            StaticValues.LBL.error_error.get() + fout.getAbsolutePath() + " " + e.toString());
                    error++;
                } catch (IOException e) {
                    System.err.println(
                            StaticValues.LBL.error_error.get() + fout.getAbsolutePath() + " " + e.toString());
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e1) {
                        }
                    }
                    error++;
                }
                result.detach();
            }
            if (fglobal != null) {
                global.add(result);
            }
        }
        if (fglobal != null) {
            if (error > 0) {
                global.addAttribute("status", "error");
            } else {
                global.addAttribute("status", "ok");
            }
            XmlDom.addDate(VitamArgument.ONEXML, StaticValues.config, global);
            FileOutputStream out;
            try {
                out = new FileOutputStream(fglobal);
                writer.setOutputStream(out);
                writer.write(globalDoc);
                writer.close();
            } catch (FileNotFoundException e) {
                System.err.println(
                        StaticValues.LBL.error_error.get() + fglobal.getAbsolutePath() + " " + e.toString());
                error++;
            } catch (IOException e) {
                System.err.println(
                        StaticValues.LBL.error_error.get() + fglobal.getAbsolutePath() + " " + e.toString());
                error++;
            }
        }
        if (error > 0) {
            System.err.println(StaticValues.LBL.error_error.get() + " Digest" + " [ " + currank
                    + (error > 0 ? " (" + StaticValues.LBL.error_error.get() + error + " ) " : "") + " ]");
            return -error;
        }
        return currank;
    } catch (UnsupportedEncodingException e) {
        System.err.println(StaticValues.LBL.error_error.get() + " " + e.toString());
        return -1;
    }

}

From source file:fr.gouv.culture.vitam.droid.DroidHandler.java

License:Open Source License

/**
 * Example only/* w  w  w . ja  va2 s .  c o m*/
 * 
 * @param args
 * @throws CommandExecutionException
 */
public static void main(String[] args) throws CommandExecutionException {
    StaticValues.initialize();
    String signatureFile = StaticValues.resourceToFile(StaticValues.config.SIGNATURE_FILE);
    String containerSignatureFile = StaticValues.resourceToFile(StaticValues.config.CONTAINER_SIGNATURE_FILE);

    // Init Signature
    initialize(signatureFile, containerSignatureFile, -1);

    // Prepare command
    DroidHandler droid = new DroidHandler();

    String[] tocheck = new String[] { "J:\\Git\\SEDA\\droid-binary-6.1-bin\\doc",
            "J:\\Git\\SEDA\\droid-binary-6.1-bin\\doc\\vitam.xlsx" };

    // Execute and get result
    List<DroidFileFormat> list = null;
    try {
        list = droid.checkFilesFormat(tocheck, null, VitamArgument.NOFEATURE, null);
    } catch (CommandExecutionException e) {
        e.printStackTrace();
    }

    // for the example, print out the result as is
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(System.out, StaticValues.defaultOutputFormat);
    } catch (UnsupportedEncodingException e1) {
    }
    try {
        for (DroidFileFormat droidFileFormat : list) {
            writer.write(droidFileFormat.toElement(true));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        list = droid.checkFileFormat(tocheck[1], VitamArgument.SHAALLONLY);
    } catch (CommandExecutionException e) {
        e.printStackTrace();
    }
    try {
        for (DroidFileFormat droidFileFormat : list) {
            writer.write(droidFileFormat.toElement(true));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        list = droid.checkFileFormat(tocheck[1], VitamArgument.SHAALLONLY);
        for (DroidFileFormat droidFileFormat : list) {
            System.out.println(droidFileFormat.toStringCsv());
        }
    } catch (CommandExecutionException e) {
        e.printStackTrace();
    }
}

From source file:fr.gouv.culture.vitam.extract.ExtractInfo.java

License:Open Source License

public static void main(String[] args) {
    if (args.length == 0) {
        System.err.println("need file as target");
        return;// www .  j a va 2s.  c o m
    }
    StaticValues.initialize();
    Document document = DocumentFactory.getInstance().createDocument(StaticValues.CURRENT_OUTPUT_ENCODING);
    Element root = DocumentFactory.getInstance().createElement("extractkeywords");
    document.add(root);
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(StaticValues.CURRENT_OUTPUT_ENCODING);
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(System.out, format);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        return;
    }
    for (String string : args) {
        File file = new File(string);
        recursive(file, string, root, StaticValues.config, writer);
    }
    if (StaticValues.config.argument.outputModel == VitamOutputModel.OneXML) {
        try {
            writer.write(document);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:fr.gouv.culture.vitam.utils.XmlDom.java

License:Open Source License

public final static void addElement(XMLWriter writer, VitamArgument argument, Element parent, Element sub) {
    switch (argument.outputModel) {
    case TXT:/* www.jav a2  s .c o  m*/
        try {
            if (writer != null) {
                writer.write(sub);
            }
        } catch (IOException e) {
        }
        break;
    case MultipleXML:
    case OneXML:
        if (sub != null) {
            parent.add(sub);
        }
    }

}

From source file:fr.isima.ponge.wsprotocol.xml.XmlIOManager.java

License:Open Source License

/**
 * Writes a business protocol as an XML representation to a writer.
 *
 * @param protocol The protocol./*w w w.j  a  v a  2 s  .  c  o  m*/
 * @param writer   The writer to use.
 * @throws IOException Thrown in case an I/O error occurs.
 */
@SuppressWarnings("unchecked")
public void writeBusinessProtocol(BusinessProtocol protocol, Writer writer) throws IOException {
    // Root
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("business-protocol"); //$NON-NLS-1$

    // Protocol
    root.addElement("name").setText(protocol.getName()); //$NON-NLS-1$
    writeExtraProperties(root, protocol);

    // States
    Iterator it = protocol.getStates().iterator();
    while (it.hasNext()) {
        State s = (State) it.next();
        Element el = root.addElement("state"); //$NON-NLS-1$
        el.addElement("name").setText(s.getName()); //$NON-NLS-1$
        el.addElement("final").setText(s.isFinalState() ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        if (s.isInitialState()) {
            el.addElement("initial-state"); //$NON-NLS-1$
        }
        writeExtraProperties(el, s);
    }

    // Operations
    it = protocol.getOperations().iterator();
    while (it.hasNext()) {
        Operation o = (Operation) it.next();
        Message m = o.getMessage();
        String pol;
        if (m.getPolarity().equals(Polarity.POSITIVE)) {
            pol = "positive"; //$NON-NLS-1$
        } else if (m.getPolarity().equals(Polarity.NEGATIVE)) {
            pol = "negative"; //$NON-NLS-1$

        } else {
            pol = "null"; //$NON-NLS-1$
        }
        Element oel = root.addElement("operation"); //$NON-NLS-1$
        Element mel = oel.addElement("message"); //$NON-NLS-1$
        mel.addElement("name").setText(m.getName()); //$NON-NLS-1$
        mel.addElement("polarity").setText(pol); //$NON-NLS-1$
        oel.addElement("name").setText(o.getName()); //$NON-NLS-1$
        oel.addElement("source").setText(o.getSourceState().getName()); //$NON-NLS-1$
        oel.addElement("target").setText(o.getTargetState().getName()); //$NON-NLS-1$
        oel.addElement("kind").setText(o.getOperationKind().toString()); //$NON-NLS-1$
        writeExtraProperties(mel, m);
        writeExtraProperties(oel, o);
    }

    // Write
    XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint());
    xmlWriter.write(document);
}

From source file:fullyMeshedNet.FullyMeshedNet.java

License:Open Source License

@Override
public void exportToFile(File saveFile) {
    String extension = FrevoMain.getExtension(saveFile);
    if (extension.equals("net")) {
        System.out.println("Exporting Pajek network file to " + saveFile.getName());
        try {/*w  w w  .ja v  a  2s  .  c o  m*/
            // Create file
            FileWriter fstream = new FileWriter(saveFile);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("*Vertices " + this.nodes);
            out.newLine();
            // input neurons
            for (int i = 1; i < input_nodes + 1; i++) {
                out.write(i + " \"I" + i + "\"");
                out.newLine();
            }
            for (int h = input_nodes + 1; h < nodes - output_nodes + 1; h++) {
                out.write(h + " \"H" + (h - input_nodes) + "\"");
                out.newLine();
            }
            int a = 1;
            for (int o = nodes - output_nodes + 1; o < nodes + 1; o++) {
                out.write(o + " \"O" + a + "\"");
                out.newLine();
                a++;
            }

            // Edges
            out.write("*Edges");
            out.newLine();
            for (int n = 0; n < input_nodes - 1; n++) {
                for (int p = n + 1; p < input_nodes; p++) {
                    if (n != p) {
                        out.write((n + 1) + " " + (p + 1) + " " + 0);
                        out.newLine();
                    }
                }
            }

            for (int n = input_nodes; n < nodes; n++) {
                for (int from = 0; from < nodes; from++) {
                    out.write((n + 1) + " " + (from + 1) + " " + weight[from][n]);
                    out.newLine();
                }
            }

            // Close the output stream
            out.close();
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    } else if (extension.equals("xml")) {
        System.out.println("Saving to XML");

        Document doc = DocumentHelper.createDocument();
        doc.addDocType("CompleteNetwork", null, System.getProperty("user.dir")
                + "//Components//Representations//CompleteNetwork//src//CompleteNetwork.dtd");
        Element cnetwork = doc.addElement("CompleteNetwork");
        this.exportToXmlElement(cnetwork);

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));

        try {
            saveFile.createNewFile();
            FileWriter out = new FileWriter(saveFile);
            BufferedWriter bw = new BufferedWriter(out);
            XMLWriter wr = new XMLWriter(bw, format);
            wr.write(doc);
            wr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:gestionecassa.backends.XmlDataBackend.java

License:Open Source License

@Override
public void saveArticlesList(ArticlesList lista) throws IOException {

    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("article_groups");
    Collection<ArticleGroup> groups = lista.getGroupsList();
    for (ArticleGroup group : groups) {
        Element tempGroup = root.addElement("group");

        tempGroup.addElement("name").addText(group.getName());
        tempGroup.addElement("id").addText(group.getId() + "");

        for (Article art : group.getList()) {
            Element tempArt = tempGroup.addElement("article");

            tempArt.addElement("name").addText(art.getName());
            tempArt.addElement("price").addText(art.getPrice() + "");
            tempArt.addElement("id").addText(art.getId() + "");

            if (art.hasOptions()) {
                tempArt.addAttribute("options", "true");
                Element tempOpzioni = tempArt.addElement("options");

                Collection<ArticleOption> options = art.getOptions();
                for (ArticleOption option : options) {
                    tempOpzioni.addElement("option").addText(option.getName());
                } //FIXME aggiungi altre parti di ArticleOption
            } else {
                tempArt.addAttribute("options", "false");
            }//from  w w w . j a v a2  s . c o m
        }
    }

    // for debug purposes
    OutputFormat format = OutputFormat.createPrettyPrint();

    // lets write to a file
    XMLWriter writer = new XMLWriter(new FileWriter(ArtListFile), format);
    //XMLWriter writer = new XMLWriter(new FileWriter(fileName));
    writer.write(document);
    writer.close();
}