예제 #1
0
        /// <summary>
        /// Parses the option file for option values.
        /// </summary>
        /// <param name="fileName"> The option file name (must be a xml file). </param>
        /// <exception cref="OptionException"> </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void parseOptionInstanceXMLfile(String fileName) throws org.maltparser.core.exception.MaltChainedException
        public virtual void parseOptionInstanceXMLfile(string fileName)
        {
            File file = new File(fileName);

            try
            {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder        db  = dbf.newDocumentBuilder();

                Element  root       = db.parse(file).DocumentElement;
                NodeList containers = root.getElementsByTagName("optioncontainer");
                Element  container;
                for (int i = 0; i < containers.Length; i++)
                {
                    container = (Element)containers.item(i);
                    parseOptionValues(container, i);
                }
            }
            catch (IOException e)
            {
                throw new OptionException("Can't find the file " + fileName + ". ", e);
            }
            catch (OptionException e)
            {
                throw new OptionException("Problem parsing the file " + fileName + ". ", e);
            }
            catch (ParserConfigurationException e)
            {
                throw new OptionException("Problem parsing the file " + fileName + ". ", e);
            }
            catch (SAXException e)
            {
                throw new OptionException("Problem parsing the file " + fileName + ". ", e);
            }
        }
예제 #2
0
        protected internal AbstractModelParser()
        {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            configureFactory(dbf);
            this.documentBuilderFactory = dbf;
        }
예제 #3
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void load(java.net.URL specModelURL) throws org.maltparser.core.exception.MaltChainedException
        public virtual void load(URL specModelURL)
        {
            try
            {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder        db  = dbf.newDocumentBuilder();
                Element root = null;

                root = db.parse(specModelURL.openStream()).DocumentElement;

                if (root == null)
                {
                    throw new FlowException("The flow chart system file '" + specModelURL.File + "' cannot be found. ");
                }

                readChartElements(root);
            }
            catch (IOException e)
            {
                throw new FlowException("The flow chart system file '" + specModelURL.File + "' cannot be found. ", e);
            }
            catch (ParserConfigurationException e)
            {
                throw new FlowException("Problem parsing the file " + specModelURL.File + ". ", e);
            }
            catch (SAXException e)
            {
                throw new FlowException("Problem parsing the file " + specModelURL.File + ". ", e);
            }
        }
예제 #4
0
        /// <summary>
        /// Loads The XML document.
        /// </summary>
        /// <param name="in">
        ///            is the input stream. </param>
        /// <exception cref="DOMLoaderException">
        ///             DOM loader exception. </exception>
        /// <returns> The loaded document. </returns>
        // XXX: fix error reporting
        public virtual Document load(System.IO.Stream @in)
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            factory.NamespaceAware = true;
            factory.Validating     = _validating;

            try
            {
                DocumentBuilder builder = factory.newDocumentBuilder();

                // if(_validating) {
                builder.ErrorHandler = new ErrorHandlerAnonymousInnerClass(this);
                // }
                return(builder.parse(@in));
            }
            catch (SAXException e)
            {
                throw new DOMLoaderException("SAX exception: " + e.Message);
            }
            catch (ParserConfigurationException e)
            {
                throw new DOMLoaderException("Parser configuration exception: " + e.Message);
            }
            catch (IOException e)
            {
                throw new DOMLoaderException("IO exception: " + e.Message);
            }
        }
예제 #5
0
        public static Document LoadXML(string path)
        {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            dbf.setNamespaceAware(true);
            return(dbf.newDocumentBuilder().parse(new BufferedInputStream(new FileInputStream(path))));
        }
예제 #6
0
        private Document LoadXML(string path)
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            factory.setNamespaceAware(true);
            return(factory.newDocumentBuilder().parse(new BufferedInputStream(new FileInputStream(path))));
        }
예제 #7
0
        private static DocumentBuilder newDocumentBuilder()
        {
            var factory = DocumentBuilderFactory.newInstance();

            factory.setNamespaceAware(true);
            return(factory.newDocumentBuilder());
        }
예제 #8
0
        public void Sign(string unsignedXmlPath, string signedXmlPath, string pfxPath, string pfxPassword)
        {
            PrivateKey      privateKey;
            Provider        provider;
            X509Certificate certificate = _LoadCertificate(pfxPath, pfxPassword, out privateKey, out provider);

            if (certificate != null)
            {
                TrustFactory.instance             = es.mityc.javasign.trust.TrustExtendFactory.newInstance();
                TrustFactory.truster              = es.mityc.javasign.trust.MyPropsTruster.getInstance();
                PoliciesManager.POLICY_SIGN       = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager();
                PoliciesManager.POLICY_VALIDATION = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager();

                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true);
                Document unsignedDocument = dbf.newDocumentBuilder().parse(new BufferedInputStream(new FileInputStream(unsignedXmlPath)));

                DataToSign dataToSign = new DataToSign();
                dataToSign.setXadesFormat(EnumFormatoFirma.XAdES_BES);
                dataToSign.setEsquema(XAdESSchemas.XAdES_132);
                dataToSign.setPolicyKey("facturae31");
                dataToSign.setAddPolicy(true);
                dataToSign.setXMLEncoding("UTF-8");
                dataToSign.setEnveloped(true);
                dataToSign.addObject(new ObjectToSign(new AllXMLToSign(), "Description", null, "text/xml", null));
                dataToSign.setDocument(unsignedDocument);

                Object[] res = new FirmaXML().signFile(certificate, dataToSign, privateKey, provider);

                UtilidadTratarNodo.saveDocumentToOutputStream((Document)res[0], new FileOutputStream(signedXmlPath), true);
            }
        }
예제 #9
0
        public static void init()
        {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

            documentBuilderFactory.IgnoringElementContentWhitespace = true;
            documentBuilderFactory.IgnoringComments = true;
            documentBuilderFactory.Coalescing       = true;
            try
            {
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document        document        = documentBuilder.parse(typeof(PreDecrypt).getResourceAsStream("PreDecrypt.xml"));
                Element         configuration   = document.DocumentElement;
                load(configuration);
            }
            catch (ParserConfigurationException e)
            {
                Console.WriteLine(e);
            }
            catch (SAXException e)
            {
                Console.WriteLine(e);
            }
            catch (IOException e)
            {
                Console.WriteLine(e);
            }
        }
예제 #10
0
        public virtual void discover(string descriptionUrl)
        {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

            documentBuilderFactory.IgnoringElementContentWhitespace = true;
            documentBuilderFactory.IgnoringComments = true;
            documentBuilderFactory.Coalescing       = true;

            try
            {
                URL             url             = new URL(descriptionUrl);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document        description     = documentBuilder.parse(url.openStream());
                parseIGDdata(description);
                this.descriptionUrl = descriptionUrl;
            }
            catch (ParserConfigurationException e)
            {
                Console.WriteLine("Discovery", e);
            }
            catch (SAXException e)
            {
                Console.WriteLine("Discovery", e);
            }
            catch (MalformedURLException e)
            {
                Console.WriteLine("Discovery", e);
            }
            catch (IOException e)
            {
                Console.WriteLine("Discovery", e);
            }
        }
예제 #11
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void load(java.net.URL url, PropagationSpecs propagationSpecs) throws org.maltparser.core.exception.MaltChainedException
        public virtual void load(URL url, PropagationSpecs propagationSpecs)
        {
            try
            {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder        db  = dbf.newDocumentBuilder();
                Element root = null;

                root = db.parse(url.openStream()).DocumentElement;

                if (root == null)
                {
                    throw new PropagationException("The propagation specification file '" + url.File + "' cannot be found. ");
                }

                readPropagationSpecs(root, propagationSpecs);
            }
            catch (IOException e)
            {
                throw new PropagationException("The propagation specification file '" + url.File + "' cannot be found. ", e);
            }
            catch (ParserConfigurationException e)
            {
                throw new PropagationException("Problem parsing the file " + url.File + ". ", e);
            }
            catch (SAXException e)
            {
                throw new PropagationException("Problem parsing the file " + url.File + ". ", e);
            }
        }
예제 #12
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void load(java.net.URL specModelURL, org.maltparser.core.feature.spec.SpecificationModels featureSpecModels) throws org.maltparser.core.exception.MaltChainedException
        public virtual void load(URL specModelURL, SpecificationModels featureSpecModels)
        {
            try
            {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder        db  = dbf.newDocumentBuilder();
                Element root = null;

                root = db.parse(specModelURL.openStream()).DocumentElement;

                if (root == null)
                {
                    throw new FeatureException("The feature specification file '" + specModelURL.File + "' cannot be found. ");
                }

                readFeatureModels(root, featureSpecModels);
            }
            catch (IOException e)
            {
                throw new FeatureException("The feature specification file '" + specModelURL.File + "' cannot be found. ", e);
            }
            catch (SAXParseException e)
            {
                throw new FeatureException("Problem parsing the feature specification XML-file " + specModelURL.File + ". ", e);
            }
            catch (ParserConfigurationException e)
            {
                throw new FeatureException("Problem parsing the feature specification XML-file " + specModelURL.File + ". ", e);
            }
            catch (SAXException e)
            {
                throw new FeatureException("Problem parsing the feature specification XML-file " + specModelURL.File + ". ", e);
            }
        }
예제 #13
0
        protected void read(string file)
        {
            try
            {
                string rootDir = "";
                try
                {
                    rootDir =
                        getClass().getProtectionDomain().getCodeSource().getLocation().getPath().replace("%20", " ");
                    rootDir = new File(rootDir).getParent();
                }
                catch (Exception e)
                {
                    //throw e;
                }

                file = rootDir + FileUtils.FILE_SEPARATOR + file;

                DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document        doc        = docBuilder.parse(new File(file));
                doc.getDocumentElement().normalize();
                NodeList childNodes = doc.getChildNodes();

                parameters.clear();
                for (int s = 0; s < childNodes.getLength(); s++)
                {
                    Node item = childNodes.item(s);
                    if (item.getNodeType() == Node.ELEMENT_NODE)
                    {
                        Element  element = (Element)item;
                        NodeList tagName = element.getElementsByTagName("port");
                        parameters.put("port", tagName.item(0).getChildNodes().item(0).getNodeValue().trim());
                    }
                }
            }
            catch (SAXParseException err)
            {
                Console.Out.WriteLine("parsing error");
            }
            catch (ParserConfigurationException e)
            {
                Console.Out.WriteLine("configuration error");
            }
            catch (SAXException e)
            {
                Console.Out.WriteLine("general sax parser error");
            }
            catch (IOException e)
            {
                Console.Out.WriteLine("config file error");
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("general parser error");
            }
        }
예제 #14
0
        public static Document Erp90w(string path)
        {
            SAXParserFactoryImpl   sAXParserFactoryImpl   = new SAXParserFactoryImpl();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

            documentBuilderFactory.setNamespaceAware(true);
            Document document = documentBuilderFactory.newDocumentBuilder().parse(new BufferedInputStream(new FileInputStream(path)));

            return(document);
        }
예제 #15
0
 /// <summary>
 /// Create a new prefs XML document.
 /// </summary>
 private static Document CreatePrefsDoc(String qname)
 {
     try
     {
         DOMImplementation di = DocumentBuilderFactory.newInstance().newDocumentBuilder().DOMImplementation;
         DocumentType      dt = di.createDocumentType(qname, null, PREFS_DTD_URI);
         return(di.createDocument(null, qname, dt));
     }
     catch (ParserConfigurationException e)
     {
         throw new AssertionError(e);
     }
 }
예제 #16
0
        public static void firmar(string Archivo)
        {
            string     path = @"C:\Firma\fabricio_fortunato_mero_mosquera.p12";
            PrivateKey privatekey;
            Provider   provider;

            java.security.cert.X509Certificate certificate = LayerLogic.ClassLibrary.Complementos.Firmar.loadCertificate(path, "FFmm_1978", out privatekey, out provider);
            if (certificate != null)
            {
                //Creamos el documento a firmar
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true);
                DocumentBuilder db = dbf.newDocumentBuilder();

                //C#
                var    base64 = System.Convert.FromBase64String(Archivo);
                string bytes  = System.Text.Encoding.UTF8.GetString(base64);

                ByteArrayInputStream bs        = new ByteArrayInputStream(System.Text.Encoding.UTF8.GetBytes(bytes));
                Document             documento = dbf.newDocumentBuilder().parse(bs);
                //Creamos datos a firmar

                DataToSign dataToSign = new DataToSign();
                dataToSign.setXadesFormat(EnumFormatoFirma.XAdES_BES); //XAdES-EPES
                dataToSign.setAddPolicy(false);
                dataToSign.setXMLEncoding(encoding);
                dataToSign.setEnveloped(true);
                dataToSign.addObject(new ObjectToSign(new InternObjectToSign(nodoFirma), "comprobante", null, "text/xml", null));
                dataToSign.setParentSignNode(nodoFirma);
                //dataToSign.setDocument(LoadXML(NombreArchivo));
                dataToSign.setDocument(documento);

                //Firmar
                Object[] res = new FirmaXML().signFile(certificate, dataToSign, privatekey, provider);

                Document doc = (Document)res[0];
                //Transformar a string
                org.w3c.dom.ls.DOMImplementationLS domImplementation = (org.w3c.dom.ls.DOMImplementationLS)doc.getImplementation();
                org.w3c.dom.ls.LSSerializer        lsSerializer      = domImplementation.createLSSerializer();
                Archivo = lsSerializer.writeToString(doc).Replace("UTF-16", "UTF-8");

                //C#

                var    ArchivoFirmado = Encoding.UTF8.GetBytes(Archivo);
                string firmado        = Convert.ToBase64String(ArchivoFirmado);

                var    base642 = System.Convert.FromBase64String(firmado);
                string bytes2  = System.Text.Encoding.UTF8.GetString(base642);
            }
        }
예제 #17
0
        /// <summary>
        /// Parse a XML file that contains the options used for controlling the application. The method
        /// calls the parseOptionGroups to parse the set of option groups in the DOM tree.
        /// </summary>
        /// <param name="url">	The path to a XML file that explains the options used in the application. </param>
        /// <exception cref="OptionException"> </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void parseOptionDescriptionXMLfile(java.net.URL url) throws org.maltparser.core.exception.MaltChainedException
        public virtual void parseOptionDescriptionXMLfile(URL url)
        {
            if (url == null)
            {
                throw new OptionException("The URL to the default option file is null. ");
            }

            try
            {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder        db  = dbf.newDocumentBuilder();

                Element  root   = db.parse(url.openStream()).DocumentElement;
                NodeList groups = root.getElementsByTagName("optiongroup");
                Element  group;
                for (int i = 0; i < groups.Length; i++)
                {
                    group = (Element)groups.item(i);
                    string      groupname = group.getAttribute("groupname").ToLower();
                    OptionGroup og        = null;
                    if (optionGroups.ContainsKey(groupname))
                    {
                        og = optionGroups[groupname];
                    }
                    else
                    {
                        optionGroups[groupname] = new OptionGroup(groupname);
                        og = optionGroups[groupname];
                    }
                    parseOptionsDescription(group, og);
                }
            }
            catch (java.io.IOException e)
            {
                throw new OptionException("Can't find the file " + url.ToString() + ".", e);
            }
            catch (OptionException e)
            {
                throw new OptionException("Problem parsing the file " + url.ToString() + ". ", e);
            }
            catch (ParserConfigurationException e)
            {
                throw new OptionException("Problem parsing the file " + url.ToString() + ". ", e);
            }
            catch (SAXException e)
            {
                throw new OptionException("Problem parsing the file " + url.ToString() + ". ", e);
            }
        }
예제 #18
0
        /// <summary>
        /// Obtener y transformar a la representación XML el parametro enviado como cadena
        /// </summary>
        /// <param name="xmlStr">Cadena a transformar</param>
        /// <returns>un objecto Document</returns>
        public static Document ConvertStringToDocument(String xmlStr)
        {
            DocumentBuilder db  = null;
            InputSource     iss = null;

            try
            {
                db  = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                iss = new InputSource();
                iss.setCharacterStream(new java.io.StringReader(xmlStr));
                return(db.parse(iss));
            } catch (Exception e) {
                LogUtil.Error(e);
            }

            return(null);
        }
예제 #19
0
        /*
         * parse and construct query objects in memory as soon as this class is loaded
         * in the JVM.
         */
        static QueryFileParser()
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            try
            {
                DocumentBuilder builder = factory.newDocumentBuilder();
                document = builder.parse(new File(ConfigurationXMLParser.getProperty("queryFilename")));
                parseQueryNodes();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error parsing query XML. Continuing...");
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }
        }
예제 #20
0
        private void Initialise()
        {
            Settings.Instance.registerSettingsListener("Compiler", "emu.ignoreInvalidMemoryAccess", new IgnoreInvalidMemoryAccessSettingsListerner(this));
            Settings.Instance.registerSettingsListener("Compiler", "emu.compiler.methodMaxInstructions", new MethodMaxInstructionsSettingsListerner(this));

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

            documentBuilderFactory.IgnoringElementContentWhitespace = true;
            documentBuilderFactory.IgnoringComments = true;
            documentBuilderFactory.Coalescing       = true;
            configuration = null;
            try
            {
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                configuration = documentBuilder.parse(new File("Compiler.xml"));
            }
            catch (ParserConfigurationException e)
            {
                Console.WriteLine(e);
            }
            catch (SAXException e)
            {
                Console.WriteLine(e);
            }
            catch (IOException e)
            {
                Console.WriteLine(e);
            }

            if (configuration != null)
            {
                nativeCodeManager = new NativeCodeManager(configuration.DocumentElement);
            }
            else
            {
                nativeCodeManager = new NativeCodeManager(null);
            }

            compilerTypeManager = new CompilerTypeManager();

            reset();
        }
예제 #21
0
        //read information from the XML as soon as the class is loaded into the JVM
        static ConfigurationXMLParser()
        {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

            try
            {
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                document = documentBuilder.parse(new File(Start.PathToDir + "config.xml"));
                try
                {
                    parseProperties();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error parsing properties from XML!");
                    Console.WriteLine(e.ToString());
                    Console.Write(e.StackTrace);
                    Environment.Exit(1);
                }
            }
            catch (ParserConfigurationException e)
            {
                Console.WriteLine("error parsing XML configuration!");
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
                Environment.Exit(1);
            }
            catch (SAXException e)
            {
                Console.WriteLine("error parsing XML configuration!");
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
                Environment.Exit(1);
            }
            catch (IOException e)
            {
                Console.WriteLine("error processing XML configuration file!");
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
                Environment.Exit(1);
            }
        }
예제 #22
0
        /// <summary>
        /// Load an XML document from specified input stream, which must
        /// have the requisite DTD URI.
        /// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static Document loadPrefsDoc(InputStream in) throws SAXException, IOException
        private static Document LoadPrefsDoc(InputStream @in)
        {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            dbf.IgnoringElementContentWhitespace = true;
            dbf.Validating       = true;
            dbf.Coalescing       = true;
            dbf.IgnoringComments = true;
            try
            {
                DocumentBuilder db = dbf.newDocumentBuilder();
                db.EntityResolver = new Resolver();
                db.ErrorHandler   = new EH();
                return(db.parse(new InputSource(@in)));
            }
            catch (ParserConfigurationException e)
            {
                throw new AssertionError(e);
            }
        }
예제 #23
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldWriteTransaction() throws javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException, java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void shouldWriteTransaction()
        {
            // given a model
            BpmnModelInstance newModel = Bpmn.createProcess("process").done();

            Process process = newModel.getModelElementById("process");

            Transaction transaction = newModel.newInstance(typeof(Transaction));

            transaction.Id     = "transaction";
            transaction.Method = TransactionMethod.Store;
            process.addChildElement(transaction);

            // that is written to a stream
            MemoryStream outStream = new MemoryStream();

            Bpmn.writeModelToStream(outStream, newModel);

            // when reading from that stream
            MemoryStream inStream = new MemoryStream(outStream.toByteArray());

            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder        docBuilder        = docBuilderFactory.newDocumentBuilder();
            Document actualDocument = docBuilder.parse(inStream);

            // then it possible to traverse to the transaction element and assert its attributes
            NodeList transactionElements = actualDocument.getElementsByTagName("transaction");

            assertThat(transactionElements.Length).isEqualTo(1);

            Node transactionElement = transactionElements.item(0);

            assertThat(transactionElement).NotNull;
            Node methodAttribute = transactionElement.Attributes.getNamedItem("method");

            assertThat(methodAttribute.NodeValue).isEqualTo("##Store");
        }
예제 #24
0
        private Document parseaDoc(InputStream fichero)
        {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder1 = (DocumentBuilder)null;
            DocumentBuilder documentBuilder2;

            try
            {
                documentBuilder2 = documentBuilderFactory.newDocumentBuilder();
            }
            catch (ParserConfigurationException ex)
            {
                int num = (int)XtraMessageBox.Show("Error al realizar validacion a documento = " + ex.toString());
                return((Document)null);
            }
            Document document = (Document)null;

            try
            {
                return(documentBuilder2.parse(fichero));
            }
            catch (SAXException ex)
            {
                document = (Document)null;
            }
            catch (System.IO.IOException ex)
            {
                int num = (int)XtraMessageBox.Show("Error al realizar validacion a documento = " + ex.ToString());
            }
            finally
            {
                documentBuilder1 = (DocumentBuilder)null;
            }
            return((Document)null);
        }
예제 #25
0
        protected internal virtual Dictionary <string, string> parseSimpleCommandResponse(string content)
        {
            Dictionary <string, string> result = null;

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

            documentBuilderFactory.IgnoringElementContentWhitespace = true;
            documentBuilderFactory.IgnoringComments = true;
            documentBuilderFactory.Coalescing       = true;

            try
            {
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document        response        = documentBuilder.parse(new System.IO.MemoryStream(content.GetBytes()));
                result = new Dictionary <string, string>();
                parseElement(response.DocumentElement, result, null);
            }
            catch (ParserConfigurationException e)
            {
                Console.WriteLine("Discovery", e);
            }
            catch (SAXException e)
            {
                Console.WriteLine("Discovery", e);
            }
            catch (MalformedURLException e)
            {
                Console.WriteLine("Discovery", e);
            }
            catch (IOException e)
            {
                Console.WriteLine("Discovery", e);
            }

            return(result);
        }
        public void parse()
        {
            DocumentBuilderFactory factory = null;
            DocumentBuilder        builder = null;
            Document document = null;

            factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true); //otherwise we can not act namespace independend, i.e. use document.getElementsByTagNameNS("*",...
            try
            {
                builder = factory.newDocumentBuilder();
            }
            catch (ParserConfigurationException ex3)
            {
                // TODO Auto-generated catch block
                ex3.printStackTrace();
            }
            try
            {
                InputStream bais = new ByteArrayInputStream(rawXML);
                document = builder.parse(bais);
            }
            catch (SAXException ex1)
            {
                ex1.printStackTrace();
            }
            catch (IOException ex2)
            {
                ex2.printStackTrace();
            }
            NodeList ndList;

            // rootNode = document.getDocumentElement();
            // ApplicableSupplyChainTradeSettlement
            ndList = document.getDocumentElement()
                     .getElementsByTagNameNS("*", "PaymentReference"); //$NON-NLS-1$
            for (int bookingIndex = 0; bookingIndex < ndList
                 .getLength(); bookingIndex++)
            {
                Node booking = ndList.item(bookingIndex);
                // if there is a attribute in the tag number:value
                setForeignReference(booking.getTextContent());
            }

            /*
             * ndList = document
             * .getElementsByTagName("GermanBankleitzahlID"); //$NON-NLS-1$
             * for (int bookingIndex = 0; bookingIndex < ndList
             * .getLength(); bookingIndex++) {
             * Node booking = ndList.item(bookingIndex);
             * // if there is a attribute in the tag number:value
             * setBIC(booking.getTextContent());
             * }
             * ndList = document.getElementsByTagName("ProprietaryID"); //$NON-NLS-1$
             * for (int bookingIndex = 0; bookingIndex < ndList
             * .getLength(); bookingIndex++) {
             * Node booking = ndList.item(bookingIndex);
             * // if there is a attribute in the tag number:value
             * setIBAN(booking.getTextContent());
             * }
             * <ram:PayeePartyCreditorFinancialAccount>
             * <ram:IBANID>DE1234</ram:IBANID>
             * </ram:PayeePartyCreditorFinancialAccount>
             * <ram:PayeeSpecifiedCreditorFinancialInstitution>
             * <ram:BICID>DE5656565</ram:BICID>
             * <ram:Name>Commerzbank</ram:Name>
             * </ram:PayeeSpecifiedCreditorFinancialInstitution>
             */
            ndList = document.getElementsByTagNameNS("*", "PayeePartyCreditorFinancialAccount"); //$NON-NLS-1$
            for (int bookingIndex = 0; bookingIndex < ndList
                 .getLength(); bookingIndex++)
            {
                Node booking = ndList.item(bookingIndex);
                // there are many "name" elements, so get the one below
                // SellerTradeParty
                NodeList bookingDetails = booking.getChildNodes();
                for (int detailIndex = 0; detailIndex < bookingDetails
                     .getLength(); detailIndex++)
                {
                    Node detail = bookingDetails.item(detailIndex);
                    if ((detail.getLocalName() != null) && (detail.getLocalName().Equals("IBANID")))
                    { //$NON-NLS-1$
                        setIBAN(detail.getTextContent());
                    }
                }
            }
            ndList = document.getElementsByTagNameNS("*", "PayeeSpecifiedCreditorFinancialInstitution"); //$NON-NLS-1$
            for (int bookingIndex = 0; bookingIndex < ndList
                 .getLength(); bookingIndex++)
            {
                Node booking = ndList.item(bookingIndex);
                // there are many "name" elements, so get the one below
                // SellerTradeParty
                NodeList bookingDetails = booking.getChildNodes();
                for (int detailIndex = 0; detailIndex < bookingDetails
                     .getLength(); detailIndex++)
                {
                    Node detail = bookingDetails.item(detailIndex);
                    if ((detail.getLocalName() != null) && (detail.getLocalName().Equals("BICID")))
                    { //$NON-NLS-1$
                        setBIC(detail.getTextContent());
                    }
                    if ((detail.getLocalName() != null) && (detail.getLocalName().Equals("Name")))
                    { //$NON-NLS-1$
                        setBankName(detail.getTextContent());
                    }
                }
            }
            //
            ndList = document.getElementsByTagNameNS("*", "SellerTradeParty"); //$NON-NLS-1$
            for (int bookingIndex = 0; bookingIndex < ndList
                 .getLength(); bookingIndex++)
            {
                Node booking = ndList.item(bookingIndex);
                // there are many "name" elements, so get the one below
                // SellerTradeParty
                NodeList bookingDetails = booking.getChildNodes();
                for (int detailIndex = 0; detailIndex < bookingDetails
                     .getLength(); detailIndex++)
                {
                    Node detail = bookingDetails.item(detailIndex);
                    if ((detail.getLocalName() != null) && (detail.getLocalName().Equals("Name")))
                    { //$NON-NLS-1$
                        setHolder(detail.getTextContent());
                    }
                }
            }
            ndList = document.getElementsByTagNameNS("*", "DuePayableAmount"); //$NON-NLS-1$
            for (int bookingIndex = 0; bookingIndex < ndList
                 .getLength(); bookingIndex++)
            {
                Node booking = ndList.item(bookingIndex);
                // if there is a attribute in the tag number:value
                amountFound = true;
                setAmount(booking.getTextContent());
            }
            if (!amountFound)
            {
                /* there is apparently no requirement to mention DuePayableAmount,,
                 * if it's not there, check for GrandTotalAmount
                 */
                ndList = document.getElementsByTagNameNS("*", "GrandTotalAmount"); //$NON-NLS-1$
                for (int bookingIndex = 0; bookingIndex < ndList
                     .getLength(); bookingIndex++)
                {
                    Node booking = ndList.item(bookingIndex);
                    // if there is a attribute in the tag number:value
                    amountFound = true;
                    setAmount(booking.getTextContent());
                }
            }
        }
예제 #27
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void parseDataFormatXMLfile(java.net.URL url) throws org.maltparser.core.exception.MaltChainedException
        public virtual void parseDataFormatXMLfile(URL url)
        {
            if (url == null)
            {
                throw new DataFormatException("The data format specifcation file cannot be found. ");
            }

            try
            {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder        db  = dbf.newDocumentBuilder();

                Element root = db.parse(url.openStream()).DocumentElement;
                if (root.NodeName.Equals("dataformat"))
                {
                    dataFormatName = root.getAttribute("name");
                    if (root.getAttribute("datastructure").length() > 0)
                    {
                        dataStructure = Enum.Parse(typeof(DataStructure), root.getAttribute("datastructure").ToUpper());
                    }
                    else
                    {
                        dataStructure = DataStructure.DEPENDENCY;
                    }
                }
                else
                {
                    throw new DataFormatException("Data format specification file must contain one 'dataformat' element. ");
                }
                NodeList cols = root.getElementsByTagName("column");
                Element  col  = null;
                for (int i = 0, n = cols.Length; i < n; i++)
                {
                    col = (Element)cols.item(i);
                    DataFormatEntry entry = new DataFormatEntry(col.getAttribute("name"), col.getAttribute("category"), col.getAttribute("type"), col.getAttribute("default"));
                    entries[entry.DataFormatEntryName] = entry;
                }
                NodeList deps = root.getElementsByTagName("dependencies");
                if (deps.Length > 0)
                {
                    NodeList dep = ((Element)deps.item(0)).getElementsByTagName("dependency");
                    for (int i = 0, n = dep.Length; i < n; i++)
                    {
                        Element e = (Element)dep.item(i);
                        dependencies.add(new Dependency(this, e.getAttribute("name"), e.getAttribute("url"), e.getAttribute("map"), e.getAttribute("urlmap")));
                    }
                }
            }
            catch (java.io.IOException e)
            {
                throw new DataFormatException("Cannot find the file " + url.ToString() + ". ", e);
            }
            catch (ParserConfigurationException e)
            {
                throw new DataFormatException("Problem parsing the file " + url.ToString() + ". ", e);
            }
            catch (SAXException e)
            {
                throw new DataFormatException("Problem parsing the file " + url.ToString() + ". ", e);
            }
        }
예제 #28
0
 /// <summary>
 /// Constructor for the <c>DocumentProvider</c> object. This
 /// is used to instantiate a parser factory that will be used to
 /// create parsers when requested. Instantiating the factory up
 /// front also checks that the framework is fully supported.
 /// </summary>
 public DocumentProvider()
 {
     this.factory = DocumentBuilderFactory.newInstance();
     this.factory.setNamespaceAware(true);
 }
예제 #29
0
        private OSMTagMapping(URL tagConf)
        {
            try
            {
                sbyte defaultZoomAppear;

                // ---- Parse XML file ----
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder        builder = factory.newDocumentBuilder();
                Document document = builder.parse(tagConf.openStream());

                XPath xpath = XPathFactory.newInstance().newXPath();

                XPathExpression xe = xpath.compile(XPATH_EXPRESSION_DEFAULT_ZOOM);
                defaultZoomAppear = sbyte.Parse((string)xe.evaluate(document, XPathConstants.STRING));

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.HashMap<Nullable<short>, java.util.Set<String>> tmpPoiZoomOverrides = new java.util.HashMap<>();
                Dictionary <short?, ISet <string> > tmpPoiZoomOverrides = new Dictionary <short?, ISet <string> >();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.HashMap<Nullable<short>, java.util.Set<String>> tmpWayZoomOverrides = new java.util.HashMap<>();
                Dictionary <short?, ISet <string> > tmpWayZoomOverrides = new Dictionary <short?, ISet <string> >();

                // ---- Get list of poi nodes ----
                xe = xpath.compile(XPATH_EXPRESSION_POIS);
                NodeList pois = (NodeList)xe.evaluate(document, XPathConstants.NODESET);

                for (int i = 0; i < pois.Length; i++)
                {
                    NamedNodeMap attributes = pois.item(i).Attributes;
                    string       key        = attributes.getNamedItem("key").TextContent;
                    string       value      = attributes.getNamedItem("value").TextContent;

                    string[] equivalentValues = null;
                    if (attributes.getNamedItem("equivalent-values") != null)
                    {
                        equivalentValues = attributes.getNamedItem("equivalent-values").TextContent.Split(",");
                    }

                    sbyte zoom = attributes.getNamedItem("zoom-appear") == null ? defaultZoomAppear : sbyte.Parse(attributes.getNamedItem("zoom-appear").TextContent);

                    bool renderable = attributes.getNamedItem("renderable") == null ? true : bool.Parse(attributes.getNamedItem("renderable").TextContent);

                    bool forcePolygonLine = attributes.getNamedItem("force-polygon-line") == null ? false : bool.Parse(attributes.getNamedItem("force-polygon-line").TextContent);

                    OSMTag osmTag = new OSMTag(this.poiID, key, value, zoom, renderable, forcePolygonLine);
                    if (this.stringToPoiTag.ContainsKey(osmTag.tagKey()))
                    {
                        LOGGER.warning("duplicate osm-tag found in tag-mapping configuration (ignoring): " + osmTag);
                        continue;
                    }
                    LOGGER.finest("adding poi: " + osmTag);
                    this.stringToPoiTag[osmTag.tagKey()] = osmTag;
                    if (equivalentValues != null)
                    {
                        foreach (string equivalentValue in equivalentValues)
                        {
                            this.stringToPoiTag[OSMTag.tagKey(key, equivalentValue)] = osmTag;
                        }
                    }
                    this.idToPoiTag[Convert.ToInt16(this.poiID)] = osmTag;

                    // also fill optimization mapping with identity
                    this.optimizedPoiIds[Convert.ToInt16(this.poiID)] = Convert.ToInt16(this.poiID);

                    // check if this tag overrides the zoom level spec of another tag
                    NodeList zoomOverrideNodes = pois.item(i).ChildNodes;
                    for (int j = 0; j < zoomOverrideNodes.Length; j++)
                    {
                        Node overriddenNode = zoomOverrideNodes.item(j);
                        if (overriddenNode is Element)
                        {
                            string        keyOverridden   = overriddenNode.Attributes.getNamedItem("key").TextContent;
                            string        valueOverridden = overriddenNode.Attributes.getNamedItem("value").TextContent;
                            ISet <string> s = tmpPoiZoomOverrides[Convert.ToInt16(this.poiID)];
                            if (s == null)
                            {
                                s = new HashSet <>();
                                tmpPoiZoomOverrides[Convert.ToInt16(this.poiID)] = s;
                            }
                            s.Add(OSMTag.tagKey(keyOverridden, valueOverridden));
                        }
                    }

                    this.poiID++;
                }

                // ---- Get list of way nodes ----
                xe = xpath.compile(XPATH_EXPRESSION_WAYS);
                NodeList ways = (NodeList)xe.evaluate(document, XPathConstants.NODESET);

                for (int i = 0; i < ways.Length; i++)
                {
                    NamedNodeMap attributes = ways.item(i).Attributes;
                    string       key        = attributes.getNamedItem("key").TextContent;
                    string       value      = attributes.getNamedItem("value").TextContent;

                    string[] equivalentValues = null;
                    if (attributes.getNamedItem("equivalent-values") != null)
                    {
                        equivalentValues = attributes.getNamedItem("equivalent-values").TextContent.Split(",");
                    }

                    sbyte zoom = attributes.getNamedItem("zoom-appear") == null ? defaultZoomAppear : sbyte.Parse(attributes.getNamedItem("zoom-appear").TextContent);

                    bool renderable = attributes.getNamedItem("renderable") == null ? true : bool.Parse(attributes.getNamedItem("renderable").TextContent);

                    bool forcePolygonLine = attributes.getNamedItem("force-polygon-line") == null ? false : bool.Parse(attributes.getNamedItem("force-polygon-line").TextContent);

                    OSMTag osmTag = new OSMTag(this.wayID, key, value, zoom, renderable, forcePolygonLine);
                    if (this.stringToWayTag.ContainsKey(osmTag.tagKey()))
                    {
                        LOGGER.warning("duplicate osm-tag found in tag-mapping configuration (ignoring): " + osmTag);
                        continue;
                    }
                    LOGGER.finest("adding way: " + osmTag);
                    this.stringToWayTag[osmTag.tagKey()] = osmTag;
                    if (equivalentValues != null)
                    {
                        foreach (string equivalentValue in equivalentValues)
                        {
                            this.stringToWayTag[OSMTag.tagKey(key, equivalentValue)] = osmTag;
                        }
                    }
                    this.idToWayTag[Convert.ToInt16(this.wayID)] = osmTag;

                    // also fill optimization mapping with identity
                    this.optimizedWayIds[Convert.ToInt16(this.wayID)] = Convert.ToInt16(this.wayID);

                    // check if this tag overrides the zoom level spec of another tag
                    NodeList zoomOverrideNodes = ways.item(i).ChildNodes;
                    for (int j = 0; j < zoomOverrideNodes.Length; j++)
                    {
                        Node overriddenNode = zoomOverrideNodes.item(j);
                        if (overriddenNode is Element)
                        {
                            string        keyOverridden   = overriddenNode.Attributes.getNamedItem("key").TextContent;
                            string        valueOverridden = overriddenNode.Attributes.getNamedItem("value").TextContent;
                            ISet <string> s = tmpWayZoomOverrides[Convert.ToInt16(this.wayID)];
                            if (s == null)
                            {
                                s = new HashSet <>();
                                tmpWayZoomOverrides[Convert.ToInt16(this.wayID)] = s;
                            }
                            s.Add(OSMTag.tagKey(keyOverridden, valueOverridden));
                        }
                    }

                    this.wayID++;
                }

                // copy temporary values from zoom-override data sets
                foreach (KeyValuePair <short?, ISet <string> > entry in tmpPoiZoomOverrides.SetOfKeyValuePairs())
                {
                    ISet <OSMTag> overriddenTags = new HashSet <OSMTag>();
                    foreach (string tagString in entry.Value)
                    {
                        OSMTag tag = this.stringToPoiTag[tagString];
                        if (tag != null)
                        {
                            overriddenTags.Add(tag);
                        }
                    }
                    if (overriddenTags.Count > 0)
                    {
                        this.poiZoomOverrides[entry.Key] = overriddenTags;
                    }
                }

                foreach (KeyValuePair <short?, ISet <string> > entry in tmpWayZoomOverrides.SetOfKeyValuePairs())
                {
                    ISet <OSMTag> overriddenTags = new HashSet <OSMTag>();
                    foreach (string tagString in entry.Value)
                    {
                        OSMTag tag = this.stringToWayTag[tagString];
                        if (tag != null)
                        {
                            overriddenTags.Add(tag);
                        }
                    }
                    if (overriddenTags.Count > 0)
                    {
                        this.wayZoomOverrides[entry.Key] = overriddenTags;
                    }
                }

                // ---- Error handling ----
            }
            catch (SAXParseException spe)
            {
                LOGGER.severe("\n** Parsing error, line " + spe.LineNumber + ", uri " + spe.SystemId);
                throw new System.InvalidOperationException(spe);
            }
            catch (SAXException sxe)
            {
                throw new System.InvalidOperationException(sxe);
            }
            catch (ParserConfigurationException pce)
            {
                throw new System.InvalidOperationException(pce);
            }
            catch (IOException ioe)
            {
                throw new System.InvalidOperationException(ioe);
            }
            catch (XPathExpressionException e)
            {
                throw new System.InvalidOperationException(e);
            }
        }