Example usage for org.jdom2 Namespace getNamespace

List of usage examples for org.jdom2 Namespace getNamespace

Introduction

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

Prototype

public static Namespace getNamespace(final String uri) 

Source Link

Document

This will retrieve (if in existence) or create (if not) a Namespace for the supplied URI, and make it usable as a default namespace, as no prefix is supplied.

Usage

From source file:ca.nrc.cadc.dali.tables.votable.VOTableWriter.java

License:Open Source License

/**
 * Builds a empty VOTable document with the appropriate namespaces and
 * attributes./*  w w  w  .ja  v  a2  s .  c o  m*/
 *
 * @return VOTable document.
 */
protected Document createDocument() {
    // the root VOTABLE element
    Namespace vot = Namespace.getNamespace(VOTABLE_12_NS_URI);
    Namespace xsi = Namespace.getNamespace("xsi", XSI_SCHEMA);
    Element votable = new Element("VOTABLE", vot);
    votable.setAttribute("version", VOTABLE_VERSION);
    votable.addNamespaceDeclaration(xsi);

    Document document = new Document();
    document.addContent(votable);

    return document;
}

From source file:ca.nrc.cadc.vos.NodeReader.java

License:Open Source License

/**
 * Constructor. XML schema validation may be disabled, in which case the client
 * is likely to fail in horrible ways (e.g. NullPointerException) if it receives
 * invalid documents. However, performance may be improved.
 *
 * @param enableSchemaValidation//from  w ww.  j a v  a  2  s  . c om
 */
public NodeReader(boolean enableSchemaValidation) {
    if (enableSchemaValidation) {
        String vospaceSchemaUrl = XmlUtil.getResourceUrlString(VOSPACE_SCHEMA_RESOURCE, NodeReader.class);
        log.debug("vospaceSchemaUrl: " + vospaceSchemaUrl);

        String xlinkSchemaUrl = XmlUtil.getResourceUrlString(XLINK_SCHEMA_RESOURCE, NodeReader.class);
        log.debug("xlinkSchemaUrl: " + xlinkSchemaUrl);

        if (vospaceSchemaUrl == null)
            throw new RuntimeException("failed to load " + VOSPACE_SCHEMA_RESOURCE + " from classpath");
        if (vospaceSchemaUrl == null)
            throw new RuntimeException("failed to load " + XLINK_SCHEMA_RESOURCE + " from classpath");

        schemaMap = new HashMap<String, String>();
        schemaMap.put(VOSPACE_SCHEMA_URL, vospaceSchemaUrl);
        schemaMap.put(XLINK_SCHEMA_URL, xlinkSchemaUrl);
        log.debug("schema validation enabled");
    } else
        log.debug("schema validation disabled");

    xsiNamespace = Namespace.getNamespace("http://www.w3.org/2001/XMLSchema-instance");
}

From source file:ca.nrc.cadc.xml.JsonInputter.java

License:Open Source License

private Namespace getNamespace(List<Namespace> namespaces, JSONObject jsonObject, List<String> keys)
        throws JSONException {
    for (String key : keys) {
        if (key.equals("@xmlns")) {
            if (jsonObject.isNull(key)) {
                break;
            }//from w  w w.  jav  a  2s .c  o  m
            String uri = jsonObject.getString(key);
            Namespace namespace = Namespace.getNamespace(uri);
            if (!namespaces.contains(namespace)) {
                namespaces.add(namespace);
            }
            return namespace;
        }
    }
    return null;
}

From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationDstructureModuleImpl.java

License:Open Source License

@Override
public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationDstructureException {
    // Ausgabe SIARD-Modul Ersichtlich das KOST-Val arbeitet
    System.out.print("D   ");
    System.out.print("\r");
    int onWork = 41;

    boolean valid = true;
    try {//from   w  w w  . j  ava 2  s . c  o m
        /* Extract the metadata.xml from the temporare work folder and build a jdom document */
        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        pathToWorkDir = pathToWorkDir + File.separator + "SIARD";
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());
        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each schema and table entry verify existence in temporary
         * extracted structure */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");
        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            valid = validateSchema(schema, ns, pathToWorkDir);
            if (onWork == 41) {
                onWork = 2;
                System.out.print("D-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("D\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("D|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("D/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, ioe.getMessage() + " (IOException)"));
    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (JDOMException)"));
    }

    return valid;
}

From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationFrowModuleImpl.java

License:Open Source License

@Override
public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationFrowException {
    // Ausgabe SIARD-Modul Ersichtlich das KOST-Val arbeitet
    System.out.print("F   ");
    System.out.print("\r");
    int onWork = 41;

    boolean valid = true;
    try {/* www .j av  a  2  s . co  m*/
        /* Extract the metadata.xml from the temporare work folder and build a jdom document */
        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        pathToWorkDir = pathToWorkDir + File.separator + "SIARD";
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());
        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each schema and table entry verify existence in temporary
         * extracted structure and compare the rownumber */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");
        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            valid = validateSchema(schema, ns, pathToWorkDir);
            if (onWork == 41) {
                onWork = 2;
                System.out.print("F-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("F\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("F|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("F/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, ioe.getMessage() + " (IOException)"));
    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (JDOMException)"));
    }

    return valid;
}

From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationGtableModuleImpl.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override// w  w  w .  ja v  a 2 s . c  o m
public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationGtableException {
    // Ausgabe SIARD-Modul Ersichtlich das KOST-Val arbeitet
    System.out.print("G   ");
    System.out.print("\r");
    int onWork = 41;

    boolean valid = true;
    try {
        /* Extract the metadata.xml from the temporare work folder and build a jdom document */

        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        pathToWorkDir = pathToWorkDir + File.separator + "SIARD";
        /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
         * entsprechenden Modul die property anzugeben: <property name="configurationService"
         * ref="configurationService" /> */
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());

        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        // declare ArrayLists
        List listSchemas = new ArrayList();
        List listTables = new ArrayList();
        List listColumns = new ArrayList();

        /* read the document and for each schema and table entry verify existence in temporary
         * extracted structure */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");

        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            String schemaName = schema.getChild("name", ns).getText();

            String lsSch = (new StringBuilder().append(schemaName).toString());

            // select table elements and loop
            List<Element> tables = schema.getChild("tables", ns).getChildren("table", ns);
            for (Element table : tables) {
                String tableName = table.getChild("name", ns).getText();

                // Concatenate schema and table
                String lsTab = (new StringBuilder().append(schemaName).append(" / ").append(tableName)
                        .toString());

                // select column elements and loop
                List<Element> columns = table.getChild("columns", ns).getChildren("column", ns);
                for (Element column : columns) {
                    String columnName = column.getChild("name", ns).getText();

                    // Concatenate schema, table and column
                    String lsCol = (new StringBuilder().append(schemaName).append(" / ").append(tableName)
                            .append(" / ").append(columnName).toString());
                    listColumns.add(lsCol);
                    // concatenating Strings
                }
                listTables.add(lsTab);
                // concatenating Strings (table names)
                if (onWork == 41) {
                    onWork = 2;
                    System.out.print("G-   ");
                    System.out.print("\r");
                } else if (onWork == 11) {
                    onWork = 12;
                    System.out.print("G\\   ");
                    System.out.print("\r");
                } else if (onWork == 21) {
                    onWork = 22;
                    System.out.print("G|   ");
                    System.out.print("\r");
                } else if (onWork == 31) {
                    onWork = 32;
                    System.out.print("G/   ");
                    System.out.print("\r");
                } else {
                    onWork = onWork + 1;
                }
            }
            listSchemas.add(lsSch);
            // concatenating Strings (schema names)
        }
        HashSet hashSchemas = new HashSet(); // check for duplicate schemas
        for (Object value : listSchemas)
            if (!hashSchemas.add(value)) {
                valid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_SIARD)
                        + getTextResourceService().getText(MESSAGE_XML_G_DUPLICATE_SCHEMA, value));
            }
        HashSet hashTables = new HashSet(); // check for duplicate tables
        for (Object value : listTables)
            if (!hashTables.add(value)) {
                valid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_SIARD)
                        + getTextResourceService().getText(MESSAGE_XML_G_DUPLICATE_TABLE, value));
            }
        HashSet hashColumns = new HashSet(); // check for duplicate columns
        for (Object value : listColumns)
            if (!hashColumns.add(value)) {
                valid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_SIARD)
                        + getTextResourceService().getText(MESSAGE_XML_G_DUPLICATE_COLUMN, value));
            }

    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, ioe.getMessage() + " (IOException)"));

    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (JDOMException)"));
        return valid;
    }
    return valid;
}

From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationHcontentModuleImpl.java

License:Open Source License

@Override
public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationHcontentException {
    // Ausgabe SIARD-Modul Ersichtlich das KOST-Val arbeitet
    System.out.print("H   ");
    System.out.print("\r");
    int onWork = 41;

    boolean valid = true;
    try {/*w w  w .  j  a v  a 2  s.c o  m*/
        /* Extract the metadata.xml from the temporary work folder and build a jdom document */
        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        pathToWorkDir = pathToWorkDir + File.separator + "SIARD";
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());
        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each schema and table entry verify existence in temporary
         * extracted structure */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");
        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            Element schemaFolder = schema.getChild("folder", ns);
            File schemaPath = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("content")
                    .append(File.separator).append(schemaFolder.getText()).toString());
            if (schemaPath.isDirectory()) {
                Element[] tables = schema.getChild("tables", ns).getChildren("table", ns)
                        .toArray(new Element[0]);
                for (Element table : tables) {
                    Element tableFolder = table.getChild("folder", ns);
                    File tablePath = new File(new StringBuilder(schemaPath.getAbsolutePath())
                            .append(File.separator).append(tableFolder.getText()).toString());
                    if (tablePath.isDirectory()) {
                        File tableXml = new File(new StringBuilder(tablePath.getAbsolutePath())
                                .append(File.separator).append(tableFolder.getText() + ".xml").toString());
                        File tableXsd = new File(new StringBuilder(tablePath.getAbsolutePath())
                                .append(File.separator).append(tableFolder.getText() + ".xsd").toString());
                        // TODO: hier erfolgt die Validerung
                        if (verifyRowCount(tableXml, tableXsd)) {

                            // valid = validate1( tableXml, tableXsd ) && valid;

                            // xmllint via cmd
                            // resources\xmllint\xmllint --noout --stream --schema tableXsd tableXml
                            try {
                                // Pfad zum Programm xmllint existiert die Dateien?
                                String pathToxmllintExe = "resources" + File.separator + "xmllint"
                                        + File.separator + "xmllint.exe";
                                String pathToxmllintDll1 = "resources" + File.separator + "xmllint"
                                        + File.separator + "iconv.dll";
                                String pathToxmllintDll2 = "resources" + File.separator + "xmllint"
                                        + File.separator + "libxml2.dll";
                                String pathToxmllintDll3 = "resources" + File.separator + "xmllint"
                                        + File.separator + "zlib1.dll";

                                File fpathToxmllintExe = new File(pathToxmllintExe);
                                File fpathToxmllintDll1 = new File(pathToxmllintDll1);
                                File fpathToxmllintDll2 = new File(pathToxmllintDll2);
                                File fpathToxmllintDll3 = new File(pathToxmllintDll3);
                                if (!fpathToxmllintExe.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT1_MISSING));
                                    valid = false;
                                } else if (!fpathToxmllintDll1.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT2_MISSING));
                                    valid = false;
                                } else if (!fpathToxmllintDll2.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT3_MISSING));
                                    valid = false;
                                } else if (!fpathToxmllintDll3.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT4_MISSING));
                                    valid = false;
                                } else {

                                    StringBuffer command = new StringBuffer("resources" + File.separator
                                            + "xmllint" + File.separator + "xmllint ");
                                    command.append("--noout --stream ");
                                    command.append(" --schema ");
                                    command.append(" ");
                                    command.append("\"");
                                    command.append(tableXsd.getAbsolutePath());
                                    command.append("\"");
                                    command.append(" ");
                                    command.append("\"");
                                    command.append(tableXml.getAbsolutePath());
                                    command.append("\"");

                                    Process proc = null;
                                    Runtime rt = null;

                                    try {
                                        File outTableXml = new File(pathToWorkDir + File.separator + "SIARD_H_"
                                                + tableXml.getName() + ".txt");

                                        Util.switchOffConsoleToTxt(outTableXml);

                                        rt = Runtime.getRuntime();
                                        proc = rt.exec(command.toString().split(" "));
                                        // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden
                                        // ist!

                                        // Fehleroutput holen

                                        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(),
                                                "ERROR-" + tableXml.getName());

                                        // Output holen
                                        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(),
                                                "OUTPUT-" + tableXml.getName());

                                        // Threads starten
                                        errorGobbler.start();
                                        outputGobbler.start();

                                        // Warte, bis wget fertig ist 0 = Alles io
                                        int exitStatus = proc.waitFor();

                                        // 200ms warten bis die Konsole umgeschaltet wird, damit wirklich alles im
                                        // file landet
                                        Thread.sleep(200);
                                        Util.switchOnConsole();

                                        if (0 != exitStatus) {
                                            // message.xml.h.invalid.xml = <Message>{0} ist invalid zu
                                            // {1}</Message></Error>
                                            getMessageService().logError(
                                                    getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                                                            + getTextResourceService().getText(
                                                                    MESSAGE_XML_H_INVALID_XML,
                                                                    tableXml.getName(), tableXsd.getName()));
                                            valid = false;

                                            // Fehlermeldung aus outTableXml auslesen

                                            BufferedReader br = new BufferedReader(new FileReader(outTableXml));
                                            try {
                                                String line = br.readLine();
                                                String linePrev = null;
                                                /* Fehlermeldungen holen, ausser die letzte, die besagt, dass es invalide
                                                 * ist (wurde bereits oben in D, F,E ausgegeben */
                                                while (line != null) {
                                                    if (linePrev != null) {
                                                        getMessageService().logError(getTextResourceService()
                                                                .getText(MESSAGE_XML_MODUL_H_SIARD)
                                                                + getTextResourceService().getText(
                                                                        MESSAGE_XML_H_INVALID_ERROR, linePrev));
                                                    }
                                                    linePrev = line;
                                                    line = br.readLine();
                                                }
                                            } finally {
                                                br.close();

                                                /* Konsole zuerst einmal noch umleiten und die Streams beenden, damit die
                                                 * dateien gelscht werden knnen */
                                                Util.switchOffConsoleToTxtClose(outTableXml);
                                                System.out.println(" . ");
                                                Util.switchOnConsole();
                                                Util.deleteFile(outTableXml);

                                            }
                                        } else {
                                            /* Konsole zuerst einmal noch umleiten und die Streams beenden, damit die
                                             * dateien gelscht werden knnen */
                                            Util.switchOffConsoleToTxtClose(outTableXml);
                                            System.out.println(" . ");
                                            Util.switchOnConsole();
                                            Util.deleteFile(outTableXml);

                                        }
                                        /* Konsole zuerst einmal noch umleiten und die Streams beenden, damit die
                                         * dateien gelscht werden knnen */
                                        Util.switchOffConsoleToTxtClose(outTableXml);
                                        System.out.println(" . ");
                                        Util.switchOnConsole();
                                        Util.deleteFile(outTableXml);

                                    } catch (Exception e) {
                                        getMessageService().logError(
                                                getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                                                        + getTextResourceService().getText(ERROR_XML_UNKNOWN,
                                                                e.getMessage()));
                                        return false;
                                    } finally {
                                        if (proc != null) {
                                            closeQuietly(proc.getOutputStream());
                                            closeQuietly(proc.getInputStream());
                                            closeQuietly(proc.getErrorStream());
                                        }
                                    }
                                }
                            } finally {
                            }
                        }
                    }
                    if (onWork == 41) {
                        onWork = 2;
                        System.out.print("H-   ");
                        System.out.print("\r");
                    } else if (onWork == 11) {
                        onWork = 12;
                        System.out.print("H\\   ");
                        System.out.print("\r");
                    } else if (onWork == 21) {
                        onWork = 22;
                        System.out.print("H|   ");
                        System.out.print("\r");
                    } else if (onWork == 31) {
                        onWork = 32;
                        System.out.print("H/   ");
                        System.out.print("\r");
                    } else {
                        onWork = onWork + 1;
                    }
                }
            }
            if (onWork == 41) {
                onWork = 2;
                System.out.print("H-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("H\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("H|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("H/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, ioe.getMessage() + " (IOException)"));
    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (JDOMException)"));
    } catch (SAXException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (SAXException)"));
    }

    return valid;
}

From source file:ch.kostceco.tools.siardexcerpt.excerption.moduleexcerpt.impl.ExcerptCGrepModuleImpl.java

License:Open Source License

@Override
public boolean validate(File siardDatei, File outFile, String excerptString) throws ExcerptCGrepException {
    // Ausgabe -> Ersichtlich das SIARDexcerpt arbeitet
    int onWork = 41;

    boolean isValid = true;

    File fGrepExe = new File("resources" + File.separator + "grep" + File.separator + "grep.exe");
    String pathToGrepExe = fGrepExe.getAbsolutePath();
    if (!fGrepExe.exists()) {
        // grep.exe existiert nicht --> Abbruch
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fGrepExe.getAbsolutePath()));
        return false;
    } else {//from  w  ww .ja  va2  s.  co m
        File fMsys10dll = new File("resources" + File.separator + "grep" + File.separator + "msys-1.0.dll");
        if (!fMsys10dll.exists()) {
            // msys-1.0.dll existiert nicht --> Abbruch
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                    + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fMsys10dll.getAbsolutePath()));
            return false;
        }
    }

    File tempOutFile = new File(outFile.getAbsolutePath() + ".tmp");
    String content = "";

    // Record aus Maintable herausholen
    try {
        if (tempOutFile.exists()) {
            Util.deleteDir(tempOutFile);
        }

        /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
         * entsprechenden Modul die property anzugeben: <property name="configurationService"
         * ref="configurationService" /> */

        String name = getConfigurationService().getMaintableName();
        String folder = getConfigurationService().getMaintableFolder();
        String cell = getConfigurationService().getMaintablePrimarykeyCell();

        File fMaintable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator
                + "schema0" + File.separator + folder + File.separator + folder + ".xml");

        try {
            // grep "<c11>7561234567890</c11>" table13.xml >> output.txt
            String command = "cmd /c \"" + pathToGrepExe + " \"<" + cell + ">" + excerptString + "</" + cell
                    + ">\" " + fMaintable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\"";
            /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
             * gehts: cmd /c\"urspruenlicher Befehl\" */

            // System.out.println( command );

            Process proc = null;
            Runtime rt = null;

            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name));

            try {
                Util.switchOffConsole();
                rt = Runtime.getRuntime();
                proc = rt.exec(command.toString().split(" "));
                // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist!

                // Fehleroutput holen
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

                // Output holen
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

                // Threads starten
                errorGobbler.start();
                outputGobbler.start();

                // Warte, bis wget fertig ist
                proc.waitFor();

                Util.switchOnConsole();

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            } finally {
                if (proc != null) {
                    closeQuietly(proc.getOutputStream());
                    closeQuietly(proc.getInputStream());
                    closeQuietly(proc.getErrorStream());
                }
            }

            Scanner scanner = new Scanner(tempOutFile);
            content = "";
            try {
                content = scanner.useDelimiter("\\Z").next();
            } catch (Exception e) {
                // Grep ergab kein treffer Content Null
                content = "";
            }
            scanner.close();

            getMessageService()
                    .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content));
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name));

            if (tempOutFile.exists()) {
                Util.deleteDir(tempOutFile);
            }
            content = "";

            // Ende Grep

        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                    + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            return false;
        }

    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    // Ende MainTable

    // grep der SubTables
    try {
        String name = null;
        String folder = null;
        String cell = null;

        InputStream fin = new FileInputStream(
                new File("configuration" + File.separator + "SIARDexcerpt.conf.xml"));
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each subTable */
        Namespace ns = Namespace.getNamespace("");

        // select schema elements and loop
        List<Element> subtables = document.getRootElement().getChild("subtables", ns).getChildren("subtable",
                ns);
        for (Element subtable : subtables) {
            name = subtable.getChild("name", ns).getText();
            folder = subtable.getChild("folder", ns).getText();
            cell = subtable.getChild("foreignkeycell", ns).getText();

            // System.out.println( name + " - " + folder + " - " + cell );
            File fSubtable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator
                    + "schema0" + File.separator + folder + File.separator + folder + ".xml");

            try {
                // grep "<c11>7561234567890</c11>" table13.xml >> output.txt
                String command = "cmd /c \"" + pathToGrepExe + " \"<" + cell + ">" + excerptString + "</" + cell
                        + ">\" " + fSubtable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\"";
                /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
                 * gehts: cmd /c\"urspruenlicher Befehl\" */

                // System.out.println( command );

                Process proc = null;
                Runtime rt = null;

                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name));

                try {
                    Util.switchOffConsole();
                    rt = Runtime.getRuntime();
                    proc = rt.exec(command.toString().split(" "));
                    // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist!

                    // Fehleroutput holen
                    StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

                    // Output holen
                    StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

                    // Threads starten
                    errorGobbler.start();
                    outputGobbler.start();

                    // Warte, bis wget fertig ist
                    proc.waitFor();

                    Util.switchOnConsole();

                } catch (Exception e) {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                            + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                    return false;
                } finally {
                    if (proc != null) {
                        closeQuietly(proc.getOutputStream());
                        closeQuietly(proc.getInputStream());
                        closeQuietly(proc.getErrorStream());
                    }
                }

                Scanner scanner = new Scanner(tempOutFile);
                content = "";
                try {
                    content = scanner.useDelimiter("\\Z").next();
                } catch (Exception e) {
                    // Grep ergab kein treffer Content Null
                    content = "";
                }
                scanner.close();

                getMessageService()
                        .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content));
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name));

                if (tempOutFile.exists()) {
                    Util.deleteDir(tempOutFile);
                }
                content = "";

                // Ende Grep

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            }

            // Ende SubTables
            if (onWork == 41) {
                onWork = 2;
                System.out.print("-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
        System.out.print("   ");
        System.out.print("\r");
    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    return isValid;
}

From source file:ch.kostceco.tools.siardval.validation.module.impl.ValidationDstructureModuleImpl.java

License:Open Source License

@Override
public boolean validate(File siardDatei) throws ValidationDstructureException {
    boolean valid = true;
    try {//from  w ww.  ja  v a  2 s  .c  om
        /*
         * Extract the metadata.xml from the temporare work folder and build
         * a jdom document
         */
        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());
        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /*
         * read the document and for each schema and table entry verify
         * existence in temporary extracted structure
         */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");
        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            valid = validateSchema(schema, ns, pathToWorkDir);
        }
    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_D)
                + getTextResourceService().getText(MESSAGE_DASHES) + "IOException " + ioe.getMessage());
    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_D)
                + getTextResourceService().getText(MESSAGE_DASHES) + "JDOMException " + e.getMessage());
    }

    return valid;
}

From source file:ch.kostceco.tools.siardval.validation.module.impl.ValidationGtableModuleImpl.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from www  .j a v  a 2s  . c  om
public boolean validate(File siardDatei) throws ValidationGtableException {
    boolean valid = true;
    try {
        /*
         * Extract the metadata.xml from the temporare work folder and build
         * a jdom document
         */

        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        /*
         * Nicht vergessen in
         * "src/main/resources/config/applicationContext-services.xml" beim
         * entsprechenden Modul die property anzugeben: <property
         * name="configurationService" ref="configurationService" />
         */
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());

        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        // declare ArrayLists
        List listSchemas = new ArrayList();
        List listTables = new ArrayList();
        List listColumns = new ArrayList();

        /*
         * read the document and for each schema and table entry verify
         * existence in temporary extracted structure
         */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");

        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            String schemaName = schema.getChild("name", ns).getText();

            String lsSch = (new StringBuilder().append(schemaName).toString());

            // select table elements and loop
            List<Element> tables = schema.getChild("tables", ns).getChildren("table", ns);
            for (Element table : tables) {
                String tableName = table.getChild("name", ns).getText();

                // Concatenate schema and table
                String lsTab = (new StringBuilder().append(schemaName).append(" / ").append(tableName)
                        .toString());

                // select column elements and loop
                List<Element> columns = table.getChild("columns", ns).getChildren("column", ns);
                for (Element column : columns) {
                    String columnName = column.getChild("name", ns).getText();

                    // Concatenate schema, table and column
                    String lsCol = (new StringBuilder().append(schemaName).append(" / ").append(tableName)
                            .append(" / ").append(columnName).toString());
                    listColumns.add(lsCol); // concatenating Strings
                }
                listTables.add(lsTab); // concatenating Strings (table
                // names)
            }
            listSchemas.add(lsSch); // concatenating Strings (schema
            // names)
        }
        HashSet hashSchemas = new HashSet(); // check for duplicate schemas
        for (Object value : listSchemas)
            if (!hashSchemas.add(value)) {
                valid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G)
                        + getTextResourceService().getText(MESSAGE_DASHES)
                        + getTextResourceService().getText(MESSAGE_MODULE_G_DUPLICATE_SCHEMA, value));
            }
        HashSet hashTables = new HashSet(); // check for duplicate tables
        for (Object value : listTables)
            if (!hashTables.add(value)) {
                valid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G)
                        + getTextResourceService().getText(MESSAGE_DASHES)
                        + getTextResourceService().getText(MESSAGE_MODULE_G_DUPLICATE_TABLE, value));
            }
        HashSet hashColumns = new HashSet(); // check for duplicate columns
        for (Object value : listColumns)
            if (!hashColumns.add(value)) {
                valid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G)
                        + getTextResourceService().getText(MESSAGE_DASHES)
                        + getTextResourceService().getText(MESSAGE_MODULE_G_DUPLICATE_COLUMN, value));
            }

    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G)
                + getTextResourceService().getText(MESSAGE_DASHES) + "IOException " + ioe.getMessage());

    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_G)
                + getTextResourceService().getText(MESSAGE_DASHES) + "JDOMException " + e.getMessage());
        return valid;
    }
    return valid;
}