Example usage for org.xml.sax SAXParseException printStackTrace

List of usage examples for org.xml.sax SAXParseException printStackTrace

Introduction

In this page you can find the example usage for org.xml.sax SAXParseException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:de.dfki.iui.mmds.dialogue.SiamStateMachine.java

private SCXML load(final String scxml) {

    ErrorHandler errHandler = new ErrorHandler() {
        @Override//from   www .j a v a  2  s . c  om
        public void error(SAXParseException e) throws SAXException {
            System.err.println(e.getMessage());

        }

        @Override
        public void fatalError(SAXParseException e) throws SAXException {
            System.err.println(e.getMessage());

        }

        @Override
        public void warning(SAXParseException e) throws SAXException {
            System.err.println(e.getMessage());
        }
    };

    SCXML stateMachine = null;
    try {
        stateMachine = SCXMLParser.parse(new InputSource(new StringReader(scxml)), errHandler);// ca
        // );
    } catch (IOException | SAXException | ModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return stateMachine;
}

From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java

/**
 * Reads in a DigiDoc file. One of fname or isSdoc must be given.
 * @param fname signed doc filename//from   w  ww  .j  a v  a  2  s.com
 * @param isSdoc opened stream with DigiDoc data
 * The user must open and close it.
 * @param errs list of errors to fill with parsing errors. If given
 * then attempt is made to continue parsing on errors and return them in this list.
 * If not given (null) then the first error found will be thrown.
 * @return signed document object if successfully parsed
 */
private SignedDoc readSignedDocOfType(String fname, InputStream isSdoc, boolean isBdoc, List errs)
        throws DigiDocException {
    // Use an instance of ourselves as the SAX event handler
    SAXDigiDocFactory handler = this;
    m_errs = errs;
    DigiDocVerifyFactory.initProvider();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    if (m_logger.isDebugEnabled())
        m_logger.debug("Start reading ddoc/bdoc " + ((fname != null) ? "from file: " + fname : "from stream")
                + " bdoc: " + isBdoc);
    if (fname == null && isSdoc == null) {
        throw new DigiDocException(DigiDocException.ERR_READ_FILE, "No input file", null);
    }
    if (fname != null) {
        File inFile = new File(fname);
        if (!inFile.canRead() || inFile.length() == 0) {
            throw new DigiDocException(DigiDocException.ERR_READ_FILE, "Empty or unreadable input file", null);
        }
    }
    ZipFile zf = null;
    ZipArchiveInputStream zis = null;
    ZipArchiveEntry ze = null;
    InputStream isEntry = null;
    File fTmp = null;
    try {
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        if (isBdoc) { // bdoc parsing
            // must be a bdoc document ?
            m_doc = new SignedDoc();
            m_doc.setVersion(SignedDoc.BDOC_VERSION_1_0);
            m_doc.setFormat(SignedDoc.FORMAT_BDOC);
            Enumeration eFiles = null;
            if (fname != null) {
                zf = new ZipFile(fname, "UTF-8");
                eFiles = zf.getEntries();
            } else if (isSdoc != null) {
                zis = new ZipArchiveInputStream(isSdoc, "UTF-8", true, true);
            }
            ArrayList lSigFnames = new ArrayList();
            ArrayList lDataFnames = new ArrayList();
            // read all entries
            boolean bHasMimetype = false, bManifest1 = false;
            int nFil = 0;
            while ((zf != null && eFiles.hasMoreElements())
                    || (zis != null && ((ze = zis.getNextZipEntry()) != null))) {
                nFil++;

                // read entry
                if (zf != null) { // ZipFile
                    ze = (ZipArchiveEntry) eFiles.nextElement();
                    isEntry = zf.getInputStream(ze);
                } else { // ZipArchiveInputStream
                    int n = 0, nTot = 0;
                    if ((ze.getName().equals(FILE_MIMETYPE) || ze.getName().equals(FILE_MANIFEST)
                            || (ze.getName().startsWith(FILE_SIGNATURES) && ze.getName().endsWith(".xml")))
                            || (nMaxBdocFilCached <= 0
                                    || (ze.getSize() < nMaxBdocFilCached && ze.getSize() >= 0))) {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        byte[] data = new byte[2048];
                        while ((n = zis.read(data)) > 0) {
                            bos.write(data, 0, n);
                            nTot += n;
                        }
                        if (m_logger.isDebugEnabled())
                            m_logger.debug("Read: " + nTot + " bytes from zip");
                        data = bos.toByteArray();
                        bos = null;
                        isEntry = new ByteArrayInputStream(data);
                    } else {
                        File fCacheDir = new File(ConfigManager.instance().getStringProperty(
                                "DIGIDOC_DF_CACHE_DIR", System.getProperty("java.io.tmpdir")));
                        fTmp = File.createTempFile("bdoc-data", ".tmp", fCacheDir);
                        FileOutputStream fos = new FileOutputStream(fTmp);
                        byte[] data = new byte[2048];
                        while ((n = zis.read(data)) > 0) {
                            fos.write(data, 0, n);
                            nTot += n;
                        }
                        if (m_logger.isDebugEnabled())
                            m_logger.debug("Read: " + nTot + " bytes from zip to: " + fTmp.getAbsolutePath());
                        fos.close();
                        isEntry = new FileInputStream(fTmp);
                    }
                }
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Entry: " + ze.getName() + " nlen: " + ze.getName().length() + " size: "
                            + ze.getSize() + " dir: " + ze.isDirectory() + " comp-size: "
                            + ze.getCompressedSize());
                // mimetype file
                if (ze.getName().equals(FILE_MIMETYPE)) {
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Check mimetype!");
                    checkBdocMimetype(isEntry);
                    bHasMimetype = true;
                    m_doc.setComment(ze.getComment());
                    if (nFil != 1) {
                        m_logger.error("mimetype file is " + nFil + " file but must be first");
                        handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                                "mimetype file is not first zip entry", null));
                    }
                } else if (ze.getName().equals(FILE_MANIFEST)) { // manifest.xml file
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Read manifest");
                    if (!bManifest1 && isEntry != null) {
                        bManifest1 = true;
                        BdocManifestParser mfparser = new BdocManifestParser(m_doc);
                        mfparser.readManifest(isEntry);
                    } else {
                        m_logger.error("Found multiple manifest.xml files!");
                        throw new DigiDocException(DigiDocException.ERR_MULTIPLE_MANIFEST_FILES,
                                "Found multiple manifest.xml files!", null);
                    }
                } else if (ze.getName().startsWith(FILE_SIGNATURES) && ze.getName().endsWith(".xml")) { // some signature
                    m_fileName = ze.getName();
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Reading bdoc siganture: " + m_fileName);
                    boolean bExists = false;
                    for (int j = 0; j < lSigFnames.size(); j++) {
                        String s1 = (String) lSigFnames.get(j);
                        if (s1.equals(m_fileName))
                            bExists = true;
                    }
                    if (bExists) {
                        m_logger.error("Duplicate signature filename: " + m_fileName);
                        handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                                "Duplicate signature filename: " + m_fileName, null));
                    } else
                        lSigFnames.add(m_fileName);
                    SAXParser saxParser = factory.newSAXParser();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    int n = 0;
                    byte[] data = new byte[2048];
                    while ((n = isEntry.read(data)) > 0)
                        bos.write(data, 0, n);
                    data = bos.toByteArray();
                    bos = null;
                    if (m_logger.isDebugEnabled())
                        m_logger.debug(
                                "Parsing bdoc: " + m_fileName + " size: " + ((data != null) ? data.length : 0));
                    saxParser.parse(new SignatureInputStream(new ByteArrayInputStream(data)), this);
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Parsed bdoc: " + m_fileName);
                    Signature sig1 = m_doc.getLastSignature();
                    m_sigComment = ze.getComment();
                    if (sig1 != null) {
                        sig1.setPath(m_fileName);
                        sig1.setComment(ze.getComment());
                    }
                } else { // probably a data file
                    if (m_logger.isDebugEnabled())
                        m_logger.debug("Read data file: " + ze.getName());
                    if (!ze.isDirectory()) {
                        boolean bExists = false;
                        for (int j = 0; j < lDataFnames.size(); j++) {
                            String s1 = (String) lDataFnames.get(j);
                            if (s1.equals(ze.getName()))
                                bExists = true;
                        }
                        if (bExists) {
                            m_logger.error("Duplicate datafile filename: " + ze.getName());
                            handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                                    "Duplicate datafile filename: " + ze.getName(), null));
                        } else
                            lDataFnames.add(ze.getName());
                        DataFile df = m_doc.findDataFileById(ze.getName());
                        if (df != null) {
                            if (ze.getSize() > 0)
                                df.setSize(ze.getSize());
                            df.setContentType(DataFile.CONTENT_BINARY);
                            df.setFileName(ze.getName());
                        } else {
                            df = new DataFile(ze.getName(), DataFile.CONTENT_BINARY, ze.getName(),
                                    "application/binary", m_doc);
                            if (m_doc.getDataFiles() == null)
                                m_doc.setDataFiles(new ArrayList());
                            m_doc.getDataFiles().add(df);
                            //m_doc.addDataFile(df); // this does some intiailization work unnecessary here
                        }
                        // enable caching if requested
                        if (isEntry != null)
                            df.setOrCacheBodyAndCalcHashes(isEntry);
                        df.setComment(ze.getComment());
                        df.setLastModDt(new Date(ze.getTime()));
                        // fix mime type according to DataObjectFormat
                        Signature sig1 = m_doc.getLastSignature();
                        if (sig1 != null) {
                            Reference dRef = sig1.getSignedInfo().getReferenceForDataFile(df);
                            if (dRef != null) {
                                DataObjectFormat dof = sig1.getSignedInfo()
                                        .getDataObjectFormatForReference(dRef);
                                if (dof != null) {
                                    df.setMimeType(dof.getMimeType());
                                }
                            }
                        }
                    }
                }
                if (fTmp != null) {
                    fTmp.delete();
                    fTmp = null;
                }
            } // while zip entries
            if (!bHasMimetype) {
                m_logger.error("No mimetype file");
                handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                        "Not a BDOC format file! No mimetype file!", null));
            }
            // if no signatures exist then copy mime-type from manifest.xml to DataFile -s
            if (m_doc.countSignatures() == 0) {
                for (int i = 0; i < m_doc.countDataFiles(); i++) {
                    DataFile df = m_doc.getDataFile(i);
                    if (m_doc.getManifest() != null) {
                        for (int j = 0; j < m_doc.getManifest().getNumFileEntries(); j++) {
                            ManifestFileEntry mfe = m_doc.getManifest().getFileEntry(j);
                            if (mfe.getFullPath() != null && mfe.getFullPath().equals(df.getFileName())) {
                                df.setMimeType(mfe.getMediaType());
                            } // if fullpath
                        } // for
                    } // if
                } // for i
            }
        } else { // ddoc parsing
            if (m_logger.isDebugEnabled())
                m_logger.debug("Reading ddoc: " + fname + " file: " + m_fileName);
            m_fileName = fname;
            SAXParser saxParser = factory.newSAXParser();
            if (fname != null)
                saxParser.parse(new SignatureInputStream(new FileInputStream(fname)), this);
            else if (isSdoc != null)
                saxParser.parse(isSdoc, this);
        }
    } catch (org.xml.sax.SAXParseException ex) {
        m_logger.error("SAX Error: " + ex);
        handleError(ex);

    } catch (Exception ex) {
        m_logger.error("Error reading3: " + ex);
        ex.printStackTrace();
        /*if(ex instanceof DigiDocException){
           DigiDocException dex = (DigiDocException)ex;
           m_logger.error("Dex: " + ex);
           if(dex.getNestedException() != null) {
              dex.getNestedException().printStackTrace();
              m_logger.error("Trace: "); 
           }
        }*/
        handleError(ex);
    } finally { // cleanup
        try {
            if (isEntry != null) {
                isEntry.close();
                isEntry = null;
            }
            if (zis != null)
                zis.close();
            if (zf != null)
                zf.close();
            if (fTmp != null) {
                fTmp.delete();
                fTmp = null;
            }
        } catch (Exception ex) {
            m_logger.error("Error closing streams and files: " + ex);
        }
    }
    // compare Manifest and DataFiles
    boolean bErrList = (errs != null);
    if (errs == null)
        errs = new ArrayList();
    boolean bOk = DigiDocVerifyFactory.verifyManifestEntries(m_doc, errs);
    if (m_doc == null) {
        m_logger.error("Error reading4: doc == null");
        handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML,
                "This document is not in ddoc or bdoc format", null));
    }
    if (!bErrList && errs.size() > 0) { // if error list was not used then we have to throw exception. So we will throw the first one since we can only do it once
        DigiDocException ex = (DigiDocException) errs.get(0);
        throw ex;
    }
    return m_doc;
}

From source file:org.easyrec.utils.Web.java

/**
 * This procedure extracts the values/*from w  w w  .  j a  v  a  2  s. c  om*/
 * of the <name>-Tags of a given Xml file into a list of Strings.
 * e.g.
 * <name>hanso</name>
 * <name>stritzi</name>
 * <p/>
 * --> {"hansi","stritzi"}
 *
 * @param apiURL  String
 * @param tagName String
 * @return a list of strings
 */
@SuppressWarnings({ "UnusedDeclaration" })
public static List<String> getInnerHTMLfromTags(String apiURL, String tagName) {

    List<String> innerHTMLList = new ArrayList<String>();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ErrorHandler() {
            public void warning(SAXParseException e) throws SAXException {
            }

            public void error(SAXParseException e) throws SAXException {
            }

            public void fatalError(SAXParseException e) throws SAXException {
            }
        });
        Document doc = db.parse(apiURL.replaceAll(" ", "%20"));

        NodeList tagNodes = doc.getElementsByTagName(tagName);

        for (int i = 0; i < tagNodes.getLength(); i++) {
            innerHTMLList.add(tagNodes.item(i).getTextContent());
        }
    } catch (ParserConfigurationException e1) {
        e1.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return innerHTMLList;
}

From source file:org.jbuiltDemo.managed.view.Xhtml2Jbuilt.java

@Override
public void warning(SAXParseException e) throws SAXException {
    e.printStackTrace();
}

From source file:org.opencds.knowledgeRepository.SimpleKnowledgeRepository.java

protected static void initialize(String submittedFullPathToKRData) throws DSSRuntimeExceptionFault {
    String startTime = DateUtility.getInstance().getDateAsString(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
    System.out.println();/*from w w w  . j  a  v  a 2s .com*/
    System.out.println(
            startTime + " <<< Initializing OpenCDS SimpleKnowledgeRepository at " + fullPathToKRData + " >>>");

    // save the fullPathToKRData where we can use it.
    fullPathToKRData = submittedFullPathToKRData.trim();
    // add a trailing / if it is missing...
    if (!"/".equals(fullPathToKRData.substring(fullPathToKRData.length()))) {
        fullPathToKRData = fullPathToKRData + "/";
    }
    log.info("Path to SimpleKnowledgeRepository data: " + fullPathToKRData);

    // read executionEngines resource
    String executionEngines = "";
    try {
        executionEngines = getResourceAsString("resourceAttributes", "openCdsExecutionEngines.xml");
    } catch (DSSRuntimeExceptionFault e1) {
        e1.printStackTrace();
        throw new DSSRuntimeExceptionFault(
                "SimpleKnowledgeRepository failed to getResourceAsString('resourceAttributes','openCdsExecutionEngines.xml': "
                        + e1.getCause());
    }
    XmlEntity executionEnginesRootEntity = null;
    try {
        executionEnginesRootEntity = XmlConverter.getInstance().unmarshalXml(executionEngines, false, null);
    } catch (SAXParseException e) {
        e.printStackTrace();
        throw new DSSRuntimeExceptionFault(
                "SimpleKnowledgeRepository failed to unmarshall openCdsExecutionEngines.xml " + executionEngines
                        + " " + e.getCause());
    }

    // load executionEngine array
    List<XmlEntity> executionEngineList = executionEnginesRootEntity.getChildrenWithLabel("executionEngine");
    for (XmlEntity executionEngine : executionEngineList) {
        // load kmId supported operations 
        String engineName = executionEngine.getAttributeValue("name");
        String logEngine = engineName;
        List<String> supportedDSSOperationStringList = new ArrayList<String>();
        Set<String> supportedOps = executionEngine.getAttributeLabels();
        Iterator<String> it = supportedOps.iterator();
        while (it.hasNext()) {
            String thisSupportedOperationName = it.next();
            String thisSupportedOperationValue = executionEngine.getAttributeValue(thisSupportedOperationName);
            if ("true".equals(thisSupportedOperationValue)) {
                supportedDSSOperationStringList.add(thisSupportedOperationName);
                logEngine = logEngine + ", " + thisSupportedOperationName;
            }
        }
        log.debug("Execution Engine: " + logEngine + ", name: " + engineName);
        myExecutionEngineToSupportedOperationsMap.put(engineName, supportedDSSOperationStringList);

    }

    // read semanticSignifiers resource
    String semanticSignifiers = "";
    try {
        semanticSignifiers = getResourceAsString("resourceAttributes", "semanticSignifiers.xml");
    } catch (DSSRuntimeExceptionFault e1) {
        e1.printStackTrace();
        throw new DSSRuntimeExceptionFault(
                "SimpleKnowledgeRepository failed to getResourceAsString('resourceAttributes','semanticSignifiers.xml': "
                        + e1.getCause());
    }
    XmlEntity semanticSignifiersRootEntity = null;
    try {
        semanticSignifiersRootEntity = XmlConverter.getInstance().unmarshalXml(semanticSignifiers, false, null);
    } catch (SAXParseException e) {
        e.printStackTrace();
        throw new DSSRuntimeExceptionFault(
                "SimpleKnowledgeRepository failed to unmarshall semanticSignifiers.xml " + executionEngines
                        + " " + e.getCause());
    }

    // load SSID arrays
    List<XmlEntity> semanticSignifierList = semanticSignifiersRootEntity
            .getChildrenWithLabel("semanticSignifier");
    for (XmlEntity semanticSignifier : semanticSignifierList) {
        // load ssid supported operations 
        XmlEntity dataModelElement = semanticSignifier.getFirstChildWithLabel("dataModel");
        String dataModel = dataModelElement.getValue();
        XmlEntity unmarshalClassName = semanticSignifier.getFirstChildWithLabel("unmarshalClass");

        mySSIdToUnmarshallerClassNameMap.put(dataModel, unmarshalClassName.getValue());
        XmlEntity marshalClassName = semanticSignifier.getFirstChildWithLabel("marshalClass");
        mySSIdToPayloadCreatorMap.put(dataModel, marshalClassName.getValue());
        log.debug("SSID: " + dataModel + ", marshalClassName: " + marshalClassName);
    }

    // read knowledgeModules
    String knowledgeModules = "";
    try {
        knowledgeModules = getResourceAsString("resourceAttributes", "knowledgeModules.xml");
    } catch (DSSRuntimeExceptionFault e1) {
        e1.printStackTrace();
        throw new DSSRuntimeExceptionFault(
                "SimpleKnowledgeRepository failed to getResourceAsString('resourceAttributes','knowledgeModules.xml': "
                        + e1.getCause());
    }
    XmlEntity kmMetadataRootEntity = null;
    try {
        kmMetadataRootEntity = XmlConverter.getInstance().unmarshalXml(knowledgeModules, false, null);
    } catch (SAXParseException e) {
        e.printStackTrace();
        throw new DSSRuntimeExceptionFault(
                "SimpleKnowledgeRepository failed to unmarshall knowledgeModules.xml " + knowledgeModules + " "
                        + e.getCause());
    }

    // load km arrays
    List<XmlEntity> kmMetadataList = kmMetadataRootEntity.getChildrenWithLabel("kmMetadata");
    for (XmlEntity kmMetadata : kmMetadataList) {
        // load kmId to dataModel map
        XmlEntity identifier = kmMetadata.getFirstChildWithLabel("identifier");
        String kmId = identifier.getAttributeValue("scopingEntityId") + "^"
                + identifier.getAttributeValue("businessId") + "^" + identifier.getAttributeValue("version");
        XmlEntity dataModel = kmMetadata.getFirstChildWithLabel("dataModel");
        EntityIdentifier dataModelEI = DSSUtility.makeEI(dataModel.getValue());
        myKMIdToSSIdMap.put(kmId, dataModelEI);

        // load kmId to inference engine adapter map
        XmlEntity executionEngine = kmMetadata.getFirstChildWithLabel("executionEngine");
        myKMIdToInferenceEngineAdapterMap.put(kmId, executionEngine.getValue());

        // load kmId to primary process name map
        XmlEntity knowledgeModulePrimaryProcessName = kmMetadata
                .getFirstChildWithLabel("knowledgeModulePrimaryProcessName");
        if ((knowledgeModulePrimaryProcessName != null)
                && (knowledgeModulePrimaryProcessName.getValue() != null)
                && !("".equals(knowledgeModulePrimaryProcessName.getValue()))) {
            myKMIdToPrimaryProcessNameMap.put(kmId, knowledgeModulePrimaryProcessName.getValue());
        } else {
            myKMIdToPrimaryProcessNameMap.put(kmId, "");
        }

        // load kmId to supported operations map
        if (myExecutionEngineToSupportedOperationsMap.get(executionEngine) != null) {
            myKMIdToSupportedOperationsMap.put(kmId,
                    myExecutionEngineToSupportedOperationsMap.get(executionEngine));
            log.debug("KMiD: " + kmId);
        }

    }

    //      private            HashMap<String, String> myCodeSystemOIDtoCodeSystemDisplayNameMap = new HashMap<String, String>();
    //      // key = String containing OID, target = displayName for OID

    // read codeSystem
    String codeSystems = "";
    try {
        codeSystems = getResourceAsString("resourceAttributes", "openCDSCodeSystems.xml");
    } catch (DSSRuntimeExceptionFault e1) {
        e1.printStackTrace();
        throw new DSSRuntimeExceptionFault(
                "SimpleKnowledgeRepository failed to getResourceAsString('resourceAttributes','openCDSCodeSystems.xml': "
                        + e1.getCause());
    }
    XmlEntity codeSystemsRootEntity = null;
    try {
        codeSystemsRootEntity = XmlConverter.getInstance().unmarshalXml(codeSystems, false, null);
    } catch (SAXParseException e) {
        e.printStackTrace();
        throw new DSSRuntimeExceptionFault(
                "SimpleKnowledgeRepository failed to unmarshall openCDSCodeSystems.xml " + codeSystems + " "
                        + e.getCause());
    }

    // load codeSystem arrays
    List<XmlEntity> codeSystemsList = codeSystemsRootEntity.getChildrenWithLabel("codeSystem");
    for (XmlEntity codeSystem : codeSystemsList) {
        // load oid to codeSystemName map
        String oid = codeSystem.getAttributeValue("codeSystemOID");
        String name = codeSystem.getAttributeValue("codeSystemDisplayName");
        String apelonNamespace = codeSystem.getAttributeValue("apelonNamespaceName");
        boolean isOntylog = "true".equals(codeSystem.getAttributeValue("isApelonOntylog"));
        myCodeSystemOIDtoCodeSystemDisplayNameMap.put(oid, name);
        if (apelonNamespace != null) {
            myCodeSystemOIDtoApelonNamespaceName.put(oid, apelonNamespace);
            myApelonNamespaceNameToCodeSystemOID.put(apelonNamespace, oid);
        }
        myCodeSystemOIDtoIsOntylog.put(oid, isOntylog);

        //load OIDs
        myOpenCdsCodeSystemOIDs.add(oid);
        log.debug("OpenCDSCodeSystems: " + oid + ", name: " + name);
    }

    // load codeSystem arrays
    List<String> conceptTypesList = OpenCDSConceptTypes.getOpenCdsConceptTypes();//conceptTypesRootEntity.getChildrenWithLabel("ConceptType");
    for (String conceptType : conceptTypesList) {
        // load concepts
        myOpenCdsConceptTypes.add(conceptType);
        log.trace("OpenCDSConceptTypes: " + conceptType);
    }

    String initTime = DateUtility.getInstance().getDateAsString(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
    System.out.println(initTime + " <<< OpenCDS SimpleKnowledgeRepository Initialized >>>");
    System.out.println();
    setKnowledgeRepositoryInitialized(true);
}

From source file:org.opencds.terminology.SimpleTerminologyManager.java

private void initialize() throws DSSRuntimeExceptionFault {
    // load code system OID to display name map and displayName to OID map      
    String openCDSCodeSystems = SimpleKnowledgeRepository.getResourceAsString("resourceAttributes",
            "openCDSCodeSystems.xml");
    XmlEntity codeSystemsRootEntity = null;
    try {/* w  ww.  j  a v  a  2s  . c  o  m*/
        codeSystemsRootEntity = XmlConverter.getInstance().unmarshalXml(openCDSCodeSystems, false, null);
    } catch (SAXParseException e) {
        e.printStackTrace();
        throw new DSSRuntimeExceptionFault("SimpleTerminologyService.initialize() failed to unmarshall '"
                + openCDSCodeSystems + "' " + e.getMessage());
    }

    // get target OpenCDS resource element
    ArrayList<XmlEntity> codeSystemEntitites = codeSystemsRootEntity.getChildrenWithLabel("codeSystem");
    for (XmlEntity codeSystemEntity : codeSystemEntitites) {
        String codeSystemOid = codeSystemEntity.getAttributeValue("codeSystemOID");
        String codeSystemDisplayName = codeSystemEntity.getAttributeValue("codeSystemDisplayName");
        myCodeSystemOIDtoCodeSystemDisplayNameMap.put(codeSystemOid, codeSystemDisplayName);
        myCodeSystemDisplayNametoCodeSystemOIDMap.put(codeSystemDisplayName, codeSystemOid);
        log.trace("codeSystem: " + codeSystemOid + ", name: " + codeSystemDisplayName);
    }
    /*      
          // load ConceptType name to value map
          String openCDSConceptTypes = SimpleKnowledgeRepository.getInstance().getResourceAsString("resourceAttributes","openCDSConceptTypes.xml");
          XmlEntity conceptTypesfileRootEntity = null;
          try 
          {
             conceptTypesfileRootEntity = XmlConverter.getInstance().unmarshalXml(openCDSConceptTypes, false, null);
          } catch (SAXParseException e) {
             e.printStackTrace();
             throw new DSSRuntimeExceptionFault("SimpleTerminologyService.initialize() failed to unmarshall '" + openCDSConceptTypes + "' " + e.getMessage());
          }
            
          // get target OpenCDS resource element
          ArrayList<XmlEntity> conceptTypeEntities = conceptTypesfileRootEntity.getChildrenWithLabel("ConceptType");
          for (XmlEntity conceptTypeEntity : conceptTypeEntities)
          {
             myConceptTypesNametoConceptTypeMap.put(conceptTypeEntity.getAttributeValue("name"), conceptTypeEntity.getAttributeValue("value"));
          }         
    */
    /*
     * Above code replaced by single line below, since openCDSConceptTypes.xml file is deprecated in the KR, des 2012-03-14
     */
    // load ConceptType name to value map from OpenCDSConceptTypes.java
    OpenCDSConceptTypes.getOpenCdsConceptTypes(myConceptTypesNametoConceptTypeMap);

    // load concept specification files
    String extendedPath = "conceptMappingSpecifications//autoGeneratedMappings";
    List<String> fileNames = SimpleKnowledgeRepository.listResourceNamesByType(extendedPath);
    loadEachFile(fileNames, extendedPath);

    String extendedPath2 = "conceptMappingSpecifications//manualMappings";
    List<String> fileNames2 = SimpleKnowledgeRepository.listResourceNamesByType(extendedPath2);
    loadEachFile(fileNames2, extendedPath2);
}

From source file:org.opencds.terminology.SimpleTerminologyManager.java

private void loadEachFile(List<String> fileNames, String extendedPath) throws DSSRuntimeExceptionFault {

    for (String fileName : fileNames) {
        String fileNameLowerCase = fileName.toLowerCase(); //so we catch .xml, .XML, .XmL, etc.  des 20121112
        if (fileNameLowerCase.endsWith(".xml")) // without this check, when packaged into jars, seems to find a filename of "" that gets processed
        {/*from  w  ww .j av  a2 s  .  c om*/
            String fileXmlAsString = SimpleKnowledgeRepository.getResourceAsXML(extendedPath, fileName);

            XmlEntity fileNamesRootEntity = null;
            try {
                fileNamesRootEntity = XmlConverter.getInstance().unmarshalXml(fileXmlAsString, false, null);
            } catch (SAXParseException e) {
                e.printStackTrace();
                throw new DSSRuntimeExceptionFault(
                        "SimpleTerminologyService.initialize() failed to unmarshall '" + fileXmlAsString + "' "
                                + e.getMessage());
            }

            // get target OpenCDS concept
            XmlEntity openCdsConceptEntity = fileNamesRootEntity.getFirstChildWithLabel("openCdsConcept");
            CD openCdsConcept = new CD(CodeSystems.CODE_SYSTEM_OID_OPENCDS_CONCEPTS,
                    getCodeSystemFromOID(CodeSystems.CODE_SYSTEM_OID_OPENCDS_CONCEPTS),
                    openCdsConceptEntity.getAttributeValue("code"),
                    openCdsConceptEntity.getAttributeValue("displayName"));

            // get concept determination method
            XmlEntity conceptDeterminationMethodEntity = fileNamesRootEntity
                    .getFirstChildWithLabel("conceptDeterminationMethod");
            CD conceptDeterminationMethod = new CD(CodeSystems.CODE_SYSTEM_OID_OPENCDS_CONCEPTS,
                    getCodeSystemFromOID(CodeSystems.CODE_SYSTEM_OID_OPENCDS_CONCEPTS),
                    conceptDeterminationMethodEntity.getAttributeValue("code"),
                    conceptDeterminationMethodEntity.getAttributeValue("displayName"));

            ObjectPair targetObjectPair = new ObjectPair();
            targetObjectPair.setObject1(openCdsConcept);
            targetObjectPair.setObject2(conceptDeterminationMethod);
            log.trace("OpenCdsConcept: " + openCdsConcept.toString() + ", ConceptDeterminationMethod: "
                    + conceptDeterminationMethod.toString() + ", mappingFile: " + fileName);

            // get members for code system
            XmlEntity membersForCodeSystemEntity = fileNamesRootEntity
                    .getFirstChildWithLabel("membersForCodeSystem");
            String codeSystem = membersForCodeSystemEntity.getAttributeValue("codeSystem");

            for (XmlEntity csEntity : (ArrayList<XmlEntity>) membersForCodeSystemEntity.getChildren()) {
                CD cd = new CD(codeSystem, csEntity.getAttributeValue("code"));
                log.trace(" - OpenCdsConcept code: " + csEntity.getAttributeValue("code") + ", codeSystem: "
                        + codeSystem.toString());

                if ((myCdToOpenCdsConceptObjectPairSetMap != null)
                        && (myCdToOpenCdsConceptObjectPairSetMap.containsKey(cd))) {
                    HashSet<ObjectPair> targetSet = myCdToOpenCdsConceptObjectPairSetMap.get(cd);
                    targetSet.add(targetObjectPair);
                } else {
                    HashSet<ObjectPair> objectPairSet = new HashSet<ObjectPair>();
                    objectPairSet.add(targetObjectPair);
                    myCdToOpenCdsConceptObjectPairSetMap.put(cd, objectPairSet);
                }
            }
        }
    }

}

From source file:org.opencds.terminology.SimpleTerminologyManager.java

@Override
/**/* w w  w .j  a v  a 2s.c o m*/
 * Returns a HashMap containing the OpenCDSConcepts supported by the terminology service.
 * 
 * All OpenCDSConcept types are represented.  If there are n matching OpenCDSConcepts for the type, an empty 
 * HashSet is associated with the key.
 * 
 * Key = supported OpenCDSConcept type enumerated in org.opencds.terminology.OpenCDSConceptTypes.
 * Target = HashSet of supported OpenCDSConcepts for type.
 *  
 * @return
 */
public HashMap<String, HashSet<CD>> getSupportedOpenCDSConcepts() throws DSSRuntimeExceptionFault {

    HashMap<String, HashSet<CD>> mapToReturn = new HashMap<String, HashSet<CD>>();

    // load config file with contents
    //InputStream configFileStream = this.getClass().getClassLoader().getResourceAsStream("SupportedConceptsConfigFile.xml");
    //String configFileXmlAsString = StreamUtility.getInstance().getStringFromInputStream_depleteStream(configFileStream);
    String configFileXmlAsString = SimpleKnowledgeRepository.getResourceAsString("resourceAttributes",
            "supportedConceptsConfigFile.xml");
    XmlEntity configFileRootEntity = null;
    try {
        configFileRootEntity = XmlConverter.getInstance().unmarshalXml(configFileXmlAsString, false, null);
    } catch (SAXParseException e) {
        e.printStackTrace();
        throw new DSSRuntimeExceptionFault(
                "SAXParseException in SimpleTerminologyManager.getSupportedOpenCDSConcepts: " + e.getMessage());
    }
    for (XmlEntity supportedConceptsForTypeEntity : (ArrayList<XmlEntity>) configFileRootEntity.getChildren()) {
        String openCdsConceptType = supportedConceptsForTypeEntity.getFirstChildWithLabel("openCdsConceptType")
                .getValue();

        ArrayList<XmlEntity> supportedOpenCdsConceptEntities = (ArrayList<XmlEntity>) supportedConceptsForTypeEntity
                .getChildrenWithLabel("supportedOpenCdsConcept");

        HashSet<CD> openCdsConceptsForType = new HashSet<CD>();

        for (XmlEntity supportedOpenCdsConceptEntity : supportedOpenCdsConceptEntities) {
            XmlEntity openCdsConceptEntity = supportedOpenCdsConceptEntity
                    .getFirstChildWithLabel("openCdsConcept");
            //            CD openCdsConcept = new CD("2.16.840.1.113883.3.795.12.1.1", "OpenCDS concepts", openCdsConceptEntity.getAttributeValue("code"), openCdsConceptEntity.getAttributeValue("displayName"));
            CD openCdsConcept = new CD(CodeSystems.CODE_SYSTEM_OID_OPENCDS_CONCEPTS, "OpenCDS concepts",
                    openCdsConceptEntity.getAttributeValue("code"),
                    openCdsConceptEntity.getAttributeValue("displayName"));
            openCdsConceptsForType.add(openCdsConcept);
        }
        mapToReturn.put(openCdsConceptType, openCdsConceptsForType);
    }

    ArrayList<String> openCdsConceptTypes = OpenCDSConceptTypes.getOpenCdsConceptTypes();
    for (String openCdsConceptType : openCdsConceptTypes) {
        if (!mapToReturn.containsKey(openCdsConceptType)) {
            mapToReturn.put(openCdsConceptType, new HashSet<CD>());
        }
    }

    return mapToReturn;
}

From source file:test.common.TestBase.java

/**
 * Assert that the XML is valid to the schema.
 * /*from   w  w  w  .ja va 2s  . co  m*/
 * @param xmlData
 * @param schemaFileName
 * @throws Exception Any exception
 */
public static void assertXMLValid(final String xmlData) throws Exception {
    logger.info("### assertXMLValid ###");
    if (xmlData == null) {
        throw new IllegalArgumentException(TestBase.class.getSimpleName() + ":assertXMLValid:xmlData is null");
    }
    if (schemas == null) {
        initializeSchemas();
    }
    String nameSpace = getNameSpaceFromXml(xmlData);
    logger.info("Looking up namespace '" + nameSpace + "'");
    Schema schema = schemas.get(nameSpace);

    try {
        Validator validator = schema.newValidator();
        InputStream in = new ByteArrayInputStream(xmlData.getBytes("UTF-8"));
        validator.validate(new SAXSource(new InputSource(in)));
    } catch (SAXParseException e) {
        e.printStackTrace();
        StringBuffer sb = new StringBuffer();
        sb.append("XML invalid at line:" + e.getLineNumber() + ", column:" + e.getColumnNumber() + "\n");
        sb.append("SAXParseException message: " + e.getMessage() + "\n");
        sb.append("Affected XML: \n" + xmlData);
        fail(sb.toString());
    }
}