Example usage for org.w3c.dom Document normalize

List of usage examples for org.w3c.dom Document normalize

Introduction

In this page you can find the example usage for org.w3c.dom Document normalize.

Prototype

public void normalize();

Source Link

Document

Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

Usage

From source file:com.netspective.sparx.util.xml.XmlSource.java

public Document loadXML(File file) {
    if (docSource == null) {
        errors.clear();/*from w  ww  . ja  va  2  s. c  om*/
        sourceFiles.clear();
        metaInfoElem = null;
        metaInfoOptionsElem = null;
    }

    SourceInfo sourceInfo = new SourceInfo(docSource, file);
    sourceFiles.put(file.getAbsolutePath(), sourceInfo);

    Document doc = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = factory.newDocumentBuilder();
        doc = parser.parse(file);
        doc.normalize();
    } catch (Exception e) {
        throw new RuntimeException("XML Parsing error in '" + file.getAbsolutePath() + "': " + e);
    }

    if (docSource == null) {
        xmlDoc = doc;
        docSource = sourceInfo;
    }

    /*
    find all of the <include file="xyz"> elements and "include" all the
    elements in that document as children of the main document
    */

    Element rootElem = doc.getDocumentElement();
    NodeList includes = rootElem.getElementsByTagName("include");
    if (includes != null && includes.getLength() > 0) {
        for (int n = 0; n < includes.getLength(); n++) {
            Element include = (Element) includes.item(n);
            String incFileAttr = include.getAttribute("file");
            File incFile = new File(file.getParentFile(), incFileAttr);
            if (!sourceFiles.containsKey(incFile.getAbsolutePath())) {
                Document includeDoc = loadXML(incFile);
                if (includeDoc != null) {
                    Element includeRoot = includeDoc.getDocumentElement();
                    NodeList incChildren = includeRoot.getChildNodes();
                    for (int c = 0; c < incChildren.getLength(); c++) {
                        Node incCopy = doc.importNode(incChildren.item(c), true);
                        if (incCopy.getNodeType() == Node.ELEMENT_NODE)
                            ((Element) incCopy).setAttribute("_included-from", incFileAttr);
                        rootElem.insertBefore(incCopy, include);
                    }
                }
            }
        }
    }

    /*
     find all of the <pre-process stylesheet="xyz"> elements and "pre-process" using XSLT stylesheets
    */

    NodeList preProcessors = rootElem.getElementsByTagName("pre-process");
    if (preProcessors != null && preProcessors.getLength() > 0) {
        for (int n = 0; n < preProcessors.getLength(); n++) {
            Element preProcessor = (Element) preProcessors.item(n);
            String ppFileAttr = preProcessor.getAttribute("style-sheet");
            if (ppFileAttr.length() == 0) {
                addError("No style-sheet attribute provided for pre-process element");
                continue;
            }
            File ppFile = new File(file.getParentFile(), ppFileAttr);
            docSource.addPreProcessor(new SourceInfo(docSource, ppFile));
            preProcess(ppFile);
        }
    }
    return doc;
}

From source file:com.cloud.network.cisco.CiscoVnmcConnectionImpl.java

private List<String> listNatPolicies(String tenantName) throws ExecutionException {

    String xml = VnmcXml.LIST_NAT_POLICIES.getXml();
    String service = VnmcXml.LIST_NAT_POLICIES.getService();
    xml = replaceXmlValue(xml, "cookie", _cookie);
    xml = replaceXmlValue(xml, "vdcdn", getDnForTenantVDC(tenantName));

    String response = sendRequest(service, xml);

    List<String> result = new ArrayList<String>();
    Document xmlDoc = getDocument(response);
    xmlDoc.normalize();
    NodeList policyList = xmlDoc.getElementsByTagName("pair");
    for (int i = 0; i < policyList.getLength(); i++) {
        Node policyNode = policyList.item(i);
        result.add(policyNode.getAttributes().getNamedItem("key").getNodeValue());
    }//from   ww w . ja v  a2 s  . c  o  m

    return result;
}

From source file:com.cloud.network.cisco.CiscoVnmcConnectionImpl.java

private List<String> listAclPolicies(String tenantName) throws ExecutionException {

    String xml = VnmcXml.LIST_ACL_POLICIES.getXml();
    String service = VnmcXml.LIST_ACL_POLICIES.getService();
    xml = replaceXmlValue(xml, "cookie", _cookie);
    xml = replaceXmlValue(xml, "vdcdn", getDnForTenantVDC(tenantName));

    String response = sendRequest(service, xml);

    List<String> result = new ArrayList<String>();
    Document xmlDoc = getDocument(response);
    xmlDoc.normalize();
    NodeList policyList = xmlDoc.getElementsByTagName("pair");
    for (int i = 0; i < policyList.getLength(); i++) {
        Node policyNode = policyList.item(i);
        result.add(policyNode.getAttributes().getNamedItem("key").getNodeValue());
    }/*from   w w w .  ja  v a2  s.  c om*/

    return result;
}

From source file:com.cloud.network.cisco.CiscoVnmcConnectionImpl.java

private List<String> listChildren(String dn) throws ExecutionException {

    String xml = VnmcXml.LIST_CHILDREN.getXml();
    String service = VnmcXml.LIST_CHILDREN.getService();
    xml = replaceXmlValue(xml, "cookie", _cookie);
    xml = replaceXmlValue(xml, "dn", dn);

    String response = sendRequest(service, xml);

    List<String> result = new ArrayList<String>();
    Document xmlDoc = getDocument(response);
    xmlDoc.normalize();
    NodeList policyList = xmlDoc.getElementsByTagName("policyRule");
    for (int i = 0; i < policyList.getLength(); i++) {
        Node policyNode = policyList.item(i);
        result.add(policyNode.getAttributes().getNamedItem("name").getNodeValue());
    }//from  w  w  w.ja  v  a  2  s  .com

    return result;
}

From source file:com.cloud.network.cisco.CiscoVnmcConnectionImpl.java

@Override
public Map<String, String> listUnAssocAsa1000v() throws ExecutionException {
    String xml = VnmcXml.LIST_UNASSOC_ASA1000V.getXml();
    String service = VnmcXml.LIST_UNASSOC_ASA1000V.getService();
    xml = replaceXmlValue(xml, "cookie", _cookie);

    String response = sendRequest(service, xml);

    Map<String, String> result = new HashMap<String, String>();
    Document xmlDoc = getDocument(response);
    xmlDoc.normalize();
    NodeList fwList = xmlDoc.getElementsByTagName("fwInstance");
    for (int j = 0; j < fwList.getLength(); j++) {
        Node fwNode = fwList.item(j);
        result.put(fwNode.getAttributes().getNamedItem("mgmtIp").getNodeValue(),
                fwNode.getAttributes().getNamedItem("dn").getNodeValue());
    }/* w w w . j  ava2  s . c o m*/

    return result;
}

From source file:com.enonic.vertical.adminweb.ContentObjectHandlerServlet.java

public void handlerForm(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems) throws VerticalAdminException {

    User user = securityService.getLoggedInAdminConsoleUser();
    boolean createContentObject = false;
    String xmlData = null;/*from w w w.j  a  va 2  s  .  com*/
    Document doc;
    String queryParam = "";
    String script = "";

    int menuKey = formItems.getInt("menukey");

    if (request.getParameter("key") == null || request.getParameter("key").equals("")) {
        // Blank form, make dummy document
        doc = XMLTool.createDocument("contentobjects");
        createContentObject = true;
    } else {
        int cobKey = Integer.parseInt(request.getParameter("key"));

        xmlData = admin.getContentObject(cobKey);

        doc = XMLTool.domparse(xmlData);

        NodeList coNodes = doc.getElementsByTagName("contentobject");
        Element contentobject = (Element) coNodes.item(0);
        String contentKeyStr = contentobject.getAttribute("contentkey");
        if (contentKeyStr != null && contentKeyStr.length() > 0) {
            int contentKey = Integer.parseInt(contentKeyStr);

            String contentXML = admin.getContent(user, contentKey, 0, 0, 0);
            Document contentDoc = XMLTool.domparse(contentXML);
            NodeList contentNodes = contentDoc.getElementsByTagName("content");
            Element content = (Element) contentNodes.item(0);
            content = (Element) doc.importNode(content, true);
            contentobject.appendChild(content);
        }

        String menuItemsXML;
        menuItemsXML = admin.getMenuItemsByContentObject(user, cobKey);
        Document menuItemsDoc = XMLTool.domparse(menuItemsXML);
        contentobject.appendChild(doc.importNode(menuItemsDoc.getDocumentElement(), true));

        // Henter ut pagetemplates/frameworks som bruker dette contentobject
        String pageTemplatesXML = admin.getPageTemplatesByContentObject(cobKey);
        Document pageTemplatesDoc = XMLTool.domparse(pageTemplatesXML);
        contentobject.appendChild(doc.importNode(pageTemplatesDoc.getDocumentElement(), true));

        Element objectstylesheetElem = XMLTool.getElement(contentobject, "objectstylesheet");
        ResourceKey objectStyleSheetKey = new ResourceKey(objectstylesheetElem.getAttribute("key"));

        ResourceFile res = resourceService.getResourceFile(objectStyleSheetKey);
        objectstylesheetElem.setAttribute("exist", res == null ? "false" : "true");

        if (res != null) {
            try {
                Document styleSheetDoc = res.getDataAsXml().getAsDOMDocument();
                objectstylesheetElem.setAttribute("valid", "true");

                Element styleSheetRoot = styleSheetDoc.getDocumentElement();
                String attr = styleSheetRoot.getAttribute("xmlns:xsl");
                styleSheetRoot.removeAttribute("xmlns:xsl");
                styleSheetRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", attr);
                Element elem = XMLTool.createElement(doc, contentobject, "objectstylesheet_xsl");
                elem.appendChild(doc.importNode(styleSheetRoot, true));
            } catch (XMLException e) {
                objectstylesheetElem.setAttribute("valid", "false");
            }
        }

        Element borderstylesheetElem = XMLTool.getElement(contentobject, "borderstylesheet");
        if (borderstylesheetElem != null) {
            ResourceKey borderStyleSheetKey = ResourceKey.parse(borderstylesheetElem.getAttribute("key"));
            if (borderStyleSheetKey != null) {
                res = resourceService.getResourceFile(borderStyleSheetKey);
                borderstylesheetElem.setAttribute("exist", res == null ? "false" : "true");
                if (res != null) {
                    try {
                        Document borderStyleSheetDoc = res.getDataAsXml().getAsDOMDocument();
                        borderstylesheetElem.setAttribute("valid", "true");

                        Element styleSheetRoot = borderStyleSheetDoc.getDocumentElement();
                        String attr = styleSheetRoot.getAttribute("xmlns:xsl");
                        styleSheetRoot.removeAttribute("xmlns:xsl");
                        styleSheetRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", attr);
                        Element elem = XMLTool.createElement(doc, contentobject, "borderstylesheet_xsl");
                        elem.appendChild(doc.importNode(styleSheetRoot, true));
                    } catch (XMLException e) {
                        borderstylesheetElem.setAttribute("valid", "false");
                    }
                }
            }
        }
    }

    if (xmlData != null) {
        Map subelems = XMLTool.filterElements(doc.getDocumentElement().getChildNodes());
        if (subelems.get("contentobject") != null) {
            Element tempElem = (Element) subelems.get("contentobject");
            Map contentobjectmap = XMLTool.filterElements(tempElem.getChildNodes());

            Element contentobjectdata = (Element) contentobjectmap.get("contentobjectdata");
            Map queryparammap = XMLTool.filterElements(contentobjectdata.getChildNodes());
            tempElem = (Element) queryparammap.get("datasources");

            Document queryParamDoc = XMLTool.createDocument();
            tempElem = (Element) queryParamDoc.importNode(tempElem, true);
            queryParamDoc.appendChild(tempElem);

            StringWriter sw = new StringWriter();
            queryParamDoc.normalize();
            XMLTool.printDocument(sw, queryParamDoc, 0);
            queryParam = sw.toString();

            // Find the script data
            Element scriptElem = (Element) queryparammap.get("script");
            if (scriptElem != null) {
                script = XMLTool.getElementText(scriptElem);
            }

            Element[] paramElems = XMLTool.getElements(contentobjectdata, "stylesheetparam");
            for (Element paramElem1 : paramElems) {
                String type = paramElem1.getAttribute("type");
                if ("page".equals(type)) {
                    String menuItemKeyStr = XMLTool.getElementText(paramElem1);
                    int menuItemKey = Integer.parseInt(menuItemKeyStr);
                    String name = admin.getMenuItemName(menuItemKey);
                    paramElem1.setAttribute("valuename", name);
                } else if ("category".equals(type)) {
                    String categoryKeyStr = XMLTool.getElementText(paramElem1);
                    int categoryKey = Integer.parseInt(categoryKeyStr);
                    String name = admin.getMenuItemName(categoryKey);
                    paramElem1.setAttribute("valuename", name);
                }
            }

            paramElems = XMLTool.getElements(contentobjectdata, "borderparam");
            for (Element paramElem : paramElems) {
                String type = paramElem.getAttribute("type");
                if ("page".equals(type)) {
                    String menuItemKeyStr = XMLTool.getElementText(paramElem);
                    int menuItemKey = Integer.parseInt(menuItemKeyStr);
                    String name = admin.getMenuItemName(menuItemKey);
                    paramElem.setAttribute("valuename", name);
                } else if ("category".equals(type)) {
                    String categoryKeyStr = XMLTool.getElementText(paramElem);
                    int categoryKey = Integer.parseInt(categoryKeyStr);
                    String name = admin.getMenuItemName(categoryKey);
                    paramElem.setAttribute("valuename", name);
                }
            }
        }
    }

    ExtendedMap parameters = new ExtendedMap();

    // Get default css if present
    ResourceKey defaultCSS = admin.getDefaultCSSByMenu(menuKey);
    if (defaultCSS != null) {
        parameters.put("defaultcsskey", defaultCSS.toString());
        parameters.put("defaultcsskeyExist",
                resourceService.getResourceFile(defaultCSS) == null ? "false" : "true");
    }

    VerticalAdminLogger.debug(this.getClass(), 0, doc);

    addCommonParameters(admin, user, request, parameters, -1, menuKey);

    if (createContentObject) {
        parameters.put("create", "1");
        parameters.put("queryparam", "<?xml version=\"1.0\" ?>\n<datasources/>");
    } else {
        parameters.put("create", "0");
        queryParam = StringUtil.formatXML(queryParam, 2);
        parameters.put("queryparam", queryParam);
    }

    parameters.put("menukey", String.valueOf(menuKey));

    parameters.put("page", String.valueOf(request.getParameter("page")));

    String subop = formItems.getString("subop", "");
    if ("popup".equals(subop)) {
        URL redirectURL = new URL("adminpage");
        redirectURL.setParameter("op", "callback");
        redirectURL.setParameter("callback", formItems.getString("callback"));
        redirectURL.setParameter("page", 991);
        redirectURL.setParameter("key", Integer.parseInt(request.getParameter("key")));
        redirectURL.setParameter("fieldname", formItems.getString("fieldname"));
        redirectURL.setParameter("fieldrow", formItems.getString("fieldrow"));
        parameters.put("referer", redirectURL.toString());
        parameters.put("subop", "popup");
    } else {
        parameters.put("referer", request.getHeader("referer"));
    }

    parameters.put("subop", subop);
    parameters.put("fieldname", formItems.getString("fieldname", null));
    parameters.put("fieldrow", formItems.getString("fieldrow", null));
    parameters.put("script", script);

    addAccessLevelParameters(user, parameters);

    UserEntity defaultRunAsUser = siteDao.findByKey(menuKey).resolveDefaultRunAsUser();
    String defaultRunAsUserName = "NA";
    if (defaultRunAsUser != null) {
        defaultRunAsUserName = defaultRunAsUser.getDisplayName();
    }
    parameters.put("defaultRunAsUser", defaultRunAsUserName);

    transformXML(request, response, doc, "contentobject_form.xsl", parameters);
}

From source file:ch.kostceco.tools.kostval.validation.modulejp2.impl.ValidationAvalidationAModuleImpl.java

@Override
public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationAjp2validationException {

    // Start mit der Erkennung

    // Eine JP2 Datei (.jp2) muss mit ....jP ...ftypjp2
    // [0000000c6a5020200d0a870a] beginnen
    if (valDatei.isDirectory()) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                + getTextResourceService().getText(ERROR_XML_A_JP2_ISDIRECTORY));
        return false;
    } else if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".jp2"))) {

        FileReader fr = null;// ww w.  j av a 2s .c  om

        try {
            fr = new FileReader(valDatei);
            BufferedReader read = new BufferedReader(fr);

            // wobei hier nur die ersten 10 Zeichen der Datei ausgelesen werden
            // 1 00 010203
            // 2 0c 04
            // 3 6a 05
            // 4 50 06
            // 5 20 0708
            // 6 0d 09
            // 7 0a 10

            // Hex 00 in Char umwandeln
            String str1 = "00";
            int i1 = Integer.parseInt(str1, 16);
            char c1 = (char) i1;
            // Hex 0c in Char umwandeln
            String str2 = "0c";
            int i2 = Integer.parseInt(str2, 16);
            char c2 = (char) i2;
            // Hex 6a in Char umwandeln
            String str3 = "6a";
            int i3 = Integer.parseInt(str3, 16);
            char c3 = (char) i3;
            // Hex 50 in Char umwandeln
            String str4 = "50";
            int i4 = Integer.parseInt(str4, 16);
            char c4 = (char) i4;
            // Hex 20 in Char umwandeln
            String str5 = "20";
            int i5 = Integer.parseInt(str5, 16);
            char c5 = (char) i5;
            // Hex 0d in Char umwandeln
            String str6 = "0d";
            int i6 = Integer.parseInt(str6, 16);
            char c6 = (char) i6;
            // Hex 0a in Char umwandeln
            String str7 = "0a";
            int i7 = Integer.parseInt(str7, 16);
            char c7 = (char) i7;

            // auslesen der ersten 10 Zeichen der Datei
            int length;
            int i;
            char[] buffer = new char[10];
            length = read.read(buffer);
            for (i = 0; i != length; i++)
                ;

            /* die beiden charArrays (soll und ist) mit einander vergleichen IST = c1c1c1c2c3c4c5c5c6c7 */
            char[] charArray1 = buffer;
            char[] charArray2 = new char[] { c1, c1, c1, c2, c3, c4, c5, c5, c6, c7 };

            if (Arrays.equals(charArray1, charArray2)) {
                /* hchstwahrscheinlich ein JP2 da es mit 0000000c6a5020200d0a respektive ....jP ..
                 * beginnt */
            } else {
                // TODO: Droid-Erkennung, damit Details ausgegeben werden knnen
                String nameOfSignature = getConfigurationService().getPathToDroidSignatureFile();
                if (nameOfSignature == null) {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                            + getTextResourceService().getText(MESSAGE_XML_CONFIGURATION_ERROR_NO_SIGNATURE));
                    return false;
                }
                // existiert die SignatureFile am angebenen Ort?
                File fnameOfSignature = new File(nameOfSignature);
                if (!fnameOfSignature.exists()) {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                            + getTextResourceService().getText(MESSAGE_XML_CA_DROID));
                    return false;
                }

                Droid droid = null;
                try {
                    /* kleiner Hack, weil die Droid libraries irgendwo ein System.out drin haben, welche den
                     * Output stren Util.switchOffConsole() als Kommentar markieren wenn man die
                     * Fehlermeldung erhalten mchte */
                    Util.switchOffConsole();
                    droid = new Droid();

                    droid.readSignatureFile(nameOfSignature);

                } catch (Exception e) {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                            + getTextResourceService().getText(ERROR_XML_CANNOT_INITIALIZE_DROID));
                    return false;
                } finally {
                    Util.switchOnConsole();
                }
                File file = valDatei;
                String puid = "";
                IdentificationFile ifile = droid.identify(file.getAbsolutePath());
                for (int x = 0; x < ifile.getNumHits(); x++) {
                    FileFormatHit ffh = ifile.getHit(x);
                    FileFormat ff = ffh.getFileFormat();
                    puid = ff.getPUID();
                }
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                        + getTextResourceService().getText(ERROR_XML_A_JP2_INCORRECTFILE, puid));
                return false;
            }
        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                    + getTextResourceService().getText(ERROR_XML_A_JP2_INCORRECTFILE));
            return false;
        }
    } else {
        // die Datei endet nicht mit jp2 -> Fehler
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                + getTextResourceService().getText(ERROR_XML_A_JP2_INCORRECTFILEENDING));
        return false;
    }
    // Ende der Erkennung

    boolean isValid = false;

    // TODO: Erledigt - Initialisierung Jpylyzer -> existiert Jpylyzer?
    String pathToJpylyzerExe = "resources" + File.separator + "jpylyzer" + File.separator + "jpylyzer.exe";

    File fJpylyzerExe = new File(pathToJpylyzerExe);
    if (!fJpylyzerExe.exists()) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                + getTextResourceService().getText(ERROR_XML_A_JP2_JPYLYZER_MISSING));
    }

    pathToJpylyzerExe = "\"" + pathToJpylyzerExe + "\"";

    try {
        File report;
        Document doc = null;

        try {
            // jpylyzer-Befehl: pathToJpylyzerExe valDatei > valDatei.jpylyzer-log.xml
            String outputPath = directoryOfLogfile.getAbsolutePath();
            String outputName = File.separator + valDatei.getName() + ".jpylyzer-log.xml";
            String pathToJpylyzerReport = outputPath + outputName;
            File output = new File(pathToJpylyzerReport);
            Runtime rt = Runtime.getRuntime();
            Process proc = null;

            try {
                report = output;

                // falls das File bereits existiert, z.B. von einem vorhergehenden Durchlauf, lschen wir
                // es
                if (report.exists()) {
                    report.delete();
                }

                /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
                 * gehts: cmd /c\"urspruenlicher Befehl\" */
                String command = "cmd /c \"" + pathToJpylyzerExe + " \"" + valDatei.getAbsolutePath()
                        + "\" > \"" + output.getAbsolutePath() + "\"\"";
                proc = rt.exec(command.toString().split(" "));
                // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist!

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

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                        + getTextResourceService().getText(ERROR_XML_A_JP2_SERVICEFAILED, e.getMessage()));
                return false;
            } finally {
                if (proc != null) {
                    closeQuietly(proc.getOutputStream());
                    closeQuietly(proc.getInputStream());
                    closeQuietly(proc.getErrorStream());
                }
            }
            if (report.exists()) {
                // alles io
            } else {
                // Datei nicht angelegt...
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                        + getTextResourceService().getText(ERROR_XML_A_JP2_NOREPORT));
                return false;
            }

            // Ende Jpylyzer direkt auszulsen

            // TODO: Erledigt - Ergebnis auslesen

            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pathToJpylyzerReport));
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(bis);
            doc.normalize();

            NodeList nodeLstI = doc.getElementsByTagName("isValidJP2");

            // Node isValidJP2 enthlt im TextNode das Resultat TextNode ist ein ChildNode
            for (int s = 0; s < nodeLstI.getLength(); s++) {
                Node resultNode = nodeLstI.item(s);
                StringBuffer buf = new StringBuffer();
                NodeList children = resultNode.getChildNodes();
                for (int i = 0; i < children.getLength(); i++) {
                    Node textChild = children.item(i);
                    if (textChild.getNodeType() != Node.TEXT_NODE) {
                        continue;
                    }
                    buf.append(textChild.getNodeValue());
                }
                String result = buf.toString();

                // Das Resultat ist False oder True
                if (result.equalsIgnoreCase("True")) {
                    // valid
                    isValid = true;
                } else {
                    // invalide
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                            + getTextResourceService().getText(ERROR_XML_A_JP2_JPYLYZER_FAIL));
                    isValid = false;
                }
            }

        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                    + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            return false;
        }
        // TODO: Erledigt: Fehler Auswertung

        if (!isValid) {
            // Invalide JP2-Datei
            int isignatureBox = 0;
            int ifileTypeBox = 0;
            int iimageHeaderBox = 0;
            int ibitsPerComponentBox = 0;
            int icolourSpecificationBox = 0;
            int ipaletteBox = 0;
            int icomponentMappingBox = 0;
            int ichannelDefinitionBox = 0;
            int iresolutionBox = 0;
            int itileParts = 0;
            int isiz = 0;
            int icod = 0;
            int iqcd = 0;
            int icoc = 0;
            int icom = 0;
            int iqcc = 0;
            int irgn = 0;
            int ipoc = 0;
            int iplm = 0;
            int ippm = 0;
            int itlm = 0;
            int icrg = 0;
            int iplt = 0;
            int ippt = 0;
            int ixmlBox = 0;
            int iuuidBox = 0;
            int iuuidInfoBox = 0;
            int iunknownBox = 0;
            int icontainsImageHeaderBox = 0;
            int icontainsColourSpecificationBox = 0;
            int icontainsBitsPerComponentBox = 0;
            int ifirstJP2HeaderBoxIsImageHeaderBox = 0;
            int inoMoreThanOneImageHeaderBox = 0;
            int inoMoreThanOneBitsPerComponentBox = 0;
            int inoMoreThanOnePaletteBox = 0;
            int inoMoreThanOneComponentMappingBox = 0;
            int inoMoreThanOneChannelDefinitionBox = 0;
            int inoMoreThanOneResolutionBox = 0;
            int icolourSpecificationBoxesAreContiguous = 0;
            int ipaletteAndComponentMappingBoxesOnlyTogether = 0;

            int icodestreamStartsWithSOCMarker = 0;
            int ifoundSIZMarker = 0;
            int ifoundCODMarker = 0;
            int ifoundQCDMarker = 0;
            int iquantizationConsistentWithLevels = 0;
            int ifoundExpectedNumberOfTiles = 0;
            int ifoundExpectedNumberOfTileParts = 0;
            int ifoundEOCMarker = 0;

            NodeList nodeLstTest = doc.getElementsByTagName("tests");

            // Node test enthlt alle invaliden tests
            for (int s = 0; s < nodeLstTest.getLength(); s++) {
                Node testNode = nodeLstTest.item(s);
                NodeList children = testNode.getChildNodes();
                for (int i = 0; i < children.getLength(); i++) {
                    Node textChild = children.item(i);
                    if (textChild.getNodeType() == Node.ELEMENT_NODE) {
                        if (textChild.getNodeName().equals("signatureBox")) {
                            isignatureBox = isignatureBox + 1;
                        } else if (textChild.getNodeName().equals("fileTypeBox")) {
                            ifileTypeBox = ifileTypeBox + 1;
                        } else if (textChild.getNodeName().equals("jp2HeaderBox")) {
                            NodeList childrenII = textChild.getChildNodes();
                            for (int j = 0; j < childrenII.getLength(); j++) {
                                Node textChildII = childrenII.item(j);
                                if (textChildII.getNodeType() == Node.ELEMENT_NODE) {
                                    if (textChildII.getNodeName().equals("imageHeaderBox")) {
                                        iimageHeaderBox = iimageHeaderBox + 1;
                                    } else if (textChildII.getNodeName().equals("bitsPerComponentBox")) {
                                        ibitsPerComponentBox = ibitsPerComponentBox + 1;
                                    } else if (textChildII.getNodeName().equals("colourSpecificationBox")) {
                                        icolourSpecificationBox = icolourSpecificationBox + 1;
                                    } else if (textChildII.getNodeName().equals("paletteBox")) {
                                        ipaletteBox = ipaletteBox + 1;
                                    } else if (textChildII.getNodeName().equals("componentMappingBox")) {
                                        icomponentMappingBox = icomponentMappingBox + 1;
                                    } else if (textChildII.getNodeName().equals("channelDefinitionBox")) {
                                        ichannelDefinitionBox = ichannelDefinitionBox + 1;
                                    } else if (textChildII.getNodeName().equals("resolutionBox")) {
                                        iresolutionBox = iresolutionBox + 1;
                                    } else if (textChildII.getNodeName().equals("containsImageHeaderBox")) {
                                        icontainsImageHeaderBox = icontainsImageHeaderBox + 1;
                                    } else if (textChildII.getNodeName()
                                            .equals("containsColourSpecificationBox")) {
                                        icontainsColourSpecificationBox = icontainsColourSpecificationBox + 1;
                                    } else if (textChildII.getNodeName()
                                            .equals("containsBitsPerComponentBox")) {
                                        icontainsBitsPerComponentBox = icontainsBitsPerComponentBox + 1;
                                    } else if (textChildII.getNodeName()
                                            .equals("firstJP2HeaderBoxIsImageHeaderBox")) {
                                        ifirstJP2HeaderBoxIsImageHeaderBox = ifirstJP2HeaderBoxIsImageHeaderBox
                                                + 1;
                                    } else if (textChildII.getNodeName()
                                            .equals("noMoreThanOneImageHeaderBox")) {
                                        inoMoreThanOneImageHeaderBox = inoMoreThanOneImageHeaderBox + 1;
                                    } else if (textChildII.getNodeName()
                                            .equals("noMoreThanOneBitsPerComponentBox")) {
                                        inoMoreThanOneBitsPerComponentBox = inoMoreThanOneBitsPerComponentBox
                                                + 1;
                                    } else if (textChildII.getNodeName().equals("noMoreThanOnePaletteBox")) {
                                        inoMoreThanOnePaletteBox = inoMoreThanOnePaletteBox + 1;
                                    } else if (textChildII.getNodeName()
                                            .equals("noMoreThanOneComponentMappingBox")) {
                                        inoMoreThanOneComponentMappingBox = inoMoreThanOneComponentMappingBox
                                                + 1;
                                    } else if (textChildII.getNodeName()
                                            .equals("noMoreThanOneChannelDefinitionBox")) {
                                        inoMoreThanOneChannelDefinitionBox = inoMoreThanOneChannelDefinitionBox
                                                + 1;
                                    } else if (textChildII.getNodeName().equals("noMoreThanOneResolutionBox")) {
                                        inoMoreThanOneResolutionBox = inoMoreThanOneResolutionBox + 1;
                                    } else if (textChildII.getNodeName()
                                            .equals("colourSpecificationBoxesAreContiguous")) {
                                        icolourSpecificationBoxesAreContiguous = icolourSpecificationBoxesAreContiguous
                                                + 1;
                                    } else if (textChildII.getNodeName()
                                            .equals("paletteAndComponentMappingBoxesOnlyTogether")) {
                                        ipaletteAndComponentMappingBoxesOnlyTogether = ipaletteAndComponentMappingBoxesOnlyTogether
                                                + 1;
                                    }
                                }
                                continue;
                            }
                        } else if (textChild.getNodeName().equals("contiguousCodestreamBox")) {
                            NodeList childrenIII = textChild.getChildNodes();
                            for (int k = 0; k < childrenIII.getLength(); k++) {
                                Node textChildIII = childrenIII.item(k);
                                if (textChildIII.getNodeType() == Node.ELEMENT_NODE) {
                                    if (textChildIII.getNodeName().equals("tileParts")) {
                                        itileParts = itileParts + 1;
                                    } else if (textChildIII.getNodeName().equals("siz")) {
                                        isiz = isiz + 1;
                                    } else if (textChildIII.getNodeName().equals("cod")) {
                                        icod = icod + 1;
                                    } else if (textChildIII.getNodeName().equals("qcd")) {
                                        iqcd = iqcd + 1;
                                    } else if (textChildIII.getNodeName().equals("coc")) {
                                        icoc = icoc + 1;
                                    } else if (textChildIII.getNodeName().equals("com")) {
                                        icom = icom + 1;
                                    } else if (textChildIII.getNodeName().equals("qcc")) {
                                        iqcc = iqcc + 1;
                                    } else if (textChildIII.getNodeName().equals("rgn")) {
                                        irgn = irgn + 1;
                                    } else if (textChildIII.getNodeName().equals("poc")) {
                                        ipoc = ipoc + 1;
                                    } else if (textChildIII.getNodeName().equals("plm")) {
                                        iplm = iplm + 1;
                                    } else if (textChildIII.getNodeName().equals("ppm")) {
                                        ippm = ippm + 1;
                                    } else if (textChildIII.getNodeName().equals("tlm")) {
                                        itlm = itlm + 1;
                                    } else if (textChildIII.getNodeName().equals("crg")) {
                                        icrg = icrg + 1;
                                    } else if (textChildIII.getNodeName().equals("plt")) {
                                        iplt = iplt + 1;
                                    } else if (textChildIII.getNodeName().equals("ppt")) {
                                        ippt = ippt + 1;
                                    } else if (textChildIII.getNodeName()
                                            .equals("codestreamStartsWithSOCMarker")) {
                                        icodestreamStartsWithSOCMarker = icodestreamStartsWithSOCMarker + 1;
                                    } else if (textChildIII.getNodeName().equals("foundSIZMarker")) {
                                        ifoundSIZMarker = ifoundSIZMarker + 1;
                                    } else if (textChildIII.getNodeName().equals("foundCODMarker")) {
                                        ifoundCODMarker = ifoundCODMarker + 1;
                                    } else if (textChildIII.getNodeName().equals("foundQCDMarker")) {
                                        ifoundQCDMarker = ifoundQCDMarker + 1;
                                    } else if (textChildIII.getNodeName()
                                            .equals("quantizationConsistentWithLevels")) {
                                        iquantizationConsistentWithLevels = iquantizationConsistentWithLevels
                                                + 1;
                                    } else if (textChildIII.getNodeName()
                                            .equals("foundExpectedNumberOfTiles")) {
                                        ifoundExpectedNumberOfTiles = ifoundExpectedNumberOfTiles + 1;
                                    } else if (textChildIII.getNodeName()
                                            .equals("foundExpectedNumberOfTileParts")) {
                                        ifoundExpectedNumberOfTileParts = ifoundExpectedNumberOfTileParts + 1;
                                    } else if (textChildIII.getNodeName().equals("foundEOCMarker")) {
                                        ifoundEOCMarker = ifoundEOCMarker + 1;
                                    }
                                }
                                continue;
                            }
                        } else if (textChild.getNodeName().equals("xmlBox")) {
                            ixmlBox = ixmlBox + 1;
                        } else if (textChild.getNodeName().equals("uuidBox")) {
                            iuuidBox = iuuidBox + 1;
                        } else if (textChild.getNodeName().equals("uuidInfoBox")) {
                            iuuidInfoBox = iuuidInfoBox + 1;
                        } else if (textChild.getNodeName().equals("unknownBox")) {
                            iunknownBox = iunknownBox + 1;
                        }
                    }
                    continue;
                }
                continue;
            }

            if (isignatureBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                        + getTextResourceService().getText(ERROR_XML_A_JP2_SIGNATURE));
            }
            if (ifileTypeBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2)
                        + getTextResourceService().getText(ERROR_XML_A_JP2_FILETYPE));
            }
            if (iimageHeaderBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_IMAGE));
            }
            if (ibitsPerComponentBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_BITSPC));
            }
            if (icolourSpecificationBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_COLOUR));
            }
            if (ipaletteBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_PALETTE));
            }
            if (icomponentMappingBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_MAPPING));
            }
            if (ichannelDefinitionBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_CHANNEL));
            }
            if (iresolutionBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_RESOLUTION));
            }

            if (icontainsImageHeaderBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_NOIHB));
            }
            if (icontainsColourSpecificationBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_NOCSB));
            }
            if (icontainsBitsPerComponentBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_NBPCB));
            }
            if (ifirstJP2HeaderBoxIsImageHeaderBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_IHBNF));
            }
            if (inoMoreThanOneImageHeaderBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_IHBMO));
            }
            if (inoMoreThanOneBitsPerComponentBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_OBPCMO));
            }
            if (inoMoreThanOnePaletteBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_OPBMO));
            }
            if (inoMoreThanOneComponentMappingBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_CMBMO));
            }
            if (inoMoreThanOneChannelDefinitionBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_CDBMO));
            }
            if (inoMoreThanOneResolutionBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_RBMO));
            }
            if (icolourSpecificationBoxesAreContiguous >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_CSBNC));
            }
            if (ipaletteAndComponentMappingBoxesOnlyTogether >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2)
                        + getTextResourceService().getText(ERROR_XML_B_JP2_PACMB));
            }

            if (icodestreamStartsWithSOCMarker >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_SOC));
            }
            if (ifoundSIZMarker >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_FSIZ));
            }
            if (ifoundCODMarker >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_FCOD));
            }
            if (ifoundQCDMarker >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_FQCD));
            }
            if (iquantizationConsistentWithLevels >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_PQCD));
            }
            if (ifoundExpectedNumberOfTiles >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_NOTILES));
            }
            if (ifoundExpectedNumberOfTileParts >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_NOTILESPART));
            }
            if (ifoundEOCMarker >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_EOC));
            }

            if (itileParts >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_TILEPARTS));
            }
            if (isiz >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_SIZ));
            }
            if (icod >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_COD));
            }
            if (iqcd >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_QCD));
            }
            if (icom >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_COM));
            }
            if (icoc >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_COC));
            }
            if (irgn >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_RGN));
            }
            if (iqcc >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_QCC));
            }
            if (ipoc >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_POC));
            }
            if (iplm >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_PLM));
            }
            if (ippm >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_PPM));
            }
            if (itlm >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_TLM));
            }
            if (icrg >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_CRG));
            }
            if (iplt >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_PLT));
            }
            if (ippt >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2)
                        + getTextResourceService().getText(ERROR_XML_C_JP2_PPT));
            }

            if (ixmlBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_JP2)
                        + getTextResourceService().getText(ERROR_XML_D_JP2_XML));
            }
            if (iuuidBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_JP2)
                        + getTextResourceService().getText(ERROR_XML_D_JP2_UUID));
            }
            if (iuuidInfoBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_JP2)
                        + getTextResourceService().getText(ERROR_XML_D_JP2_UUIDINFO));
            }
            if (iunknownBox >= 1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_JP2)
                        + getTextResourceService().getText(ERROR_XML_D_JP2_UNKNOWN));
            }
        }

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

From source file:ch.kostceco.tools.kostval.validation.modulepdfa.impl.ValidationAvalidationAiModuleImpl.java

@Override
public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationApdfvalidationException {
    @SuppressWarnings("unused")
    boolean valid = false;

    // Version & Level herausfinden
    String pdfa1 = getConfigurationService().pdfa1();
    String pdfa2 = getConfigurationService().pdfa2();

    Integer pdfaVer1 = 0;/*  www. ja  v  a  2 s .c o m*/
    Integer pdfaVer2 = 0;

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

    // Vorbereitung fr eine allfllige Festhaltung bei unterschiedlichen Validierungsresultaten in
    // einer PDF_Diagnosedatei
    File pdfDia = null;
    String pdfDiaPath = getConfigurationService().getPathToDiagnose();

    try {
        pdfDia = new File(pdfDiaPath + File.separator + "PDF-Diagnosedaten.kost-val.xml");
        if (!pdfDia.exists()) {
            pdfDia.createNewFile();
            PrintWriter output;
            BufferedWriter buffer;
            FileWriter fileWriter;
            fileWriter = new FileWriter(pdfDia);
            buffer = new BufferedWriter(fileWriter);
            output = new PrintWriter(buffer);
            try {
                output.print(getTextResourceService().getText(MESSAGE_XML_DIAHEADER) + "\n");
                output.print(getTextResourceService().getText(MESSAGE_XML_DIAEND));
            } finally {
                output.close();
                buffer.close();
                fileWriter.close();
            }
        }
        File xslDiaOrig = new File("resources" + File.separator + "kost-val_PDFdia.xsl");
        File xslDiaCopy = new File(pdfDiaPath + File.separator + "kost-val_PDFdia.xsl");
        if (!xslDiaCopy.exists()) {
            Util.copyFile(xslDiaOrig, xslDiaCopy);
        }
    } catch (IOException e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
    }

    /* Neu soll die Validierung mit PDFTron konfigurier bar sein Mgliche Werte 1A, 1B und no sowie
     * 2A, 2B, 2U und no Da Archive beide Versionen erlauben knnen sind es 2 config eintrge Es
     * gibt mehre Mglichkeiten das PDF in der gewnschten Version zu testen - Unterscheidung anhand
     * DROID --> braucht viel Zeit auch mit KaD_Signaturefile - Unterscheidung anhand PDF/A-Eintrag
     * wie Droid aber selber programmiert --> ist viel schneller */
    if (pdfa2.equals("2A") || pdfa2.equals("2B") || pdfa2.equals("2U")) {
        // gltiger Konfigurationseintrag und V2 erlaubt
        pdfaVer2 = 2;
    } else {
        // v2 nicht erlaubt oder falscher eintrag
        pdfa2 = "no";
    }
    if (pdfa1.equals("1A") || pdfa1.equals("1B")) {
        // gltiger Konfigurationseintrag und V1 erlaubt
        pdfaVer1 = 1;
    } else {
        // v1 nicht erlaubt oder falscher eintrag
        pdfa1 = "no";
    }
    if (pdfa1 == "no" && pdfa2 == "no") {
        // keine Validierung mglich. keine PDFA-Versionen konfiguriert
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                + getTextResourceService().getText(ERROR_XML_A_PDFA_NOCONFIG));
        valid = false;
        return false;
    }

    String level = "no";
    // Richtiges Level definieren
    if (pdfaVer1 != 1) {
        // Level 1 nicht erlaubt --> Level 2
        level = pdfa2;
    } else if (pdfaVer2 != 2) {
        // Level 2 nicht erlaubt --> Level 1
        level = pdfa1;
    } else {
        try {
            // Beide sind mglich --> Level je nach File auswhlen
            pdfaVer1 = 0;
            pdfaVer2 = 0;
            BufferedReader in = new BufferedReader(new FileReader(valDatei));
            String line;
            while ((line = in.readLine()) != null) {
                // hufige Partangaben: pdfaid:part>1< pdfaid:part='1' pdfaid:part="1"
                if (line.contains("pdfaid:part")) {
                    // pdfaid:part
                    if (line.contains("pdfaid:part>1<")) {
                        level = pdfa1;
                        pdfaVer1 = 1;
                    } else if (line.contains("pdfaid:part='1'")) {
                        level = pdfa1;
                        pdfaVer1 = 1;
                    } else if (line.contains("pdfaid:part=\"1\"")) {
                        level = pdfa1;
                        pdfaVer1 = 1;
                    } else if (line.contains("pdfaid:part>2<")) {
                        level = pdfa2;
                        pdfaVer2 = 2;
                    } else if (line.contains("pdfaid:part='2'")) {
                        level = pdfa2;
                        pdfaVer2 = 2;
                    } else if (line.contains("pdfaid:part=\"2\"")) {
                        level = pdfa2;
                        pdfaVer2 = 2;
                    } else if (line.contains("pdfaid:part") && line.contains("1")) {
                        // PDFA-Version = 1
                        level = pdfa1;
                        pdfaVer1 = 1;
                    } else if (line.contains("pdfaid:part") && line.contains("2")) {
                        // PDFA-Version = 2
                        level = pdfa2;
                        pdfaVer2 = 2;
                    }
                }
                if (pdfaVer1 == 0 && pdfaVer2 == 0) {
                    // der Part wurde nicht gefunden --> Level 2
                    level = pdfa2;
                }
            }
        } catch (Throwable e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                    + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        }
    }
    getMessageService().logError(getTextResourceService().getText(MESSAGE_PDFAVALIDATION_VL, level));

    // Start mit der Erkennung

    // Eine PDF Datei (.pdf / .pdfa) muss mit %PDF [25504446] beginnen
    if (valDatei.isDirectory()) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                + getTextResourceService().getText(ERROR_XML_A_PDFA_ISDIRECTORY));
        return false;
    } else if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".pdf")
            || valDatei.getAbsolutePath().toLowerCase().endsWith(".pdfa"))) {

        FileReader fr = null;

        try {
            fr = new FileReader(valDatei);
            BufferedReader read = new BufferedReader(fr);

            // Hex 25 in Char umwandeln
            String str1 = "25";
            int i1 = Integer.parseInt(str1, 16);
            char c1 = (char) i1;
            // Hex 50 in Char umwandeln
            String str2 = "50";
            int i2 = Integer.parseInt(str2, 16);
            char c2 = (char) i2;
            // Hex 44 in Char umwandeln
            String str3 = "44";
            int i3 = Integer.parseInt(str3, 16);
            char c3 = (char) i3;
            // Hex 46 in Char umwandeln
            String str4 = "46";
            int i4 = Integer.parseInt(str4, 16);
            char c4 = (char) i4;

            // auslesen der ersten 4 Zeichen der Datei
            int length;
            int i;
            char[] buffer = new char[4];
            length = read.read(buffer);
            for (i = 0; i != length; i++)
                ;

            // die beiden charArrays (soll und ist) mit einander vergleichen IST = c1c2c3c4
            char[] charArray1 = buffer;
            char[] charArray2 = new char[] { c1, c2, c3, c4 };

            if (Arrays.equals(charArray1, charArray2)) {
                // hchstwahrscheinlich ein PDF da es mit 25504446 respektive %PDF beginnt
                valid = true;
            } else {
                // Droid-Erkennung, damit Details ausgegeben werden knnen
                String nameOfSignature = getConfigurationService().getPathToDroidSignatureFile();
                if (nameOfSignature == null) {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                            + getTextResourceService().getText(MESSAGE_XML_CONFIGURATION_ERROR_NO_SIGNATURE));
                    return false;
                }
                // existiert die SignatureFile am angebenen Ort?
                File fnameOfSignature = new File(nameOfSignature);
                if (!fnameOfSignature.exists()) {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                            + getTextResourceService().getText(MESSAGE_XML_CA_DROID));
                    return false;
                }

                Droid droid = null;
                try {
                    /* kleiner Hack, weil die Droid libraries irgendwo ein System.out drin haben, welche den
                     * Output stren Util.switchOffConsole() als Kommentar markieren wenn man die
                     * Fehlermeldung erhalten mchte */
                    Util.switchOffConsole();
                    droid = new Droid();

                    droid.readSignatureFile(nameOfSignature);

                } catch (Exception e) {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                            + getTextResourceService().getText(ERROR_XML_CANNOT_INITIALIZE_DROID));
                    return false;
                } finally {
                    Util.switchOnConsole();
                }
                File file = valDatei;
                String puid = "";
                IdentificationFile ifile = droid.identify(file.getAbsolutePath());
                for (int x = 0; x < ifile.getNumHits(); x++) {
                    FileFormatHit ffh = ifile.getHit(x);
                    FileFormat ff = ffh.getFileFormat();
                    puid = ff.getPUID();
                }
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                        + getTextResourceService().getText(ERROR_XML_A_PDFA_INCORRECTFILE, puid));
                return false;
            }
        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                    + getTextResourceService().getText(ERROR_XML_A_PDFA_INCORRECTFILE));
            return false;
        }
    } else {
        // die Datei endet nicht mit pdf oder pdfa -> Fehler
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                + getTextResourceService().getText(ERROR_XML_A_PDFA_INCORRECTFILEENDING));
        return false;
    }
    // Ende der Erkennung

    boolean isValid = false;
    boolean dual = false;

    // Initialisierung PDFTron -> berprfen der Angaben: existiert die PdftronExe am angebenen Ort?
    String pathToPdftronExe = getConfigurationService().getPathToPdftronExe();
    String producerFirstValidator = getConfigurationService().firstValidator();
    String dualValidation = getConfigurationService().dualValidation();

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

    if (dualValidation.contentEquals("dual")) {
        // Duale Validierung gewnscht
        dual = true;
    }
    if (!producerFirstValidator.contentEquals("PDFTron")) {
        // nicht der Validator von PDFTron --> PDFTools wird verwendet
        producerFirstValidator = "PDFTools";
    }

    File fPdftronExe = new File(pathToPdftronExe);
    if (!fPdftronExe.exists() || !fPdftronExe.getName().equals("pdfa.exe")) {
        // Keine Duale Validierung mglich
        if (dualValidation.contentEquals("dual") || producerFirstValidator.contentEquals("PDFTron")) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                    + getTextResourceService().getText(ERROR_XML_PDFTRON_MISSING));
            dual = false;
            producerFirstValidator = "PDFTools";
        }
    }

    pathToPdftronExe = "\"" + pathToPdftronExe + "\"";

    String pdfTools = "";
    String pdfTron = "";
    String newPdfDiaTxt = "";

    try {
        int iCategory = 999999999;
        // Create object
        PdfValidatorAPI docPdf = new PdfValidatorAPI();

        // TODO: Erledigt Start mit PDFTron
        if (producerFirstValidator.contentEquals("PDFTron")) {
            // zuerst mit PDFTron und danach ggf mit PDFTools
            File report;
            Document doc = null;

            try {

                // Pfad zum Programm Pdftron
                File pdftronExe = new File(pathToPdftronExe);
                File output = directoryOfLogfile;
                String pathToPdftronOutput = output.getAbsolutePath();
                StringBuffer command = new StringBuffer(pdftronExe + " ");
                command.append("-l " + level);
                command.append(" -o ");
                command.append("\"");
                command.append(output.getAbsolutePath());
                command.append("\"");
                command.append(" ");
                command.append("\"");
                command.append(valDatei.getAbsolutePath());
                command.append("\"");

                Process proc = null;
                Runtime rt = null;

                try {
                    /* Der Name des generierten Reports lautet per default report.xml und es scheint keine
                     * Mglichkeit zu geben, dies zu bersteuern. */
                    report = new File(pathToPdftronOutput, "report.xml");

                    // falls das File bereits existiert, z.B. von einem vorhergehenden Durchlauf, lschen
                    // wir es
                    if (report.exists()) {
                        report.delete();
                    }

                    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_A_PDFA)
                            + getTextResourceService().getText(ERROR_XML_A_PDFA_SERVICEFAILED, e.getMessage()));
                    return false;
                } finally {
                    if (proc != null) {
                        closeQuietly(proc.getOutputStream());
                        closeQuietly(proc.getInputStream());
                        closeQuietly(proc.getErrorStream());
                    }
                }
                // Ende PDFTRON direkt auszulsen

                String pathToPdftronReport = report.getAbsolutePath();
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pathToPdftronReport));
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                doc = db.parse(bis);
                doc.normalize();

                Integer passCount = new Integer(0);
                NodeList nodeLstI = doc.getElementsByTagName("Pass");

                // Valide pdfa-Dokumente enthalten "<Validation> <Pass FileName..." Anzahl pass = anzahl
                // Valider pdfa
                for (int s = 0; s < nodeLstI.getLength(); s++) {
                    passCount = passCount + 1;
                    // Valide PDFA-Datei Module A-J sind Valid
                    isValid = true;
                }

                if (passCount == 0) {
                    if (dual) {
                        // Duale Validierung mit PDFTools

                        if (docPdf.open(valDatei.getAbsolutePath(), "", NativeLibrary.COMPLIANCE.ePDFUnk)) {
                            // PDF Konnte geffnet werden
                            docPdf.setStopOnError(true);
                            docPdf.setReportingLevel(1);
                        } else {
                            docPdf.setStopOnError(true);
                            docPdf.setReportingLevel(1);
                            if (docPdf.getErrorCode() == NativeLibrary.ERRORCODE.PDF_E_PASSWORD) {
                                getMessageService().logError(getTextResourceService()
                                        .getText(MESSAGE_XML_MODUL_A_PDFA)
                                        + getTextResourceService().getText(ERROR_XML_A_PDFTOOLS_ENCRYPTED));
                                return false;
                            } else {
                                getMessageService().logError(getTextResourceService()
                                        .getText(MESSAGE_XML_MODUL_A_PDFA)
                                        + getTextResourceService().getText(ERROR_XML_A_PDFTOOLS_DAMAGED));
                                return false;
                            }
                        }

                        /* ePDFA1a 5122 ePDFA1b 5121 ePDFA2a 5891 ePDFA2b 5889 ePDFA2u 5890 */
                        if (level.contentEquals("1A")) {
                            if (docPdf.open(valDatei.getAbsolutePath(), "", 5122)) {
                                docPdf.validate();
                            }
                        } else if (level.contentEquals("1B")) {
                            if (docPdf.open(valDatei.getAbsolutePath(), "", 5121)) {
                                docPdf.validate();
                            }
                        } else if (level.contentEquals("2A")) {
                            if (docPdf.open(valDatei.getAbsolutePath(), "", 5891)) {
                                docPdf.validate();
                            }
                        } else if (level.contentEquals("2B")) {
                            if (docPdf.open(valDatei.getAbsolutePath(), "", 5889)) {
                                docPdf.validate();
                            }
                        } else if (level.contentEquals("2U")) {
                            if (docPdf.open(valDatei.getAbsolutePath(), "", 5890)) {
                                docPdf.validate();
                            }
                        } else {
                            // Validierung nach 2b
                            level = "2B";
                            if (docPdf.open(valDatei.getAbsolutePath(), "", 5889)) {
                                docPdf.validate();
                            }
                        }

                        // Error Category
                        iCategory = docPdf.getCategories();
                        /* die Zahl kann auch eine Summe von Kategorien sein z.B. 6144=2048+4096 ->
                         * getCategoryText gibt nur die erste Kategorie heraus (z.B. 2048) */

                        int success = 0;

                        /* ErrorCode kann ungleich Null sein, wenn es nur eine Information zu einer nicht
                         * einhaltung einer Empfehlung gefunden wurde.
                         * 
                         * Entsprechend wird der ErrorCode ignoriert. */

                        PdfError err = docPdf.getFirstError();
                        PdfError err1 = docPdf.getFirstError();

                        @SuppressWarnings("unused")
                        int iError = 0;
                        while (err != null) {
                            iError = err1.getErrorCode();
                            success = success + 1;
                            // Get next error
                            err = docPdf.getNextError();
                        }

                        if (success == 0 && iCategory == 0) {
                            // valide
                            isValid = true;

                            // Diskrepanz => PDF-Diagnosedaten ErrorCodes von PDFTron holen
                            NodeList nodeLst = doc.getElementsByTagName("Error");
                            String errorCodes = "";
                            for (int s = 0; s < nodeLst.getLength(); s++) {
                                Node dateiNode = nodeLst.item(s);
                                NamedNodeMap nodeMap = dateiNode.getAttributes();
                                Node errorNode = nodeMap.getNamedItem("Code");
                                String errorCode = errorNode.getNodeValue();
                                errorCodes = errorCodes + "  " + errorCode;
                            }

                            pdfTools = "<PDFTools><iCategory>0</iCategory><iError>0</iError></PDFTools>";
                            pdfTron = "<PDFTron><Code>" + errorCodes + "</Code></PDFTron>";
                            newPdfDiaTxt = "<Validation><ValFile>" + valDatei.getAbsolutePath()
                                    + "</ValFile><PdfaVL>" + level + "</PdfaVL>" + pdfTools + pdfTron
                                    + "</Validation>\n" + getTextResourceService().getText(MESSAGE_XML_DIAEND);
                            Util.pdfDia(newPdfDiaTxt, pdfDia);
                            Util.amp(pdfDia);

                        } else {
                            // invalid
                            isValid = false;
                        }
                    } else {
                        // keine duale Validierung -> invalid
                        isValid = false;
                    }
                }

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            }
        } else {
            // TODO: Erledigt Start mit PDFTools
            // zuerst mit PDFTools und danach ggf mit PDFTron

            if (docPdf.open(valDatei.getAbsolutePath(), "", NativeLibrary.COMPLIANCE.ePDFUnk)) {
                // PDF Konnte geffnet werden
            } else {
                if (docPdf.getErrorCode() == NativeLibrary.ERRORCODE.PDF_E_PASSWORD) {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                            + getTextResourceService().getText(ERROR_XML_A_PDFTOOLS_ENCRYPTED));
                    return false;
                } else {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                            + getTextResourceService().getText(ERROR_XML_A_PDFTOOLS_DAMAGED));
                    return false;
                }
            }

            /* ePDFA1a 5122 ePDFA1b 5121 ePDFA2a 5891 ePDFA2b 5889 ePDFA2u 5890 */
            if (level.contentEquals("1A")) {
                if (docPdf.open(valDatei.getAbsolutePath(), "", 5122)) {
                    docPdf.validate();
                }
            } else if (level.contentEquals("1B")) {
                if (docPdf.open(valDatei.getAbsolutePath(), "", 5121)) {
                    docPdf.validate();
                }
            } else if (level.contentEquals("2A")) {
                if (docPdf.open(valDatei.getAbsolutePath(), "", 5891)) {
                    docPdf.validate();
                }
            } else if (level.contentEquals("2B")) {
                if (docPdf.open(valDatei.getAbsolutePath(), "", 5889)) {
                    docPdf.validate();
                }
            } else if (level.contentEquals("2U")) {
                if (docPdf.open(valDatei.getAbsolutePath(), "", 5890)) {
                    docPdf.validate();
                }
            } else {
                // Validierung nach 2b
                level = "2B";
                if (docPdf.open(valDatei.getAbsolutePath(), "", 5889)) {
                    docPdf.validate();
                }
            }

            docPdf.setStopOnError(false);
            docPdf.setReportingLevel(2);

            // Error Category
            iCategory = docPdf.getCategories();
            /* die Zahl kann auch eine Summe von Kategorien sein z.B. 6144=2048+4096 -> getCategoryText
             * gibt nur die erste Kategorie heraus (z.B. 2048) */

            int success = 0;

            PdfError err = docPdf.getFirstError();
            PdfError err1 = docPdf.getFirstError();

            int iError = 0;
            while (err != null) {
                iError = err1.getErrorCode();
                success = success + 1;
                // Get next error
                err = docPdf.getNextError();
            }

            if (success == 0 && iCategory == 0) {
                // valide
                isValid = true;
            } else {
                if (dual) {
                    // duale Validierung
                    File report;
                    Document doc = null;

                    try {
                        // Pfad zum Programm Pdftron
                        File pdftronExe = new File(pathToPdftronExe);
                        File output = directoryOfLogfile;
                        String pathToPdftronOutput = output.getAbsolutePath();
                        StringBuffer command = new StringBuffer(pdftronExe + " ");
                        command.append("-l " + level);
                        command.append(" -o ");
                        command.append("\"");
                        command.append(output.getAbsolutePath());
                        command.append("\"");
                        command.append(" ");
                        command.append("\"");
                        command.append(valDatei.getAbsolutePath());
                        command.append("\"");

                        Process proc = null;
                        Runtime rt = null;

                        try {
                            /* Der Name des generierten Reports lautet per default report.xml und es scheint
                             * keine Mglichkeit zu geben, dies zu bersteuern. */
                            report = new File(pathToPdftronOutput, "report.xml");

                            // falls das File bereits existiert, z.B. von einemvorhergehenden Durchlauf, lschen
                            // wir es
                            if (report.exists()) {
                                report.delete();
                            }

                            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_A_PDFA)
                                            + getTextResourceService().getText(ERROR_XML_A_PDFA_SERVICEFAILED,
                                                    e.getMessage()));
                            return false;
                        } finally {
                            if (proc != null) {
                                closeQuietly(proc.getOutputStream());
                                closeQuietly(proc.getInputStream());
                                closeQuietly(proc.getErrorStream());
                            }
                        }
                        // Ende PDFTRON direkt auszulsen

                        String pathToPdftronReport = report.getAbsolutePath();
                        BufferedInputStream bis = new BufferedInputStream(
                                new FileInputStream(pathToPdftronReport));
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        doc = db.parse(bis);
                        doc.normalize();

                        Integer passCount = new Integer(0);
                        NodeList nodeLstI = doc.getElementsByTagName("Pass");

                        // Valide pdfa-Dokumente enthalten "<Validation> <Pass FileName..." Anzahl pass =
                        // anzahl Valider pdfa
                        for (int s = 0; s < nodeLstI.getLength(); s++) {
                            passCount = passCount + 1;
                            // Valide PDFA-Datei Module A-J sind Valid
                            isValid = true;

                            // Diskrepanz => PDF-Diagnosedaten
                            pdfTools = "<PDFTools><iCategory>" + iCategory + "</iCategory><iError>" + iError
                                    + "</iError></PDFTools>";
                            pdfTron = "<PDFTron><Code>Pass</Code></PDFTron>";
                            newPdfDiaTxt = "<Validation><ValFile>" + valDatei.getAbsolutePath()
                                    + "</ValFile><PdfaVL>" + level + "</PdfaVL>" + pdfTools + pdfTron
                                    + "</Validation>\n" + getTextResourceService().getText(MESSAGE_XML_DIAEND);
                            Util.pdfDia(newPdfDiaTxt, pdfDia);
                            Util.amp(pdfDia);

                        }
                        if (passCount == 0) {
                            // Invalide PDFA-Datei (doppelt besttigt)
                            isValid = false;
                        }

                    } catch (Exception e) {
                        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                                + getTextResourceService().getText(ERROR_XML_A_PDFA_SERVICEFAILED,
                                        e.getMessage()));
                        return false;
                    }
                } else {
                    // keine duale Validierung -> invalid
                    isValid = false;
                }
            }
        }

        // TODO: Erledigt: Fehler Auswertung

        if (!isValid) {
            // Invalide PDFA-Datei

            boolean exponent0 = false;
            boolean exponent1 = false;
            boolean exponent2 = false;
            boolean exponent3 = false;
            boolean exponent4 = false;
            boolean exponent5 = false;
            boolean exponent6 = false;
            boolean exponent7 = false;
            boolean exponent8 = false;
            boolean exponent9 = false;
            boolean exponent10 = false;
            boolean exponent11 = false;
            boolean exponent12 = false;
            boolean exponent13 = false;
            boolean exponent14 = false;
            boolean exponent15 = false;
            boolean exponent16 = false;
            boolean exponent17 = false;
            boolean exponent18 = false;

            int iExp0 = (int) Math.pow(2, 0);
            int iExp1 = (int) Math.pow(2, 1);
            int iExp2 = (int) Math.pow(2, 2);
            int iExp3 = (int) Math.pow(2, 3);
            int iExp4 = (int) Math.pow(2, 4);
            int iExp5 = (int) Math.pow(2, 5);
            int iExp6 = (int) Math.pow(2, 6);
            int iExp7 = (int) Math.pow(2, 7);
            int iExp8 = (int) Math.pow(2, 8);
            int iExp9 = (int) Math.pow(2, 9);
            int iExp10 = (int) Math.pow(2, 10);
            int iExp11 = (int) Math.pow(2, 11);
            int iExp12 = (int) Math.pow(2, 12);
            int iExp13 = (int) Math.pow(2, 13);
            int iExp14 = (int) Math.pow(2, 14);
            int iExp15 = (int) Math.pow(2, 15);
            int iExp16 = (int) Math.pow(2, 16);
            int iExp17 = (int) Math.pow(2, 17);
            int iExp18 = (int) Math.pow(2, 18);

            if (producerFirstValidator.contentEquals("PDFTools") || dual) {
                // Invalide Kategorien von PDF-Tools
                if (iCategory >= iExp18) {
                    exponent18 = true;
                    iCategory = iCategory - iExp18;
                }
                if (iCategory >= iExp17) {
                    exponent17 = true;
                    iCategory = iCategory - iExp17;
                }
                if (iCategory >= iExp16) {
                    exponent16 = true;
                    iCategory = iCategory - iExp16;
                }
                if (iCategory >= iExp15) {
                    exponent15 = true;
                    iCategory = iCategory - iExp15;
                }
                if (iCategory >= iExp14) {
                    exponent14 = true;
                    iCategory = iCategory - iExp14;
                }
                if (iCategory >= iExp13) {
                    exponent13 = true;
                    iCategory = iCategory - iExp13;
                }
                if (iCategory >= iExp12) {
                    exponent12 = true;
                    iCategory = iCategory - iExp12;
                }
                if (iCategory >= iExp11) {
                    exponent11 = true;
                    iCategory = iCategory - iExp11;
                }
                if (iCategory >= iExp10) {
                    exponent10 = true;
                    iCategory = iCategory - iExp10;
                }
                if (iCategory >= iExp9) {
                    exponent9 = true;
                    iCategory = iCategory - iExp9;
                }
                if (iCategory >= iExp8) {
                    exponent8 = true;
                    iCategory = iCategory - iExp8;
                }
                if (iCategory >= iExp7) {
                    exponent7 = true;
                    iCategory = iCategory - iExp7;
                }
                if (iCategory >= iExp6) {
                    exponent6 = true;
                    iCategory = iCategory - iExp6;
                }
                if (iCategory >= iExp5) {
                    exponent5 = true;
                    iCategory = iCategory - iExp5;
                }
                if (iCategory >= iExp4) {
                    exponent4 = true;
                    iCategory = iCategory - iExp4;
                }
                if (iCategory >= iExp3) {
                    exponent3 = true;
                    iCategory = iCategory - iExp3;
                }
                if (iCategory >= iExp2) {
                    exponent2 = true;
                    iCategory = iCategory - iExp2;
                }
                if (iCategory >= iExp1) {
                    exponent1 = true;
                    iCategory = iCategory - iExp1;
                }
                if (iCategory >= iExp0) {
                    exponent0 = true;
                    iCategory = iCategory - iExp0;
                }
            } else {
                iCategory = 0;
            }

            File report = new File(directoryOfLogfile.getAbsolutePath(), "report.xml");
            Document doc = null;

            if (producerFirstValidator.contentEquals("PDFTron") || dual) {
                // aus dem Output von Pdftron die Fehlercodes extrahieren und bersetzen

                String pathToPdftronReport = report.getAbsolutePath();
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pathToPdftronReport));
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                doc = db.parse(bis);
                doc.normalize();

                // Bsp. fr einen Error Code: <Error Code="e_PDFA173" die erste Ziffer nach e_PDFA ist der
                // Error Code.
            }
            /** Modul A **/
            if (exponent1) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_1, "iCategory_1"));
            }
            if (exponent2) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_2, "iCategory_2"));
            }
            if (producerFirstValidator.contentEquals("PDFTron") || dual) {
                // aus dem Output von Pdftron die Fehlercodes extrahieren und bersetzen

                String errorDigitA = "Fehler";

                NodeList nodeLst = doc.getElementsByTagName("Error");
                /* Bsp. fr einen Error Code: <Error Code="e_PDFA173" die erste Ziffer nach e_PDFA ist der
                 * Error Code. */
                for (int s = 0; s < nodeLst.getLength(); s++) {
                    Node dateiNode = nodeLst.item(s);
                    NamedNodeMap nodeMap = dateiNode.getAttributes();
                    Node errorNode = nodeMap.getNamedItem("Code");
                    String errorCode = errorNode.getNodeValue();
                    String errorCodeMsg = "error.xml.ai." + errorCode.substring(2);
                    Node errorNodeM = nodeMap.getNamedItem("Message");
                    String errorMessage = errorNodeM.getNodeValue();
                    errorDigitA = errorCode.substring(6, 7);

                    // der Error Code kann auch "Unknown" sein, dieser wird in den Code "0" bersetzt
                    if (errorDigitA.equals("U")) {
                        errorDigitA = "0";
                    }
                    if (errorDigitA.equals("n")) {
                        errorDigitA = "0";
                    }
                    try {
                        if (errorDigitA.equals("0")) {

                            // Allgemeiner Fehler -> A
                            isValid = false;
                            getMessageService()
                                    .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                                            + getTextResourceService().getText(errorCodeMsg, errorCode));
                        }
                    } catch (Exception e) {
                        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                                + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode,
                                        errorMessage));
                    }
                }
                if (errorDigitA.equals("Fehler")) {
                    // Fehler bei der Initialisierung Passierte bei einem Leerschlag im Namen
                    isValid = false;
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA)
                            + getTextResourceService().getText(ERROR_XML_A_PDFA_INIT));
                    return false;
                }
            }

            /** Modul B **/
            if (exponent0) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_0, "iCategory_0"));
            }
            if (exponent7) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_7, "iCategory_7"));
            }
            if (exponent18) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_18, "iCategory_18"));
            }
            if (producerFirstValidator.contentEquals("PDFTron") || dual) {
                // Analog Modul A
                NodeList nodeLst = doc.getElementsByTagName("Error");
                for (int s = 0; s < nodeLst.getLength(); s++) {
                    Node dateiNode = nodeLst.item(s);
                    NamedNodeMap nodeMap = dateiNode.getAttributes();
                    Node errorNode = nodeMap.getNamedItem("Code");
                    String errorCode = errorNode.getNodeValue();
                    String errorCodeMsg = "error.xml.ai." + errorCode.substring(2);
                    Node errorNodeM = nodeMap.getNamedItem("Message");
                    String errorMessage = errorNodeM.getNodeValue();
                    String errorDigit = errorCode.substring(6, 7);
                    try {
                        if (errorDigit.equals("1")) {
                            // Struktur Fehler -> B
                            isValid = false;
                            getMessageService()
                                    .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_PDFA)
                                            + getTextResourceService().getText(errorCodeMsg, errorCode));
                        }
                    } catch (Exception e) {
                        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_PDFA)
                                + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode,
                                        errorMessage));
                    }
                }
            }

            /** Modul C **/
            if (exponent3) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_3, "iCategory_3"));
            }
            if (exponent4) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_4, "iCategory_4"));
            }
            if (exponent5) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_5, "iCategory_5"));
            }
            if (exponent6) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_6, "iCategory_6"));
            }
            if (producerFirstValidator.contentEquals("PDFTron") || dual) {
                // Analog Modul A
                NodeList nodeLst = doc.getElementsByTagName("Error");
                for (int s = 0; s < nodeLst.getLength(); s++) {
                    Node dateiNode = nodeLst.item(s);
                    NamedNodeMap nodeMap = dateiNode.getAttributes();
                    Node errorNode = nodeMap.getNamedItem("Code");
                    String errorCode = errorNode.getNodeValue();
                    String errorCodeMsg = "error.xml.ai." + errorCode.substring(2);
                    Node errorNodeM = nodeMap.getNamedItem("Message");
                    String errorMessage = errorNodeM.getNodeValue();
                    String errorDigit = errorCode.substring(6, 7);
                    try {
                        if (errorDigit.equals("2")) {
                            // Grafik Fehler -> C
                            isValid = false;
                            getMessageService()
                                    .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_PDFA)
                                            + getTextResourceService().getText(errorCodeMsg, errorCode));
                        }
                    } catch (Exception e) {
                        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_PDFA)
                                + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode,
                                        errorMessage));
                    }
                }
            }
            /** Modul D **/
            if (exponent8) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_8, "iCategory_8"));
            }
            if (exponent9) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_9, "iCategory_9"));
            }
            if (producerFirstValidator.contentEquals("PDFTron") || dual) {
                // Analog Modul A
                NodeList nodeLst = doc.getElementsByTagName("Error");
                for (int s = 0; s < nodeLst.getLength(); s++) {
                    Node dateiNode = nodeLst.item(s);
                    NamedNodeMap nodeMap = dateiNode.getAttributes();
                    Node errorNode = nodeMap.getNamedItem("Code");
                    String errorCode = errorNode.getNodeValue();
                    String errorCodeMsg = "error.xml.ai." + errorCode.substring(2);
                    Node errorNodeM = nodeMap.getNamedItem("Message");
                    String errorMessage = errorNodeM.getNodeValue();
                    String errorDigit = errorCode.substring(6, 7);
                    try {
                        if (errorDigit.equals("3")) {
                            // Schrift Fehler -> D
                            isValid = false;
                            getMessageService()
                                    .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_PDFA)
                                            + getTextResourceService().getText(errorCodeMsg, errorCode));
                        }
                    } catch (Exception e) {
                        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_PDFA)
                                + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode,
                                        errorMessage));
                    }
                }
            }
            /** Modul E **/
            if (exponent10) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_E_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_10, "iCategory_10"));
            }
            if (producerFirstValidator.contentEquals("PDFTron") || dual) {
                // Analog Modul A
                NodeList nodeLst = doc.getElementsByTagName("Error");
                for (int s = 0; s < nodeLst.getLength(); s++) {
                    Node dateiNode = nodeLst.item(s);
                    NamedNodeMap nodeMap = dateiNode.getAttributes();
                    Node errorNode = nodeMap.getNamedItem("Code");
                    String errorCode = errorNode.getNodeValue();
                    String errorCodeMsg = "error.xml.ai." + errorCode.substring(2);
                    Node errorNodeM = nodeMap.getNamedItem("Message");
                    String errorMessage = errorNodeM.getNodeValue();
                    String errorDigit = errorCode.substring(6, 7);
                    try {
                        if (errorDigit.equals("4")) {
                            // Transparenz Fehler -> E
                            isValid = false;
                            getMessageService()
                                    .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_E_PDFA)
                                            + getTextResourceService().getText(errorCodeMsg, errorCode));
                        }
                    } catch (Exception e) {
                        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_E_PDFA)
                                + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode,
                                        errorMessage));
                    }
                }
            }
            /** Modul F **/
            if (exponent11) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_11, "iCategory_11"));
            }
            if (exponent12) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_12, "iCategory_12"));
            }
            if (exponent13) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_13, "iCategory_13"));
            }
            if (exponent14) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_14, "iCategory_14"));
            }
            if (producerFirstValidator.contentEquals("PDFTron") || dual) {
                // Analog Modul A
                NodeList nodeLst = doc.getElementsByTagName("Error");
                for (int s = 0; s < nodeLst.getLength(); s++) {
                    Node dateiNode = nodeLst.item(s);
                    NamedNodeMap nodeMap = dateiNode.getAttributes();
                    Node errorNode = nodeMap.getNamedItem("Code");
                    String errorCode = errorNode.getNodeValue();
                    String errorCodeMsg = "error.xml.ai." + errorCode.substring(2);
                    Node errorNodeM = nodeMap.getNamedItem("Message");
                    String errorMessage = errorNodeM.getNodeValue();
                    String errorDigit = errorCode.substring(6, 7);
                    try {
                        if (errorDigit.equals("5")) {
                            // Annotations Fehler -> F
                            isValid = false;
                            getMessageService()
                                    .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_PDFA)
                                            + getTextResourceService().getText(errorCodeMsg, errorCode));
                        }
                    } catch (Exception e) {
                        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_PDFA)
                                + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode,
                                        errorMessage));
                    }
                }
            }
            /** Modul G **/
            if (exponent15) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_15, "iCategory_15"));
            }
            if (producerFirstValidator.contentEquals("PDFTron") || dual) {
                // Analog Modul A
                NodeList nodeLst = doc.getElementsByTagName("Error");
                for (int s = 0; s < nodeLst.getLength(); s++) {
                    Node dateiNode = nodeLst.item(s);
                    NamedNodeMap nodeMap = dateiNode.getAttributes();
                    Node errorNode = nodeMap.getNamedItem("Code");
                    String errorCode = errorNode.getNodeValue();
                    String errorCodeMsg = "error.xml.ai." + errorCode.substring(2);
                    Node errorNodeM = nodeMap.getNamedItem("Message");
                    String errorMessage = errorNodeM.getNodeValue();
                    String errorDigit = errorCode.substring(6, 7);
                    try {
                        if (errorDigit.equals("6")) {
                            // Aktions Fehler -> G
                            isValid = false;
                            getMessageService()
                                    .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_PDFA)
                                            + getTextResourceService().getText(errorCodeMsg, errorCode));
                        }
                        // neu sind die Interaktionen (J) bei den Aktionen (G)
                        if (errorDigit.equals("9")) {
                            // Interaktions Fehler -> J
                            isValid = false;
                            getMessageService()
                                    .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_PDFA)
                                            + getTextResourceService().getText(errorCodeMsg, errorCode));
                        }
                    } catch (Exception e) {
                        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_PDFA)
                                + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode,
                                        errorMessage));
                    }
                }
            }
            /** Modul H **/
            if (exponent16) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_16, "iCategory_16"));
            }
            if (producerFirstValidator.contentEquals("PDFTron") || dual) {
                // Analog Modul A
                NodeList nodeLst = doc.getElementsByTagName("Error");
                for (int s = 0; s < nodeLst.getLength(); s++) {
                    Node dateiNode = nodeLst.item(s);
                    NamedNodeMap nodeMap = dateiNode.getAttributes();
                    Node errorNode = nodeMap.getNamedItem("Code");
                    String errorCode = errorNode.getNodeValue();
                    String errorCodeMsg = "error.xml.ai." + errorCode.substring(2);
                    Node errorNodeM = nodeMap.getNamedItem("Message");
                    String errorMessage = errorNodeM.getNodeValue();
                    String errorDigit = errorCode.substring(6, 7);
                    try {
                        if (errorDigit.equals("7")) {
                            // Metadaten Fehler -> H
                            isValid = false;
                            getMessageService()
                                    .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_PDFA)
                                            + getTextResourceService().getText(errorCodeMsg, errorCode));
                        }
                    } catch (Exception e) {
                        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_PDFA)
                                + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode,
                                        errorMessage));
                    }
                }
            }
            /** Modul I **/
            if (exponent17) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_I_PDFA)
                        + getTextResourceService().getText(ERROR_XML_AI_17, "iCategory_17"));
            }
            if (producerFirstValidator.contentEquals("PDFTron") || dual) {
                // Analog Modul A
                NodeList nodeLst = doc.getElementsByTagName("Error");
                for (int s = 0; s < nodeLst.getLength(); s++) {
                    Node dateiNode = nodeLst.item(s);
                    NamedNodeMap nodeMap = dateiNode.getAttributes();
                    Node errorNode = nodeMap.getNamedItem("Code");
                    String errorCode = errorNode.getNodeValue();
                    String errorCodeMsg = "error.xml.ai." + errorCode.substring(2);
                    Node errorNodeM = nodeMap.getNamedItem("Message");
                    String errorMessage = errorNodeM.getNodeValue();
                    String errorDigit = errorCode.substring(6, 7);
                    try {
                        if (errorDigit.equals("8")) {
                            // Zugnglichkeit Fehler -> I
                            isValid = false;
                            getMessageService()
                                    .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_I_PDFA)
                                            + getTextResourceService().getText(errorCodeMsg, errorCode));
                        }
                    } catch (Exception e) {
                        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_I_PDFA)
                                + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode,
                                        errorMessage));
                    }
                }
            }
            /** Modul J **/
            // neu sind die Interaktionen (J) bei den Aktionen (G)

            docPdf.close();

            // Destroy the object
            docPdf.destroyObject();

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

From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java

protected void init(Document config) {
    this.groups = new HashMap();
    this.contexts = new SmartCache(120);
    config.normalize();
    int refreshminutes = 120;
    Element root = config.getDocumentElement();
    NodeList nl = root.getElementsByTagName("config");
    if (nl.getLength() == 1) {
        Element conf = (Element) nl.item(0);
        Node cc = conf.getFirstChild();
        //NodeList cl= conf.getF.getChildNodes();
        //for(int i=0; i<cl.getLength(); i++){
        while (cc != null) {
            if (cc.getNodeType() == ELEMENT_NODE) {
                Element c = (Element) cc;
                c.normalize();/*from   ww w.j a  v a2s.  co m*/
                Node t = c.getFirstChild();
                if (t != null && t.getNodeType() == Node.TEXT_NODE) {
                    String name = c.getNodeName();
                    String text = ((Text) t).getData();
                    //System.out.println(name+" = "+text);
                    if (name.equals("url")) {
                        url = text;
                    } else if (name.equals("logonid")) {
                        logonid = text;
                    } else if (name.equals("logonpassword")) {
                        logonpassword = text;
                    } else if (name.equals("keyfield")) {
                        keyfield = text;
                    } else if (name.equals("namefield")) {
                        namefield = text;
                    } else if (name.equals("usercontext")) {
                        usercontext = text;
                    } else if (name.equals("refresh-minutes")) {
                        try {
                            refreshminutes = Integer.parseInt(text);
                        } catch (Exception e) {
                        }
                    }
                }
            }
            cc = cc.getNextSibling();
        }
    } else {
        throw new RuntimeException("LDAPGroupStore: config file must contain one config element");
    }

    this.personkeys = new SmartCache(refreshminutes * 60);

    NodeList gl = root.getChildNodes();
    for (int j = 0; j < gl.getLength(); j++) {
        if (gl.item(j).getNodeType() == ELEMENT_NODE) {
            Element g = (Element) gl.item(j);
            if (g.getNodeName().equals("group")) {
                GroupShadow shadow = processXmlGroupRecursive(g);
                groups.put(shadow.key, shadow);
            }
        }
    }

}

From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java

@Override
@SuppressWarnings("unchecked")
@Transactional//from   ww  w . j av a2s  .  c  o  m
public void importLayout(org.dom4j.Element layout) {
    if (layout.getNamespaceForPrefix("dlm") == null) {
        layout.add(new Namespace("dlm", Constants.NS_URI));
    }

    //Remove comments from the DOM they break import
    final List<org.dom4j.Node> comments = layout.selectNodes("//comment()");
    for (final org.dom4j.Node comment : comments) {
        comment.detach();
    }

    //Get a ref to the prefs element and then remove it from the layout
    final org.dom4j.Node preferencesElement = layout.selectSingleNode("preferences");
    if (preferencesElement != null) {
        preferencesElement.getParent().remove(preferencesElement);
    }

    final String ownerUsername = layout.valueOf("@username");

    //Get a ref to the profile element and then remove it from the layout
    final org.dom4j.Node profileElement = layout.selectSingleNode("profile");
    if (profileElement != null) {
        profileElement.getParent().remove(profileElement);

        final org.dom4j.Document profileDocument = new org.dom4j.DocumentFactory().createDocument();
        profileDocument.setRootElement((org.dom4j.Element) profileElement);
        profileDocument.setName(ownerUsername + ".profile");

        final DocumentSource profileSource = new DocumentSource(profileElement);
        this.portalDataHandlerService.importData(profileSource);
    }

    final IPerson person = new PersonImpl();
    person.setUserName(ownerUsername);

    int ownerId;
    try {
        //Can't just pass true for create here, if the user actually exists the create flag also updates the user data
        ownerId = this.userIdentityStore.getPortalUID(person);
    } catch (final AuthorizationException t) {
        if (this.errorOnMissingUser) {
            throw new RuntimeException("Unrecognized user " + person.getUserName()
                    + "; you must import users before their layouts or set org.apereo.portal.io.layout.errorOnMissingUser to false.",
                    t);
        }

        //Create the missing user
        ownerId = this.userIdentityStore.getPortalUID(person, true);
    }

    if (ownerId == -1) {
        throw new RuntimeException("Unrecognized user " + person.getUserName()
                + "; you must import users before their layouts or set org.apereo.portal.io.layout.errorOnMissingUser to false.");
    }
    person.setID(ownerId);

    IUserProfile profile = null;
    try {
        person.setSecurityContext(new BrokenSecurityContext());
        profile = this.getUserProfileByFname(person, "default");
    } catch (final Throwable t) {
        throw new RuntimeException("Failed to load profile for " + person.getUserName()
                + "; This user must have a profile for import to continue.", t);
    }

    // (6) Add database Ids & (5) Add dlm:plfID ...
    int nextId = 1;
    for (final Iterator<org.dom4j.Element> it = (Iterator<org.dom4j.Element>) layout
            .selectNodes("folder | dlm:* | channel").iterator(); it.hasNext();) {
        nextId = this.addIdAttributesIfNecessary(it.next(), nextId);
    }
    // Now update UP_USER...
    this.jdbcOperations.update("UPDATE up_user SET next_struct_id = ? WHERE user_id = ?", nextId,
            person.getID());

    // (4) Convert external DLM pathrefs to internal form (noderefs)...
    for (final Iterator<org.dom4j.Attribute> itr = (Iterator<org.dom4j.Attribute>) layout
            .selectNodes("//@dlm:origin").iterator(); itr.hasNext();) {
        final org.dom4j.Attribute a = itr.next();
        final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, a.getValue(), null,
                true, layout);
        if (dlmNoderef != null) {
            // Change the value only if we have a valid pathref...
            a.setValue(dlmNoderef.toString());
            // For dlm:origin only, also use the noderef as the ID attribute...
            a.getParent().addAttribute("ID", dlmNoderef.toString());
        } else {
            // At least insure the value is between 1 and 35 characters
            a.setValue(BAD_PATHREF_MESSAGE);
        }
    }
    for (final Iterator<org.dom4j.Attribute> itr = (Iterator<org.dom4j.Attribute>) layout
            .selectNodes("//@dlm:target").iterator(); itr.hasNext();) {
        final org.dom4j.Attribute a = itr.next();
        final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, a.getValue(), null,
                true, layout);
        // Put in the correct value, or at least insure the value is between 1 and 35 characters
        a.setValue(dlmNoderef != null ? dlmNoderef.toString() : BAD_PATHREF_MESSAGE);
    }
    for (final Iterator<org.dom4j.Attribute> names = (Iterator<org.dom4j.Attribute>) layout
            .selectNodes("//dlm:*/@name").iterator(); names.hasNext();) {
        final org.dom4j.Attribute a = names.next();
        final String value = a.getValue().trim();
        if (!VALID_PATHREF_PATTERN.matcher(value).matches()) {
            /* Don't send it to getDlmNoderef if we know in advance it's not 
             * going to work;  saves annoying/misleading log messages and 
             * possibly some processing.  NOTE this is _only_ a problem with 
             * the name attribute of some dlm:* elements, which seems to go 
             * unused intentionally in some circumstances
             */
            continue;
        }
        final org.dom4j.Attribute fname = a.getParent().attribute("fname");
        Noderef dlmNoderef = null;
        if (fname != null) {
            dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, value, fname.getValue(),
                    false, layout);
            // Remove the fname attribute now that we're done w/ it...
            fname.getParent().remove(fname);
        } else {
            dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, value, null, true, layout);
        }
        // Put in the correct value, or at least insure the value is between 1 and 35 characters
        a.setValue(dlmNoderef != null ? dlmNoderef.toString() : BAD_PATHREF_MESSAGE);
    }

    // (3) Restore chanID attributes on <channel> elements...
    for (final Iterator<org.dom4j.Element> it = (Iterator<org.dom4j.Element>) layout.selectNodes("//channel")
            .iterator(); it.hasNext();) {
        final org.dom4j.Element c = it.next();
        final String fname = c.valueOf("@fname");
        final IPortletDefinition cd = this.portletDefinitionRegistry.getPortletDefinitionByFname(fname);
        if (cd == null) {
            final String msg = "No portlet with fname=" + fname + " exists referenced by node "
                    + c.valueOf("@ID") + " from layout for " + ownerUsername;
            if (errorOnMissingPortlet) {
                throw new IllegalArgumentException(msg);
            } else {
                logger.warn(msg);
                //Remove the bad channel node
                c.getParent().remove(c);
            }
        } else {
            c.addAttribute("chanID", String.valueOf(cd.getPortletDefinitionId().getStringId()));
        }
    }

    // (2) Restore locale info...
    // (This step doesn't appear to be needed for imports)

    // (1) Process structure & theme attributes...
    Document layoutDom = null;
    try {

        final int structureStylesheetId = profile.getStructureStylesheetId();
        this.loadStylesheetUserPreferencesAttributes(person, profile, layout, structureStylesheetId,
                "structure");

        final int themeStylesheetId = profile.getThemeStylesheetId();
        this.loadStylesheetUserPreferencesAttributes(person, profile, layout, themeStylesheetId, "theme");

        // From this point forward we need the user's PLF set as DLM expects it...
        for (final Iterator<org.dom4j.Text> it = (Iterator<org.dom4j.Text>) layout
                .selectNodes("descendant::text()").iterator(); it.hasNext();) {
            // How many years have we used Java & XML, and this still isn't easy?
            final org.dom4j.Text txt = it.next();
            if (txt.getText().trim().length() == 0) {
                txt.getParent().remove(txt);
            }
        }

        final org.dom4j.Element copy = layout.createCopy();
        final org.dom4j.Document doc = this.fac.createDocument(copy);
        doc.normalize();
        layoutDom = this.writer.get().write(doc);
        person.setAttribute(Constants.PLF, layoutDom);

    } catch (final Throwable t) {
        throw new RuntimeException("Unable to set UserPreferences for user:  " + person.getUserName(), t);
    }

    // Finally store the layout...
    try {
        this.setUserLayout(person, profile, layoutDom, true, true);
    } catch (final Throwable t) {
        final String msg = "Unable to persist layout for user:  " + ownerUsername;
        throw new RuntimeException(msg, t);
    }

    if (preferencesElement != null) {
        final int ownerUserId = this.userIdentityStore.getPortalUserId(ownerUsername);
        //TODO this assumes a single layout, when multi-layout support exists portlet entities will need to be re-worked to allow for a layout id to be associated with the entity

        //track which entities from the user's pre-existing set are touched (all non-touched entities will be removed)
        final Set<IPortletEntity> oldPortletEntities = new LinkedHashSet<IPortletEntity>(
                this.portletEntityDao.getPortletEntitiesForUser(ownerUserId));

        final List<org.dom4j.Element> entries = preferencesElement.selectNodes("entry");
        for (final org.dom4j.Element entry : entries) {
            final String dlmPathRef = entry.attributeValue("entity");
            final String fname = entry.attributeValue("channel");
            final String prefName = entry.attributeValue("name");

            final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(person.getUserName(),
                    dlmPathRef, fname, false, layout);

            if (dlmNoderef != null && fname != null) {
                final IPortletEntity portletEntity = this.getPortletEntity(fname, dlmNoderef.toString(),
                        ownerUserId);
                oldPortletEntities.remove(portletEntity);

                final List<IPortletPreference> portletPreferences = portletEntity.getPortletPreferences();

                final List<org.dom4j.Element> valueElements = entry.selectNodes("value");
                final List<String> values = new ArrayList<String>(valueElements.size());
                for (final org.dom4j.Element valueElement : valueElements) {
                    values.add(valueElement.getText());
                }

                portletPreferences.add(
                        new PortletPreferenceImpl(prefName, false, values.toArray(new String[values.size()])));

                this.portletEntityDao.updatePortletEntity(portletEntity);
            }
        }

        //Delete all portlet preferences for entities that were not imported
        for (final IPortletEntity portletEntity : oldPortletEntities) {
            portletEntity.setPortletPreferences(null);

            if (portletEntityRegistry.shouldBePersisted(portletEntity)) {
                this.portletEntityDao.updatePortletEntity(portletEntity);
            } else {
                this.portletEntityDao.deletePortletEntity(portletEntity);
            }
        }
    }
}