Example usage for org.dom4j Element add

List of usage examples for org.dom4j Element add

Introduction

In this page you can find the example usage for org.dom4j Element add.

Prototype

void add(Namespace namespace);

Source Link

Document

Adds the given Namespace to this element.

Usage

From source file:fr.gouv.culture.vitam.gui.VitamGui.java

License:Open Source License

/**
 * Check one directory against digest/*from   ww  w  .  j a v a  2  s . c  om*/
 * 
 * @param task
 */
private void oneDirDigest(RunnerLongTask task) {
    List<File> files = filesToScan;
    filesToScan = null;
    System.out.println("Digest...");
    Element root = null;
    vitamResult = new VitamResult();
    if (config.argument.outputModel == VitamOutputModel.OneXML) {
        root = XmlDom.factory.createElement("digests");
        root.addAttribute("source", config.lastScannedDirectory.getAbsolutePath());
        vitamResult.unique = XmlDom.factory.createDocument(root);
    } else {
        // force multiple
        vitamResult.multiples = new ArrayList<Document>();
    }
    int currank = 0;
    int error = 0;
    for (File file : files) {
        currank++;
        String shortname;
        if (config.lastScannedDirectory.isDirectory()) {
            shortname = StaticValues.getSubPath(file, config.lastScannedDirectory);
        } else {
            shortname = config.lastScannedDirectory.getName();
        }
        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, 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 && config.argument.sha1) || (shas[1] == null && config.argument.sha256)
                || (shas[2] == null && config.argument.sha512)) {
            result.addAttribute("status", "error");
            error++;
        } else {
            result.addAttribute("status", "ok");
        }
        XmlDom.addDate(config.argument, config, result);
        if (root != null) {
            root.add(result);
        } else {
            // multiple
            root = XmlDom.factory.createElement("digests");
            root.addAttribute("source", config.lastScannedDirectory.getAbsolutePath());
            Document document = XmlDom.factory.createDocument(root);
            root.add(result);
            vitamResult.multiples.add(document);
            root = null;
        }
        if (task != null) {
            float value = ((float) currank) / (float) files.size();
            value *= 100;
            task.setProgressExternal((int) value);
        }
    }
    if (root != null) {
        if (error == 0) {
            root.addAttribute("status", "ok");
        } else {
            root.addAttribute("status", "error on " + error + " / " + currank + " file checks");
        }
        XmlDom.addDate(config.argument, config, root);
    }

    texteOut.insertIcon(new ImageIcon(getClass().getResource(RESOURCES_IMG_VALID_PNG)));
    System.out.println(StaticValues.LBL.action_digest.get() + " [ " + currank
            + (error > 0 ? " (" + StaticValues.LBL.error_error.get() + error + " ) " : "") + " ]");
}

From source file:fr.gouv.culture.vitam.gui.VitamGui.java

License:Open Source License

private void addPdfaElement(Element root, Element pdfa, File basedir, File baseoutdir, boolean error,
        String serror, String puid) {
    XmlDom.addDate(config.argument, config, pdfa);
    if (puid != null) {
        pdfa.addAttribute("puid", puid);
    }/* ww w  . j  av a  2s.c  o  m*/
    if (root != null) {
        root.add(pdfa);
    } else {
        // multiple
        root = XmlDom.factory.createElement("transform");
        root.addAttribute("source", basedir.getAbsolutePath());
        root.addAttribute("target", baseoutdir.getAbsolutePath());
        Document document = XmlDom.factory.createDocument(root);
        root.add(pdfa);
        if (error) {
            root.addAttribute("status", serror);
        } else {
            root.addAttribute("status", "ok");
        }
        vitamResult.multiples.add(document);
        root = null;
    }
}

From source file:fr.gouv.culture.vitam.gui.VitamGui.java

License:Open Source License

/**
 * Convert files to PDFA through LibreOffice/OpenOffice (temptative)
 * @param task//  www.j a v a 2 s  . co  m
 */
public void convertToPdf(RunnerLongTask task) {
    List<File> files = filesToScan;
    filesToScan = null;
    File basedir = config.lastScannedDirectory;
    File baseoutdir = tempFile;
    tempFile = null;
    int errorcpt = 0;
    boolean checkDroid = false;
    try {
        config.initDroid();
        vitamResult = null;
        checkDroid = true;
    } catch (CommandExecutionException e) {
        System.err.println(StaticValues.LBL.error_initdroid.get() + e.toString());
        vitamResult = null;
    }
    System.out.println("Transform PDF/A-1B");
    Element root = null;
    vitamResult = new VitamResult();
    if (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>();
    }
    int currank = 0;
    for (File file : files) {
        currank++;
        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 = config.droidHandler.checkFileFormat(file, 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);
                    if (task != null) {
                        float value = ((float) currank) / (float) files.size();
                        value *= 100;
                        task.setProgressExternal((int) value);
                    }
                    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);
                    if (task != null) {
                        float value = ((float) currank) / (float) files.size();
                        value *= 100;
                        task.setProgressExternal((int) value);
                    }
                    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);
                    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, 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");
        }
        addPdfaElement(root, pdfa, basedir, baseoutdir, error, "error", puid);
        if (task != null) {
            float value = ((float) currank) / (float) files.size();
            value *= 100;
            task.setProgressExternal((int) value);
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
        }
    }
    if (root != null) {
        XmlDom.addDate(config.argument, config, root);
        if (errorcpt > 0) {
            root.addAttribute("status", "error found");
        } else {
            root.addAttribute("status", "ok");
        }
    }
    if (errorcpt < files.size()) {
        texteOut.insertIcon(new ImageIcon(getClass().getResource(RESOURCES_IMG_VALID_PNG)));
        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.pdfa.PdfaConverter.java

License:Open Source License

/**
 * Convert the file rootdir/basepath/basename into Pdf/A-1B in outdir/basepath/basename <br>
 * <br>//w  ww  .  j  a v  a  2 s.c om
 * Note: Any LibreOffice/OpenOffice running instance will be killed!
 * 
 * @param basepath could be as simple as "/"
 * @param basename
 * @param rootdir
 * @param outdir Must not contains space in the path !
 * @param config
 * @return the Element as result
 */
public static Element convertPdfA(String basepath, String basename, File rootdir, File outdir,
        ConfigLoader config) {
    String temppdfname = basename.substring(0, basename.lastIndexOf('.')) + ".pdf";
    String pdfname = basename + ".pdf";
    if (!basepath.endsWith(File.separator)) {
        basepath += File.separator;
    }
    File sourceFile = new File(rootdir, basepath + basename);
    File targetDir = new File(outdir, basepath);
    targetDir.mkdirs();
    File targetFile = new File(targetDir, pdfname);
    File targetTempFile = new File(targetDir, temppdfname);
    if (targetFile.exists()) {
        System.err.println(
                StaticValues.LBL.error_warning.get() + " destination exist: " + targetFile.getAbsolutePath());
    }
    if (targetTempFile.exists()) {
        System.err.println(StaticValues.LBL.error_warning.get() + " temp destination exist: "
                + targetTempFile.getAbsolutePath());
    }

    Element root = XmlDom.factory.createElement("convert");
    Element newElt = XmlDom.factory.createElement("file");
    newElt.addAttribute("filename", basepath + basename);
    root.add(newElt);
    newElt = XmlDom.factory.createElement("pdfa");
    Attribute targetName = XmlDom.factory.createAttribute(newElt, "filename", basepath + pdfname);
    newElt.add(targetName);
    root.add(newElt);

    // Check Office installation first
    String osName = SystemPropertyUtil.get("os.name").toLowerCase();
    String python = null;
    if (osName.indexOf("win") >= 0) {
        python = config.LIBREOFFICE_HOME + "\\program\\python.exe";
    } else {
        python = config.LIBREOFFICE_HOME + "/program/python.bin";
    }
    File fpython = new File(python);
    if (!fpython.exists()) {
        System.err.println(StaticValues.LBL.error_filenotfound.get() + " LibreOffice");
        root.addAttribute("status", "Error LibreOffice not found");
        return root;
    }
    // convertion
    boolean done = false;
    ArrayList<String> command = new ArrayList<String>();
    command.add(fpython.getAbsolutePath());
    command.add(config.UNOCONV);
    //command.add("-v");
    command.add("-f");
    command.add("pdf");
    command.add("-eSelectPdfVersion=1");
    command.add("--output=" + targetDir.getAbsolutePath());
    command.add(sourceFile.getAbsolutePath());
    long wait = sourceFile.length() / 1024 * config.msPerKB;
    if (wait < config.lowLimitMs) {
        wait = config.lowLimitMs;
    }
    int status = Executor.exec(command, wait, new int[] { 0 }, false, "soffice.bin");
    done = (status == 0 || status == 1);
    try {
        Thread.sleep(200);
    } catch (InterruptedException e) {
    }
    Executor.killProcess("soffice.bin");

    if (done) {
        if (!targetTempFile.renameTo(targetFile)) {
            targetName.setText(temppdfname);
        }
        root.addAttribute("status", "ok");
    } else {
        root.addAttribute("status", "Error during convertion");
    }
    return root;
}

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

License:Open Source License

/** 
* @param basename// w w w  .  j  a  v a 2  s .c  om
* @param mimeCode
* @param format
* @param fic
* @param config
* @param argument
* @return the Element associated with the result
*/
public static Element showFormat(String basename, String mimeCode, String format, File fic, ConfigLoader config,
        VitamArgument argument) {
    try {
        Element root = XmlDom.factory.createElement("showformat");
        Element newElt = XmlDom.factory.createElement("file");
        newElt.addAttribute("filename", basename);
        if (mimeCode != null) {
            newElt.addAttribute("mime", mimeCode);
        }
        if (format != null) {
            newElt.addAttribute("puid", format);
        }
        root.add(newElt);
        newElt = XmlDom.factory.createElement("toolsversion");
        if (config.droidHandler != null) {
            newElt.addAttribute("pronom", config.droidHandler.getVersionSignature());
        }
        if (config.droidHandler != null) {
            newElt.addAttribute("droid", "6.1");
        }
        if (config.exif != null) {
            newElt.addAttribute("exif", config.exif.getToolInfo().version);
        }
        if (config.jhove != null) {
            newElt.addAttribute("jhove", config.jhove.getToolInfo().version);
        }
        root.add(newElt);
        addFormatIdentification(root, basename, fic, config, argument);
        return root;
    } catch (Exception e) {
        System.err.println("FITS_ERROR: " + e);
        e.printStackTrace();
        Element root = XmlDom.factory.createElement("showformat");
        Element newElt = XmlDom.factory.createElement("file");
        newElt.addAttribute("filename", basename);
        if (mimeCode != null) {
            newElt.addAttribute("mime", mimeCode);
        }
        if (format != null) {
            newElt.addAttribute("puid", format);
        }
        root.add(newElt);
        root.addAttribute("status", e.toString());
        return root;
    }
}

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

License:Open Source License

/**
 * Identify format of one file//from  w  w  w.  j a  v  a  2s  . c o m
 * @param root where the information will be added
 * @param basename
 * @param fic
 * @param config
 * @param argument
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public static final void addFormatIdentification(Element root, String basename, File fic, ConfigLoader config,
        VitamArgument argument) throws Exception {
    try {
        Element identification, fileinfo, filestatus, metadata;

        identification = XmlDom.factory.createElement("identification");
        fileinfo = XmlDom.factory.createElement("fileinfo");
        filestatus = XmlDom.factory.createElement("filestatus");
        metadata = XmlDom.factory.createElement("metadata");
        root.add(identification);
        root.add(fileinfo);
        root.add(filestatus);
        root.add(metadata);

        String status = "ok";

        Element toAdd;
        // Droid
        boolean identityFound = false;
        Element idp = null;
        DroidFileFormat finalFormat = null;
        if (config.droidHandler != null) {
            List<DroidFileFormat> formats = config.droidHandler.checkFileFormat(fic, argument);
            Element newElt = XmlDom.factory.createElement("subidentities");
            if (formats != null && !formats.isEmpty()) {
                boolean multiple = argument.archive && formats.size() > 1;
                Iterator<DroidFileFormat> iterator = formats.iterator();
                DroidFileFormat droidFileFormat = iterator.next();
                finalFormat = droidFileFormat;
                if (droidFileFormat.getPUID().equals(DroidFileFormat.Unknown)) {
                    idp = droidFileFormat.toElement(multiple);
                    identification.add(idp);
                } else {
                    if (!config.preventXfmt
                            || !droidFileFormat.getPUID().startsWith(StaticValues.FORMAT_XFMT)) {
                        identityFound = true;
                    } else {
                        status = "warning";
                    }
                    idp = droidFileFormat.toElement(multiple);
                    identification.add(idp);
                }
                boolean other = false;
                while (iterator.hasNext()) {
                    other = true;
                    droidFileFormat = (DroidFileFormat) iterator.next();
                    if (droidFileFormat.getPUID().equals(DroidFileFormat.Unknown)) {
                        idp = droidFileFormat.toElement(multiple);
                        newElt.add(idp);
                    } else {
                        //identityFound = true;
                        idp = droidFileFormat.toElement(multiple);
                        newElt.add(idp);
                    }
                }
                if (other) {
                    identification.add(newElt);
                }
            }
        }
        String mimeType = finalFormat.getMimeType();
        String pid = finalFormat.getPUID();
        if (identityFound && "message/rfc822".equals(mimeType)) {
            // email special task : EML
            // No rankid since done below
            Element special = EmlExtract.extractInfoEmail(fic, basename, argument, config);
            if (special == null) {
                status = "ko";
                root.addAttribute("status", status);
            } else {
                root.add(special);
                root.addAttribute("status", status);
            }
            return;
        } else if (identityFound && ("x-fmt/248".equals(pid) || "x-fmt/249".equals(pid))) {
            // email special task : PST
            config.addRankId(root);
            //String id = Long.toString(config.nbDoc.incrementAndGet());
            //root.addAttribute(EMAIL_FIELDS.rankId.name, id);
            idp.addAttribute("mime", "application/vnd.ms-outlook");
            Element special = PstExtract.extractInfoPst(fic, argument, config);
            if (special == null) {
                status = "ko";
                root.addAttribute("status", status);
            } else {
                root.add(special);
                root.addAttribute("status", status);
            }
            return;
        } else if (identityFound && "x-fmt/430".equals(pid)) {
            // email special task : MSG
            // no RankId since done below
            Element special = MsgExtract2.extractInfoEmail(fic, basename, argument, config);
            if (special == null) {
                status = "ko";
                root.addAttribute("status", status);
            } else {
                root.add(special);
                root.addAttribute("status", status);
            }
            return;
        } else if (!identityFound) {
            // email special task : MBOX RFC 4155 ?
            config.addRankId(root);
            //String id = Long.toString(config.nbDoc.incrementAndGet());
            //root.addAttribute(EMAIL_FIELDS.rankId.name, id);
            Element special = MailboxParser.extractInfoEmail(fic, argument, config);
            if (special != null) {
                // should be a MBOX RFC 4155
                idp.addAttribute("mime", "application/mbox");
                root.add(special);
                root.addAttribute("status", status);
                return;
            }
        } else {
            // not email
            config.addRankId(root);
            //String id = Long.toString(config.nbDoc.incrementAndGet());
            //root.addAttribute(EMAIL_FIELDS.rankId.name, id);
        }
        ToolOutput toolOuput;
        List<Element> sublist;
        Document doc;

        DOMOutputter output = new DOMOutputter();
        DOMReader reader = new DOMReader();
        // Exiftool
        // identity fileinfo metadata
        if (config.exif != null) {
            toolOuput = config.exif.extractInfo(fic);
            org.jdom.Document docJdom = toolOuput.getFitsXml();
            org.w3c.dom.Document dom = output.output(docJdom);
            doc = reader.read(dom);
            XmlDom.removeAllNamespaces(doc);
            XmlDom.removeEmptyDocument(doc);
            // get identity fileinfo metadata
            boolean findSubTree = false;
            Element element = null;
            if (!identityFound) {
                element = (Element) doc.selectSingleNode("//identification");
                if (element != null) {
                    sublist = element.elements();
                    if (sublist != null && !sublist.isEmpty()) {
                        toAdd = sublist.get(0);
                        findSubTree = true;
                        toAdd = (Element) toAdd.detach();
                        Element newElt = XmlDom.factory.createElement("ExifTool");
                        newElt.add(toAdd);
                        toAdd = null;
                        identification.add(newElt);
                    }
                    sublist = null;
                }
            } else {
                element = (Element) doc.selectSingleNode("//identification");
                if (element != null) {
                    findSubTree = true;
                }
            }
            element = (Element) doc.selectSingleNode("//fileinfo");
            if (element != null) {
                toAdd = element;
                findSubTree = true;
                List<Element> list = toAdd.elements();
                for (Element element2 : list) {
                    element2.detach();
                    fileinfo.add(element2);
                }
            }
            element = (Element) doc.selectSingleNode("//metadata");
            if (element != null) {
                toAdd = element;
                findSubTree = true;
                List<Element> list = toAdd.elements();
                for (Element element2 : list) {
                    element2.detach();
                    metadata.add(element2);
                }
            }
            if (!findSubTree) {
                toAdd = (Element) doc.getRootElement().detach();
                Element newElt = XmlDom.factory.createElement("ExifTool");
                newElt.add(toAdd);
                root.add(newElt);
            }
        }

        // JHove
        // identity fileinfo filestatus metadata
        if (config.jhove != null) {
            toolOuput = config.jhove.extractInfo(fic);
            org.jdom.Document docJdom = toolOuput.getFitsXml();
            org.w3c.dom.Document dom = output.output(docJdom);
            doc = reader.read(dom);
            XmlDom.removeAllNamespaces(doc);
            XmlDom.removeEmptyDocument(doc);
            // get identity fileinfo metadata
            boolean findSubTree = false;
            Element element = null;
            if (!identityFound) {
                element = (Element) doc.selectSingleNode("//identification");
                if (element != null) {
                    sublist = element.elements();
                    if (sublist != null && !sublist.isEmpty()) {
                        toAdd = sublist.get(0);
                        findSubTree = true;
                        toAdd = (Element) toAdd.detach();
                        Element newElt = XmlDom.factory.createElement("JHove");
                        newElt.add(toAdd);
                        toAdd = null;
                        identification.add(newElt);
                    }
                    sublist = null;
                }
            } else {
                element = (Element) doc.selectSingleNode("//identification");
                if (element != null) {
                    findSubTree = true;
                }
            }
            element = (Element) doc.selectSingleNode("//fileinfo");
            if (element != null) {
                toAdd = element;
                findSubTree = true;
                List<Element> list = toAdd.elements();
                for (Element element2 : list) {
                    XmlDom.checkPresence(element2, fileinfo);
                }
            }
            element = (Element) doc.selectSingleNode("//metadata");
            if (element != null) {
                toAdd = element;
                findSubTree = true;
                List<Element> list = toAdd.elements();
                for (Element element2 : list) {
                    XmlDom.checkPresence(element2, metadata);
                }
            }
            element = (Element) doc.selectSingleNode("//filestatus");
            if (element != null) {
                toAdd = element;
                findSubTree = true;
                List<Element> list = toAdd.elements();
                for (Element element2 : list) {
                    element2.detach();
                    filestatus.add(element2);
                }
            }
            if (!findSubTree) {
                toAdd = (Element) doc.getRootElement().detach();
                Element newElt = XmlDom.factory.createElement("JHove");
                newElt.add(toAdd);
                root.add(newElt);
            }
        }
        // Keywords
        if (argument.extractKeyword && finalFormat != null) {
            Element keywords = ExtractInfo.exportMetadata(fic, basename, config, null, finalFormat);
            if (keywords != null) {
                XmlDom.removeEmptyElement(keywords);
                root.add(keywords);
            }
        }
        // Global result
        root.addAttribute("status", status);
    } catch (Exception e) {
        throw e;
    }
}

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

License:Open Source License

/**
 * Try to validate the format from the XML and the Droid output
 * //from  w  ww.j a v a 2 s . c  o  m
 * @param list
 * @param mimeCode
 * @param format
 * @param ficname
 *            (name as in XML)
 * @param fic
 *            real File
 * 
 * @return Element with the result (.[@status='ok'] != null => OK)
 */
public final static Element droidFormat(List<DroidFileFormat> list, String mimeCode, String format,
        String ficname, File fic) {
    boolean localError = false;
    boolean localWarning = false;
    Element cformat = XmlDom.factory.createElement("format");
    cformat.addAttribute("srcpuid", format);
    cformat.addAttribute("srcmime", mimeCode);
    Hashtable<String, HashSet<String>> table = new Hashtable<String, HashSet<String>>();
    Hashtable<String, HashSet<String>> table2 = new Hashtable<String, HashSet<String>>();
    getMimesFormats(table, table2, list, fic.getAbsolutePath(), cformat);
    HashSet<String> formats2 = table2.get("_ALL_");
    if ((mimeCode != null) && (format != null)) {
        if (table.containsKey(mimeCode)) {
            HashSet<String> formats = table.get(mimeCode);
            if (!formats.contains(format)) {
                formats = table2.get(mimeCode);
                if (!formats.contains(format)) {
                    localError = true;
                    fillElementResult(cformat, table, table2, StaticValues.LBL.error_format.get(),
                            "correctpuid", null);
                } else {
                    localWarning = true;
                    fillElementResult(cformat, table, table2, "warning", "correctpuid", "compatiblepuid");
                }
            }
        } else {
            if (table2.containsKey(mimeCode)) {
                HashSet<String> formats = table2.get(mimeCode);
                if (!formats.contains(format)) {
                    localError = true;
                    fillElementResult(cformat, table, table2, StaticValues.LBL.error_format.get(),
                            "correctmime", null);
                } else {
                    localWarning = true;
                    fillElementResult(cformat, table, table2, "warning", "correctmime", "compatiblemime");
                }
            } else {
                localError = true;
                fillElementResult(cformat, table, table2, StaticValues.LBL.error_format.get(), "correctmime",
                        null);
            }
        }
    } else {
        if (mimeCode != null) {
            if (!table.containsKey(mimeCode)) {
                if (table2.containsKey(mimeCode)) {
                    localWarning = true;
                    fillElementResult(cformat, table, table2, "warning", "correctmime", "compatiblemime");
                } else {
                    localError = true;
                    fillElementResult(cformat, table, table2, StaticValues.LBL.error_format.get(),
                            "correctmime", null);
                }
            }
        }
        if (format != null) {
            HashSet<String> formats = table.get("_ALL_");
            if (!formats.contains(format)) {
                formats = table2.get("_ALL_");
                if (!formats.contains(format)) {
                    localWarning = true;
                    fillElementResult(cformat, table, table2, "warning", "correctpuid", "compatiblepuid");
                } else {
                    localError = true;
                    fillElementResult(cformat, table, table2, StaticValues.LBL.error_format.get(),
                            "correctpuid", null);
                }
            }
        }
    }
    if (!localError && !localWarning) {
        fillElementResult(cformat, table, table2, "ok", "found", null);
    } else if (localWarning) {
        // fill subformat
        Element newElt = XmlDom.factory.createElement("subidentities");
        for (String puid : formats2) {
            DroidFileFormat droidFileFormat = StaticValues.config.droidHandler.getDroidFileFormatFromPuid(puid,
                    ficname);
            if (droidFileFormat == null) {
                System.err.println(StaticValues.LBL.error_notfound.get() + puid);
                continue;
            }
            Element subformat = droidFileFormat.toElement(false);
            newElt.add(subformat);
        }
        cformat.add(newElt);
    }
    table.clear();
    table2.clear();
    return cformat;
}

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

License:Open Source License

private final static void getMimesFormats(Hashtable<String, HashSet<String>> table,
        Hashtable<String, HashSet<String>> table2, List<DroidFileFormat> list, String fullPath,
        Element element) {
    HashSet<String> allFormats = new HashSet<String>();
    HashSet<String> allFormats2 = new HashSet<String>();
    boolean withFilename = (list.size() > 1);
    for (DroidFileFormat identity : list) {
        // ensure that if Archive traversal is enabled, we don't use it
        if (identity.getFilename().equals(fullPath)) {
            // check correct signature
            Element subformat = identity.toElement(withFilename);
            String mime = identity.getMimeType();
            HashSet<String> formats = new HashSet<String>();
            String puid = identity.getPUID();
            element.add(subformat);
            formats.add(puid);/*from   www.  j av  a 2  s .  c  o  m*/
            allFormats.addAll(formats);
            if (table.containsKey(mime)) {
                HashSet<String> f = table.get(mime);
                f.addAll(formats);
                table.put(mime, f);
            } else {
                table.put(mime, formats);
            }
            // check additional valid signatures
            HashMap<String, String> map = identity.getAllFormats();
            for (Entry<String, String> entry : map.entrySet()) {
                puid = entry.getKey();
                mime = entry.getValue();
                formats = new HashSet<String>();
                formats.add(puid);
                allFormats2.addAll(formats);
                if (table2.containsKey(mime)) {
                    HashSet<String> f = table2.get(mime);
                    f.addAll(formats);
                    table2.put(mime, f);
                } else {
                    table2.put(mime, formats);
                }
            }
        }
    }
    table.put("_ALL_", allFormats);
    table2.put("_ALL_", allFormats2);
}

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

License:Open Source License

public final static Element fillInformation(VitamArgument argument, Element parent, String name,
        String attribut, String info) {
    Element element = null;/*from www  .  j a  va  2s. c o  m*/
    switch (argument.outputModel) {
    case TXT:
        System.out.println("\t" + name.toUpperCase() + ": " + attribut + " = " + info);
        break;
    case MultipleXML:
    case OneXML:
        element = factory.createElement(name);
        element.addAttribute(attribut, info);
        parent.add(element);
        break;
    }
    return element;
}

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://  w  ww.  j a va  2s  .  c  o m
        try {
            if (writer != null) {
                writer.write(sub);
            }
        } catch (IOException e) {
        }
        break;
    case MultipleXML:
    case OneXML:
        if (sub != null) {
            parent.add(sub);
        }
    }

}