Example usage for java.io BufferedReader read

List of usage examples for java.io BufferedReader read

Introduction

In this page you can find the example usage for java.io BufferedReader read.

Prototype

public int read(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.por.PORFileReader.java

private void decodeSec2(BufferedReader reader) throws IOException {
    dbgLog.fine("***** decodeSec2(): start *****");
    if (reader == null) {
        throw new IllegalArgumentException("decodeSec2: stream == null!");
    }//  ww w .jav a2 s . c  o m

    // Because a 64-bit machine may not save the first 40
    // bytes of a POR file in a way as a 32-bit machine does,
    // the first 5 lines of a POR file is excluded from the read-back
    // file and the new 1st line contains the format mark "SPSSPORT"
    // somewhere in it.

    // mark the start position for the later rewind
    if (reader.markSupported()) {
        reader.mark(100000);
    }

    char[] sixthLineCharArray = new char[80];
    int nbytes_sixthLine = reader.read(sixthLineCharArray);

    String sixthLine = new String(sixthLineCharArray);
    dbgLog.info("sixthLineCharArray=" + Arrays.deepToString(ArrayUtils.toObject(sixthLineCharArray)));
    int signatureLocation = sixthLine.indexOf(POR_MARK);

    if (signatureLocation >= 0) {
        dbgLog.info("format signature was found at:" + signatureLocation);
    } else {
        dbgLog.severe("signature string was not found");
        throw new IOException("signature string was not found");
    }

    // rewind the position to the beginning
    reader.reset();

    // skip bytes up to the signature string
    long skippedBytes = reader.skip(signatureLocation);

    char[] sec2_leader = new char[POR_MARK.length()];
    int nbytes_sec2_leader = reader.read(sec2_leader);

    String leader_string = new String(sec2_leader);

    dbgLog.info("format signature [SPSSPORT] detected=" + leader_string);

    if (leader_string.equals("SPSSPORT")) {
        dbgLog.info("signature was correctly detected");

    } else {
        dbgLog.severe("the format signature is not found at the previously located column");
        throw new IOException("decodeSec2: failed to find the signature string");
    }

    int length_section_2 = LENGTH_SECTION_2;

    char[] Sec2_bytes = new char[length_section_2];

    int nbytes_sec2 = reader.read(Sec2_bytes);

    if (nbytes_sec2 == 0) {
        dbgLog.severe("decodeSec2: reading error");
        throw new IOException("decodeSec2: reading error");
    } else {
        dbgLog.fine("bytes read=" + nbytes_sec2);
    }

    String sec2 = new String(Sec2_bytes);
    dbgLog.fine("sec2[creation date/time]=" + sec2);

    // sec2
    //       0123456789012345678
    //       A8/YYYYMMDD6/HHMMSS
    // thus
    // section2 should has 3 elements

    String[] section2 = StringUtils.split(sec2, '/');

    dbgLog.fine("section2=" + StringUtils.join(section2, "|"));

    String fileCreationDate = null;
    String fileCreationTime = null;
    if ((section2.length == 3) && (section2[0].startsWith("A"))) {
        fileCreationDate = section2[1].substring(0, 7);
        fileCreationTime = section2[2];
    } else {
        dbgLog.severe("decodeSec2: file creation date/time were not correctly detected");
        throw new IOException("decodeSec2: file creation date/time were not correctly detected");
    }
    dbgLog.fine("fileCreationDate=" + fileCreationDate);
    dbgLog.fine("fileCreationTime=" + fileCreationTime);
    smd.getFileInformation().put("fileCreationDate", fileCreationDate);
    smd.getFileInformation().put("fileCreationTime", fileCreationTime);
    smd.getFileInformation().put("varFormat_schema", "SPSS");
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java

private void decodeSec2(BufferedReader reader) throws IOException {
    dbgLog.fine("decodeSec2(): start");
    if (reader == null) {
        throw new IllegalArgumentException("decodeSec2: stream == null!");
    }/*from   w ww.j a  v  a  2  s . c o m*/

    // Because a 64-bit machine may not save the first 40
    // bytes of a POR file in a way as a 32-bit machine does,
    // the first 5 lines of a POR file is excluded from the read-back
    // file and the new 1st line contains the format mark "SPSSPORT"
    // somewhere in it.

    // mark the start position for the later rewind
    if (reader.markSupported()) {
        reader.mark(100000);
    }

    char[] sixthLineCharArray = new char[80];
    int nbytes_sixthLine = reader.read(sixthLineCharArray);

    String sixthLine = new String(sixthLineCharArray);
    dbgLog.fine("sixthLineCharArray=" + Arrays.deepToString(ArrayUtils.toObject(sixthLineCharArray)));
    int signatureLocation = sixthLine.indexOf(POR_MARK);

    if (signatureLocation >= 0) {
        dbgLog.fine("format signature was found at:" + signatureLocation);
    } else {
        dbgLog.severe("signature string was not found");
        throw new IOException("signature string was not found");
    }

    // rewind the position to the beginning
    reader.reset();

    // skip bytes up to the signature string
    long skippedBytes = reader.skip(signatureLocation);

    char[] sec2_leader = new char[POR_MARK.length()];
    int nbytes_sec2_leader = reader.read(sec2_leader);

    String leader_string = new String(sec2_leader);

    dbgLog.fine("format signature [SPSSPORT] detected=" + leader_string);

    if (leader_string.equals("SPSSPORT")) {
        dbgLog.fine("signature was correctly detected");

    } else {
        dbgLog.severe("the format signature is not found at the previously located column");
        throw new IOException("decodeSec2: failed to find the signature string");
    }

    int length_section_2 = LENGTH_SECTION_2;

    char[] Sec2_bytes = new char[length_section_2];

    int nbytes_sec2 = reader.read(Sec2_bytes);

    if (nbytes_sec2 == 0) {
        dbgLog.severe("decodeSec2: reading error");
        throw new IOException("decodeSec2: reading error");
    } else {
        dbgLog.fine("bytes read=" + nbytes_sec2);
    }

    String sec2 = new String(Sec2_bytes);
    dbgLog.fine("sec2[creation date/time]=" + sec2);

    // sec2
    //       0123456789012345678
    //       A8/YYYYMMDD6/HHMMSS
    // thus
    // section2 should has 3 elements

    String[] section2 = StringUtils.split(sec2, '/');

    dbgLog.fine("section2=" + StringUtils.join(section2, "|"));

    String fileCreationDate = null;
    String fileCreationTime = null;
    if ((section2.length == 3) && (section2[0].startsWith("A"))) {
        fileCreationDate = section2[1].substring(0, 7);
        fileCreationTime = section2[2];
    } else {
        dbgLog.severe("decodeSec2: file creation date/time were not correctly detected");
        throw new IOException("decodeSec2: file creation date/time were not correctly detected");
    }
    dbgLog.fine("fileCreationDate=" + fileCreationDate);
    dbgLog.fine("fileCreationTime=" + fileCreationTime);
    ///smd.getFileInformation().put("fileCreationDate", fileCreationDate);
    ///smd.getFileInformation().put("fileCreationTime", fileCreationTime);
    ///smd.getFileInformation().put("varFormat_schema", "SPSS");
    dbgLog.fine("decodeSec2(): end");
}

From source file:cn.ctyun.amazonaws.services.s3.model.transform.XmlResponsesSaxParser.java

protected InputStream sanitizeXmlDocument(DefaultHandler handler, InputStream inputStream)
        throws AmazonClientException {
    if (!sanitizeXmlDocument) {
        // No sanitizing will be performed, return the original input stream unchanged.
        return inputStream;
    } else {/*w w w. ja  v a 2  s  .  c o m*/
        if (log.isDebugEnabled()) {
            log.debug("Sanitizing XML document destined for handler " + handler.getClass());
        }

        InputStream sanitizedInputStream = null;

        try {
            /*
             * Read object listing XML document from input stream provided into a
             * string buffer, so we can replace troublesome characters before
             * sending the document to the XML parser.
             */
            StringBuilder listingDocBuffer = new StringBuilder();
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(inputStream, Constants.DEFAULT_ENCODING));

            char[] buf = new char[8192];
            int read = -1;
            while ((read = br.read(buf)) != -1) {
                listingDocBuffer.append(buf, 0, read);
            }
            br.close();

            /*
             * Replace any carriage return (\r) characters with explicit XML
             * character entities, to prevent the SAX parser from
             * misinterpreting 0x0D characters as 0x0A and being unable to
             * parse the XML.
             */
            String listingDoc = listingDocBuffer.toString().replaceAll("\r", "
");

            sanitizedInputStream = new ByteArrayInputStream(listingDoc.getBytes(Constants.DEFAULT_ENCODING));
        } catch (Throwable t) {
            try {
                inputStream.close();
            } catch (IOException e) {
                if (log.isErrorEnabled()) {
                    log.error("Unable to close response InputStream after failure sanitizing XML document", e);
                }
            }
            throw new AmazonClientException(
                    "Failed to sanitize XML document destined for handler " + handler.getClass(), t);
        }
        return sanitizedInputStream;
    }
}

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;//from   w w w. j av a  2  s. 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:org.kaaproject.kaa.server.control.cli.ControlApiCommandProcessor.java

/**
 * Read input file and return file contents as string.
 *
 * @param file//  w ww.jav  a 2  s .c  om
 *            the input file to read
 * @param errorWriter
 *            the error writer to output read errors
 * @return the file contents string
 */
private String readFile(String file, PrintWriter errorWriter) {
    String result = null;

    File f = new File(file);
    if (f.exists() && f.isFile()) {
        try {
            StringBuffer fileData = new StringBuffer();
            BufferedReader reader = new BufferedReader(new FileReader(f));
            char[] buf = new char[1024];
            int numRead = 0;
            while ((numRead = reader.read(buf)) != -1) {
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
            }
            reader.close();
            result = fileData.toString();
        } catch (FileNotFoundException e) {
            LOG.error("Unable to locate specified file '{}'!", file);
        } catch (IOException e) {
            LOG.error("Unable to read from specified file '{}'! Error:  {}", file, e.getMessage());
            e.printStackTrace(errorWriter); //NOSONAR
        }
    } else if (!f.exists()) {
        errorWriter.println(SPECIFIED_FILE + file + "' does not exists!");
    } else if (!f.isFile()) {
        errorWriter.println(SPECIFIED_FILE + file + "' is not a file!");
    }
    return result;
}

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;// ww w .  j  a  v  a 2  s . c  om
    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:cgeo.geocaching.cgBase.java

private static void readIntoBuffer(BufferedReader br, StringBuffer buffer) throws IOException {
    int bufferSize = 1024 * 16;
    char[] bytes = new char[bufferSize];
    int bytesRead;
    while ((bytesRead = br.read(bytes)) > 0) {
        if (bytesRead == bufferSize) {
            buffer.append(bytes);/*from  w  w w.  ja va 2  s .  c  om*/
        } else {
            buffer.append(bytes, 0, bytesRead);
        }
    }
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java

private void decodeData(BufferedReader reader) throws IOException {
    dbgLog.fine("decodeData(): start");
    // TODO: get rid of this "variableTypeFinal"; -- L.A. 4.0 beta
    int[] variableTypeFinal = new int[varQnty];
    dateFormatList = new String[varQnty];

    // create a File object to save the tab-delimited data file
    File tabDelimitedDataFile = File.createTempFile("tempTabfile.", ".tab");
    ingesteddata.setTabDelimitedFile(tabDelimitedDataFile);

    FileOutputStream fileOutTab = null;
    PrintWriter pwout = null;//from  ww w .jav a  2s  .c  o  m

    try {
        fileOutTab = new FileOutputStream(tabDelimitedDataFile);
        pwout = new PrintWriter(new OutputStreamWriter(fileOutTab, "utf8"), true);

        variableFormatTypeList = new String[varQnty];
        for (int i = 0; i < varQnty; i++) {
            variableFormatTypeList[i] = SPSSConstants.FORMAT_CATEGORY_TABLE
                    .get(printFormatTable.get(variableNameList.get(i)));
            formatCategoryTable.put(variableNameList.get(i), variableFormatTypeList[i]);
        }

        // contents (variable) checker concering decimals
        Arrays.fill(variableTypeFinal, 0);

        // raw-case counter
        int j = 0; // case

        // use while instead for because the number of cases (observations) is usually unknown
        FBLOCK: while (true) {
            j++;

            // case(row)-wise storage object; to be updated after each row-reading

            String[] casewiseRecordForTabFile = new String[varQnty];
            // warning: the above object is later shallow-copied to the
            // data object for calculating a UNF value/summary statistics
            //

            for (int i = 0; i < varQnty; i++) {
                // check the type of this variable
                boolean isStringType = variableTypeTable.get(variableNameList.get(i)) > 0;

                if (isStringType) {
                    // String case
                    variableTypeFinal[i] = -1;

                    StringBuilder sb_StringLengthBase30 = new StringBuilder("");
                    int stringLengthBase10 = 0;
                    String buffer = "";
                    char[] tmp = new char[1];

                    int nint;
                    while ((nint = reader.read(tmp)) > 0) {
                        buffer = Character.toString(tmp[0]);
                        if (buffer.equals("/")) {
                            break;
                        } else if (buffer.equals("Z")) {
                            if (i == 0) {
                                // the reader has passed the last case; subtract 1 from the j counter
                                caseQnty = j - 1;
                                break FBLOCK;
                            }
                        } else {
                            sb_StringLengthBase30.append(buffer);
                        }

                    }

                    if (nint == 0) {
                        // no more data to be read (reached the eof)
                        caseQnty = j - 1;
                        break FBLOCK;
                    }

                    dbgLog.finer(
                            j + "-th case " + i + "=th var:datum length=" + sb_StringLengthBase30.toString());

                    // this length value should be a positive integer
                    Matcher mtr = pattern4positiveInteger.matcher(sb_StringLengthBase30.toString());
                    if (mtr.matches()) {
                        stringLengthBase10 = Integer.valueOf(sb_StringLengthBase30.toString(), 30);
                    } else {
                        // reading error case
                        throw new IOException("reading F(data) section: string: length is not integer");
                    }

                    // read this string-variable's contents after "/"
                    char[] char_datumString = new char[stringLengthBase10];
                    reader.read(char_datumString);

                    String datum = new String(char_datumString);
                    casewiseRecordForTabFile[i] = "\""
                            + datum.replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"";
                    // end of string case
                } else {

                    // numeric case
                    StringBuilder sb_datumNumericBase30 = new StringBuilder("");
                    boolean isMissingValue = false;
                    String datum = null;
                    String datumForTabFile = null;
                    String datumDateFormat = null;

                    String buffer = "";
                    char[] tmp = new char[1];
                    int nint;
                    while ((nint = reader.read(tmp)) > 0) {
                        sb_datumNumericBase30.append(buffer);
                        buffer = Character.toString(tmp[0]);

                        if (buffer.equals("/")) {
                            break;
                        } else if (buffer.equals("Z")) {
                            if (i == 0) {
                                // the reader has passed the last case
                                // subtract 1 from the j counter
                                dbgLog.fine("Z-mark was detected");
                                caseQnty = j - 1;
                                break FBLOCK;
                            }
                        } else if (buffer.equals("*")) {
                            // '*' is the first character of the system missing value
                            datumForTabFile = MissingValueForTextDataFile;
                            datum = null;
                            isMissingValue = true;

                            // read next char '.' as part of the missing value
                            reader.read(tmp);
                            buffer = Character.toString(tmp[0]);
                            break;
                        }

                    }
                    if (nint == 0) {
                        // no more data to be read; reached the eof
                        caseQnty = j - 1;
                        break FBLOCK;
                    }

                    // follow-up process for non-missing-values
                    if (!isMissingValue) {
                        // decode a numeric datum as String
                        String datumNumericBase30 = sb_datumNumericBase30.toString();
                        Matcher matcher = pattern4Integer.matcher(datumNumericBase30);

                        if (matcher.matches()) {
                            // integer case
                            datum = Long.valueOf(datumNumericBase30, 30).toString();
                        } else {
                            // double case
                            datum = doubleNumberFormatter.format(base30Tobase10Conversion(datumNumericBase30));
                        }

                        // now check format (if date or time)
                        String variableFormatType = variableFormatTypeList[i];

                        if (variableFormatType.equals("date")) {
                            variableTypeFinal[i] = -1;
                            long dateDatum = Long.parseLong(datum) * 1000L - SPSS_DATE_OFFSET;
                            datum = sdf_ymd.format(new Date(dateDatum));
                            datumDateFormat = sdf_ymd.toPattern();

                        } else if (variableFormatType.equals("time")) {
                            variableTypeFinal[i] = -1;
                            int formatDecimalPointPosition = formatDecimalPointPositionList.get(i);

                            if (printFormatTable.get(variableNameList.get(i)).equals("DTIME")) {

                                if (datum.indexOf(".") < 0) {
                                    long dateDatum = Long.parseLong(datum) * 1000L - SPSS_DATE_BIAS;
                                    datum = sdf_dhms.format(new Date(dateDatum));
                                    // don't save date format for dtime
                                } else {
                                    // decimal point included
                                    String[] timeData = datum.split("\\.");
                                    long dateDatum = Long.parseLong(timeData[0]) * 1000L - SPSS_DATE_BIAS;
                                    StringBuilder sb_time = new StringBuilder(
                                            sdf_dhms.format(new Date(dateDatum)));

                                    if (formatDecimalPointPosition > 0) {
                                        sb_time.append(
                                                "." + timeData[1].substring(0, formatDecimalPointPosition));
                                    }

                                    datum = sb_time.toString();
                                    // DTIME is weird date/time format that no one uses outside of 
                                    // SPSS; so we are not even going to bother trying to save
                                    // this variable as a datetime. 
                                }

                            } else if (printFormatTable.get(variableNameList.get(i)).equals("DATETIME")) {
                                // TODO: 
                                // (for both datetime and "dateless" time)
                                // keep the longest of the matching formats - i.e., if there are *some*
                                // values in the vector that have thousands of a second, that should be 
                                // part of the saved format!
                                //  -- L.A. Aug. 12 2014 

                                if (!datum.contains(".")) {
                                    long dateDatum = Long.parseLong(datum) * 1000L - SPSS_DATE_OFFSET;
                                    datum = sdf_ymdhms.format(new Date(dateDatum));
                                    datumDateFormat = sdf_ymdhms.toPattern();
                                } else {
                                    // decimal point included
                                    String[] timeData = datum.split("\\.");
                                    long dateDatum = Long.parseLong(timeData[0]) * 1000L - SPSS_DATE_OFFSET;
                                    StringBuilder sb_time = new StringBuilder(
                                            sdf_ymdhms.format(new Date(dateDatum)));

                                    if (formatDecimalPointPosition > 0) {
                                        sb_time.append(
                                                "." + timeData[1].substring(0, formatDecimalPointPosition));
                                    }

                                    datum = sb_time.toString();
                                    datumDateFormat = sdf_ymdhms.toPattern()
                                            + (formatDecimalPointPosition > 0 ? ".S" : "");
                                }

                            } else if (printFormatTable.get(variableNameList.get(i)).equals("TIME")) {

                                if (!datum.contains(".")) {
                                    long dateDatum = Long.parseLong(datum) * 1000L;
                                    datum = sdf_hms.format(new Date(dateDatum));
                                    datumDateFormat = sdf_hms.toPattern();
                                } else {
                                    // decimal point included
                                    String[] timeData = datum.split("\\.");
                                    long dateDatum = Long.parseLong(timeData[0]) * 1000L;
                                    StringBuilder sb_time = new StringBuilder(
                                            sdf_hms.format(new Date(dateDatum)));

                                    if (formatDecimalPointPosition > 0) {
                                        sb_time.append(
                                                "." + timeData[1].substring(0, formatDecimalPointPosition));
                                    }

                                    datum = sb_time.toString();
                                    datumDateFormat = sdf_hms.toPattern()
                                            + (formatDecimalPointPosition > 0 ? ".S" : "");
                                }
                            }

                        } else if (variableFormatType.equals("other")) {

                            if (printFormatTable.get(variableNameList.get(i)).equals("WKDAY")) {
                                // day of week
                                variableTypeFinal[i] = -1;
                                datum = SPSSConstants.WEEKDAY_LIST.get(Integer.valueOf(datum) - 1);

                            } else if (printFormatTable.get(variableNameList.get(i)).equals("MONTH")) {
                                // month
                                variableTypeFinal[i] = -1;
                                datum = SPSSConstants.MONTH_LIST.get(Integer.valueOf(datum) - 1);
                            }
                        }

                        // since value is not missing, set both values to be the same
                        datumForTabFile = datum;

                        // decimal-point check (variable is integer or not)
                        if (variableTypeFinal[i] == 0) {
                            if (datum.contains(".")) {
                                variableTypeFinal[i] = 1;
                                decimalVariableSet.add(i);
                            }
                        }
                    }

                    if (datumDateFormat != null) {
                        dateFormatList[i] = datumDateFormat;
                    }
                    casewiseRecordForTabFile[i] = datumForTabFile;

                } // end: if: string vs numeric variable

            } // end:for-loop-i (variable-wise loop)

            // print the i-th case; use casewiseRecord to dump the current case to the tab-delimited file
            pwout.println(StringUtils.join(casewiseRecordForTabFile, "\t"));

        } // end: while-block
    } finally {
        // close the print writer
        if (pwout != null) {
            pwout.close();
        }
    }

    ///smd.setDecimalVariables(decimalVariableSet);
    dataTable.setCaseQuantity(new Long(caseQnty));

    dbgLog.fine("decodeData(): end");
}

From source file:es.bsc.servicess.ide.editors.deployers.LicenseTokensTableComposite.java

/**
 * Read the service manifest form a existing file
 * //from  w ww.  j a va 2 s.  c  om
 * @throws IOException
 */
protected void readManifestFromFile() throws IOException {
    log.debug("Reading manifest file");
    StringBuffer manifestData = new StringBuffer(1000);
    BufferedReader reader = new BufferedReader(new FileReader(getProject().getProject()
            .getFolder(ProjectMetadata.OUTPUT_FOLDER).getFolder(ProjectMetadata.PACKAGES_FOLDER).getLocation()
            .append(ProjectMetadata.SERVICE_MANIFEST).toFile()));
    char[] buf = new char[1024];
    int numRead = 0;
    while ((numRead = reader.read(buf)) != -1) {
        String readData = String.valueOf(buf, 0, numRead);
        manifestData.append(readData);
        buf = new char[1024];
    }
    reader.close();
    manifest = Manifest.Factory.newInstance(manifestData.toString());
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.por.PORFileReader.java

private void decodeData(BufferedReader reader) throws IOException {
    List<String[]> dataTableList = new ArrayList<String[]>();
    List<String[]> dateFormatList = new ArrayList<String[]>();
    int[] variableTypeFinal = new int[varQnty];

    // create a File object to save the tab-delimited data file
    File tabDelimitedDataFile = File.createTempFile("tempTabfile.", ".tab");
    smd.getFileInformation().put("tabDelimitedDataFileLocation", tabDelimitedDataFile.getAbsolutePath());

    FileOutputStream fileOutTab = null;
    PrintWriter pwout = null;/*  www.j a va2  s.c  om*/

    try {
        fileOutTab = new FileOutputStream(tabDelimitedDataFile);
        pwout = new PrintWriter(new OutputStreamWriter(fileOutTab, "utf8"), true);

        variableFormatTypeList = new String[varQnty];
        for (int i = 0; i < varQnty; i++) {
            variableFormatTypeList[i] = SPSSConstants.FORMAT_CATEGORY_TABLE
                    .get(printFormatTable.get(variableNameList.get(i)));
            formatCategoryTable.put(variableNameList.get(i), variableFormatTypeList[i]);
        }

        // contents (variable) checker concering decimals
        Arrays.fill(variableTypeFinal, 0);

        // raw-case counter
        int j = 0; // case

        // use while instead for because the number of cases (observations) is usually unknown
        FBLOCK: while (true) {
            j++;

            // case(row)-wise storage object; to be updated after each row-reading

            String[] casewiseRecord = new String[varQnty];
            String[] caseWiseDateFormat = new String[varQnty];
            String[] casewiseRecordForTabFile = new String[varQnty];
            // warning: the above object is later shallow-copied to the
            // data object for calculating a UNF value/summary statistics
            //

            for (int i = 0; i < varQnty; i++) {
                // check the type of this variable
                boolean isStringType = variableTypeTable.get(variableNameList.get(i)) > 0 ? true : false;

                if (isStringType) {
                    // String case
                    variableTypeFinal[i] = -1;

                    StringBuilder sb_StringLengthBase30 = new StringBuilder("");
                    int stringLengthBase10 = 0;
                    String buffer = "";
                    char[] tmp = new char[1];

                    int nint;
                    while ((nint = reader.read(tmp)) > 0) {
                        buffer = Character.toString(tmp[0]);
                        if (buffer.equals("/")) {
                            break;
                        } else if (buffer.equals("Z")) {
                            if (i == 0) {
                                // the reader has passed the last case; subtract 1 from the j counter
                                caseQnty = j - 1;
                                break FBLOCK;
                            }
                        } else {
                            sb_StringLengthBase30.append(buffer);
                        }

                    }

                    if (nint == 0) {
                        // no more data to be read (reached the eof)
                        caseQnty = j - 1;
                        break FBLOCK;
                    }

                    dbgLog.finer(
                            j + "-th case " + i + "=th var:datum length=" + sb_StringLengthBase30.toString());

                    // this length value should be a positive integer
                    Matcher mtr = pattern4positiveInteger.matcher(sb_StringLengthBase30.toString());
                    if (mtr.matches()) {
                        stringLengthBase10 = Integer.valueOf(sb_StringLengthBase30.toString(), 30);
                    } else {
                        // reading error case
                        throw new IOException("reading F(data) section: string: length is not integer");
                    }

                    // read this string-variable's contents after "/"
                    char[] char_datumString = new char[stringLengthBase10];
                    reader.read(char_datumString);

                    String datum = new String(char_datumString);
                    casewiseRecord[i] = datum;
                    casewiseRecordForTabFile[i] = "\""
                            + datum.replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"";
                    // end of string case
                } else {

                    // numeric case
                    StringBuilder sb_datumNumericBase30 = new StringBuilder("");
                    boolean isMissingValue = false;
                    String datum = null;
                    String datumForTabFile = null;
                    String datumDateFormat = null;

                    String buffer = "";
                    char[] tmp = new char[1];
                    int nint;
                    while ((nint = reader.read(tmp)) > 0) {
                        sb_datumNumericBase30.append(buffer);
                        buffer = Character.toString(tmp[0]);

                        if (buffer.equals("/")) {
                            break;
                        } else if (buffer.equals("Z")) {
                            if (i == 0) {
                                // the reader has passed the last case
                                // subtract 1 from the j counter
                                dbgLog.fine("Z-mark was detected");
                                caseQnty = j - 1;
                                break FBLOCK;
                            }
                        } else if (buffer.equals("*")) {
                            // '*' is the first character of the system missing value
                            datumForTabFile = MissingValueForTextDataFile;
                            datum = null;
                            isMissingValue = true;

                            // read next char '.' as part of the missing value
                            reader.read(tmp);
                            buffer = Character.toString(tmp[0]);
                            break;
                        }

                    }
                    if (nint == 0) {
                        // no more data to be read; reached the eof
                        caseQnty = j - 1;
                        break FBLOCK;
                    }

                    // follow-up process for non-missing-values
                    if (!isMissingValue) {
                        // decode a numeric datum as String
                        String datumNumericBase30 = sb_datumNumericBase30.toString();
                        Matcher matcher = pattern4Integer.matcher(datumNumericBase30);

                        if (matcher.matches()) {
                            // integer case
                            datum = Long.valueOf(datumNumericBase30, 30).toString();
                        } else {
                            // double case
                            datum = doubleNumberFormatter.format(base30Tobase10Conversion(datumNumericBase30));
                        }

                        // now check format (if date or time)
                        String variableFormatType = variableFormatTypeList[i];

                        if (variableFormatType.equals("date")) {
                            variableTypeFinal[i] = -1;
                            long dateDatum = Long.parseLong(datum) * 1000L - SPSS_DATE_OFFSET;
                            datum = sdf_ymd.format(new Date(dateDatum));
                            datumDateFormat = sdf_ymd.toPattern();

                        } else if (variableFormatType.equals("time")) {
                            variableTypeFinal[i] = -1;
                            int formatDecimalPointPosition = formatDecimalPointPositionList.get(i);

                            if (printFormatTable.get(variableNameList.get(i)).equals("DTIME")) {

                                if (datum.indexOf(".") < 0) {
                                    long dateDatum = Long.parseLong(datum) * 1000L - SPSS_DATE_BIAS;
                                    datum = sdf_dhms.format(new Date(dateDatum));
                                    // don't save date format for dtime
                                } else {
                                    // decimal point included
                                    String[] timeData = datum.split("\\.");
                                    long dateDatum = Long.parseLong(timeData[0]) * 1000L - SPSS_DATE_BIAS;
                                    StringBuilder sb_time = new StringBuilder(
                                            sdf_dhms.format(new Date(dateDatum)));

                                    if (formatDecimalPointPosition > 0) {
                                        sb_time.append(
                                                "." + timeData[1].substring(0, formatDecimalPointPosition));
                                    }

                                    datum = sb_time.toString();
                                    // don't save date format for dtime
                                }

                            } else if (printFormatTable.get(variableNameList.get(i)).equals("DATETIME")) {

                                if (datum.indexOf(".") < 0) {
                                    long dateDatum = Long.parseLong(datum) * 1000L - SPSS_DATE_OFFSET;
                                    datum = sdf_ymdhms.format(new Date(dateDatum));
                                    datumDateFormat = sdf_ymdhms.toPattern();
                                } else {
                                    // decimal point included
                                    String[] timeData = datum.split("\\.");
                                    long dateDatum = Long.parseLong(timeData[0]) * 1000L - SPSS_DATE_OFFSET;
                                    StringBuilder sb_time = new StringBuilder(
                                            sdf_ymdhms.format(new Date(dateDatum)));

                                    if (formatDecimalPointPosition > 0) {
                                        sb_time.append(
                                                "." + timeData[1].substring(0, formatDecimalPointPosition));
                                    }

                                    datum = sb_time.toString();
                                    datumDateFormat = sdf_ymdhms.toPattern()
                                            + (formatDecimalPointPosition > 0 ? ".S" : "");
                                }

                            } else if (printFormatTable.get(variableNameList.get(i)).equals("TIME")) {

                                if (datum.indexOf(".") < 0) {
                                    long dateDatum = Long.parseLong(datum) * 1000L;
                                    datum = sdf_hms.format(new Date(dateDatum));
                                    datumDateFormat = sdf_hms.toPattern();
                                } else {
                                    // decimal point included
                                    String[] timeData = datum.split("\\.");
                                    long dateDatum = Long.parseLong(timeData[0]) * 1000L;
                                    StringBuilder sb_time = new StringBuilder(
                                            sdf_hms.format(new Date(dateDatum)));

                                    if (formatDecimalPointPosition > 0) {
                                        sb_time.append(
                                                "." + timeData[1].substring(0, formatDecimalPointPosition));
                                    }

                                    datum = sb_time.toString();
                                    datumDateFormat = sdf_hms.toPattern()
                                            + (formatDecimalPointPosition > 0 ? ".S" : "");
                                }
                            }

                        } else if (variableFormatType.equals("other")) {

                            if (printFormatTable.get(variableNameList.get(i)).equals("WKDAY")) {
                                // day of week
                                variableTypeFinal[i] = -1;
                                datum = SPSSConstants.WEEKDAY_LIST.get(Integer.valueOf(datum) - 1);

                            } else if (printFormatTable.get(variableNameList.get(i)).equals("MONTH")) {
                                // month
                                variableTypeFinal[i] = -1;
                                datum = SPSSConstants.MONTH_LIST.get(Integer.valueOf(datum) - 1);
                            }
                        }

                        // since value is not missing, set both values to be the same
                        datumForTabFile = datum;

                        // decimal-point check (variable is integer or not)
                        if (variableTypeFinal[i] == 0) {
                            if (datum.indexOf(".") >= 0) {
                                variableTypeFinal[i] = 1;
                                decimalVariableSet.add(i);
                            }
                        }
                    }

                    casewiseRecord[i] = datum;
                    caseWiseDateFormat[i] = datumDateFormat;
                    casewiseRecordForTabFile[i] = datumForTabFile;

                } // end: if: string vs numeric variable

            } // end:for-loop-i (variable-wise loop)

            // print the i-th case; use casewiseRecord to dump the current case to the tab-delimited file
            pwout.println(StringUtils.join(casewiseRecordForTabFile, "\t"));
            // store the current case-holder object to the data object for later operations such as UNF/summary statistics
            dataTableList.add(casewiseRecord);
            dateFormatList.add(caseWiseDateFormat);

        } // end: while-block
    } finally {
        // close the print writer
        if (pwout != null) {
            pwout.close();
        }
    }

    smd.setDecimalVariables(decimalVariableSet);
    smd.getFileInformation().put("caseQnty", caseQnty);

    // store data in column(variable)-wise for calculating variable-wise statistics
    Object[][] dataTable2 = new Object[varQnty][caseQnty];
    String[][] dateFormat = new String[varQnty][caseQnty];

    for (int jl = 0; jl < caseQnty; jl++) {
        for (int jk = 0; jk < varQnty; jk++) {
            dataTable2[jk][jl] = dataTableList.get(jl)[jk];
            dateFormat[jk][jl] = dateFormatList.get(jl)[jk];
        }
    }

    String[] unfValues = new String[varQnty];
    for (int k = 0; k < varQnty; k++) {
        int variableTypeNumer = variableTypeFinal[k];
        unfValues[k] = getUNF(dataTable2[k], dateFormat[k], variableTypeNumer, k);
    }
    String fileUnfValue = UNF5Util.calculateUNF(unfValues);

    porDataSection.setUnf(unfValues);
    porDataSection.setFileUnf(fileUnfValue);
    porDataSection.setData(dataTable2);

    smd.setVariableUNF(unfValues);
    smd.getFileInformation().put("fileUNF", fileUnfValue);
}