Пример #1
0
        public void XmlToJsonConverterDoesNotRemovetheRootNodeWhenOmitRootObjectIsSetToTrue()
        {
            //Arrange
            IBaseMessage inputMessage =
                PTL.MessageHelper.CreateFromStream(MessageHelper.LoadMessage("PurchaseOrderWithOutNamespace.xml"));
            var xmlToJsonConverter = new XmlToJsonConverter {
                OmitRootObject = false
            };

            PTL.SendPipelineWrapper testPipelineWrapper = PTL.PipelineFactory.CreateEmptySendPipeline();
            testPipelineWrapper.AddComponent(xmlToJsonConverter, PTL.PipelineStage.Encode);
            //Act
            IBaseMessage outputMessages = testPipelineWrapper.Execute(inputMessage);

            //Assert
            Assert.IsTrue(outputMessages.BodyPart.Data.Position == 0, "The stream position should be zero");
            var     rdr    = new StreamReader(outputMessages.BodyPart.Data);
            string  outMsg = rdr.ReadToEnd();
            JObject json   = JObject.Parse(outMsg);

            Assert.IsNotNull(json);
            JToken po = json.SelectToken("PO");

            Assert.IsTrue(System.String.CompareOrdinal(po.SelectToken("poNum").Value <string>(), "poNum_0") == 0);
        }
        public void throwsBadXmlFormatExceptionOnBadXmlInput()
        {
            const string testSample = "<foo>hello</bar>";
            var          converter  = new XmlToJsonConverter();

            converter.Convert(testSample);
        }
Пример #3
0
        /// <summary>
        /// Формирует один большой файл JSON  с рабочиим классами
        /// </summary>
        /// <param name="context"></param>
        public override void Execute(IBSharpContext context)
        {
            Project.Log.Info("start generate json module");
            using (var sw = new StreamWriter(OutFileName)) {
                sw.Write("[");
                var tojson            = new XmlToJsonConverter();
                var notformatedBuffer = new StringWriter();
                var formattedBuffer   = new StringWriter();
                foreach (var cls in context.Get(BSharpContextDataType.LibPkg))
                {
                    var converted = tojson.ConvertToJson(cls.Compiled, false);
                    notformatedBuffer.Write(converted);
                    converted = tojson.ConvertToJson(cls.Compiled, true);
                    formattedBuffer.Write(",");
                    formattedBuffer.Write(converted);
                }
                var hashbase = notformatedBuffer.ToString();
                var content  = formattedBuffer.ToString();

                sw.Write(tojson.ConvertToJson(new XElement(BSharpSyntax.Class,
                                                           new XAttribute("code", "__module"),
                                                           new XAttribute("fullcode", "__module"),
                                                           new XAttribute("prototype", "__sys"),
                                                           new XAttribute("hash", Convert.ToBase64String(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(hashbase)))),
                                                           new XAttribute("timestamp", (DateTime.Now - new DateTime(2000, 1, 1)).TotalMilliseconds),
                                                           new XAttribute("user", Application.Current.Principal.CurrentUser.Identity.Name),
                                                           new XAttribute("host", Environment.MachineName)
                                                           ), true));
                sw.Write(content);
                sw.Write("]");
                sw.Flush();
            }
            Project.Log.Info("finish generate json module");
        }
Пример #4
0
        static void Main(string[] args)
        {
            PreloadAllAssemblies();
            Init();

            Console.WriteLine("Attente d'un message dans la file d'attente");

            _inputQueueService.Receive <string>((message) =>
            {
                Console.WriteLine("un message a été reçu, démarrage du traitement");

                //1°) Conversion vers Json
                var json = new XmlToJsonConverter().ConvertToJson(message);

                //2°) Mapping Produit
                var data = _dataMapper.MapData(json);

                //3°) Import dans le repository
                _dataRepo.ImportData(data);

                //5°) Mettre en file d'attente le message
                _outputQueueService.Enqueue(json).Wait();

                return(MessageProcessResponse.Complete);
            }, (ex) =>
            {
                Console.WriteLine($"Attention une erreur a été rencontrée : {ex}");
            }, () => { Task.Delay(100).Wait(); });

            Console.WriteLine("press key to exit");
            Console.ReadKey();
        }
Пример #5
0
        public void XmlToJsonExecuteTest()
        {
            var xmlToJsonConverter = new XmlToJsonConverter
            {
                TypeName = "Root"
            };

            var testMessage = new TestMessage
            {
                ContentType = new ContentType("application/xml"),
                Data        = GetXmlStream()
            };


            IMessageInspectorContext context = new StubIMessageInspectorContext
            {
                TracerGet = () => new StubITracer(),
            };

            Task task = xmlToJsonConverter.Execute(testMessage, context);

            task.Wait();
            Assert.IsTrue(task.IsCompleted);


            var     rdr    = new StreamReader(testMessage.Data);
            string  outMsg = rdr.ReadToEnd();
            JObject json   = JObject.Parse(outMsg);

            Assert.IsNotNull(json);
            JToken po = json.SelectToken("person");

            Assert.IsTrue(String.CompareOrdinal(po.SelectToken("name").Value <string>(), "Demo2") == 0);
        }
Пример #6
0
        public void XmlToJsonTestNullParam()
        {
            string xmlstring = null;
            string json      = XmlToJsonConverter.XmlToJson(xmlstring);

            Assert.AreEqual(json, @"Bad Xml format");
        }
Пример #7
0
        public void XmlToJsonTestBadFormat()
        {
            string xmlstring = "<root><item>test</item>";
            string json      = XmlToJsonConverter.XmlToJson(xmlstring);

            Assert.AreEqual(json, @"Bad Xml format");
        }
Пример #8
0
        public void BugInEscapeInLiteral()
        {
            var json = new XmlToJsonConverter().ConvertToJson(XElement.Parse("<value __jsontype=\"String\">str\n</value>"));

            Console.WriteLine(json);
            Assert.AreEqual("\"str\\n\"", json);
        }
Пример #9
0
        public void XmlToJsonTest()
        {
            string xmlstring = "<root><item>test</item></root>";
            string json      = XmlToJsonConverter.XmlToJson(xmlstring);

            json = json.Replace("\r\n", "").Replace(" ", ""); //remove formating
            Assert.AreEqual(json, @"{""root"":{""item"":""test""}}");
        }
        public string XmlToJson(string xml)
        {
            string             result             = null;
            XmlToJsonConverter xmlToJsonConverter = new XmlToJsonConverter();

            result = xmlToJsonConverter.ConvertXmlToJson(xml);
            return(result);
        }
Пример #11
0
        public void When_Format_Is_Valid_Must_Return_JSON_format()
        {
            string expected = "{\"TRANS\":{\"HPAY\":{\"ID\":\"103\",\"STATUS\":\"3\",\"EXTRA\":{\"IS3DS\":\"0\",\"AUTH\":\"031183\"},\"INT_MSG\":null,\"MLABEL\":\"501767XXXXXX6700\",\"MTOKEN\":\"project01\"}}}";
            string xmlInput = "<TRANS><HPAY><ID>103</ID><STATUS>3</STATUS><EXTRA><IS3DS>0</IS3DS><AUTH>031183</AUTH></EXTRA><INT_MSG/><MLABEL>501767XXXXXX6700</MLABEL><MTOKEN>project01</MTOKEN></HPAY></TRANS>";
            string actual   = new XmlToJsonConverter().ConvertXmlToJson(xmlInput);


            Assert.AreEqual(expected, actual);
        }
Пример #12
0
        public void When_Format_Is_Not_Valid_Must_Return_Bad_Xml_format()
        {
            string expected = "Bad Xml format";
            string xmlInput = "<foo>hello</bar>";
            string actual   = new XmlToJsonConverter().ConvertXmlToJson(xmlInput);


            Assert.AreEqual(expected, actual);
        }
Пример #13
0
        public void When_Format_Is_Valid_Must_Return_JSON_Format()
        {
            string expected = "{\"foo\":\"bar\"}";
            string xmlInput = "<foo>bar</foo>";
            string actual   = new XmlToJsonConverter().ConvertXmlToJson(xmlInput);


            Assert.AreEqual(expected, actual);
        }
        public void testEmpty()
        {
            TestUtils.WriteFile("xmltojson.xml", @"<root />");

            XmlToJsonConverter converter = new XmlToJsonConverter();

            converter.convert("xmltojson.xml", "xmltojson.json");

            Assert.Equal(@"{""root"":null}", TestUtils.ReadFile("xmltojson.json").Replace("\r\n", "").Replace("  ", ""));
        }
        public void canConvertXmlString()
        {
            const string sampleXmlString = "<foo>bar</foo>";

            var converter = new XmlToJsonConverter();

            var result = converter.Convert(sampleXmlString);

            Assert.AreEqual(removeAllBlanks(@"{ ""foo"" : ""bar"" }"), removeAllBlanks(result));
        }
        public void testDataTypes()
        {
            TestUtils.WriteFile("xmltojson.xml", @"<root><field1>b</field1><field2>33</field2><field3>-22.5</field3><field4>false</field4></root>");

            XmlToJsonConverter converter = new XmlToJsonConverter();

            converter.convert("xmltojson.xml", "xmltojson.json");

            Assert.Equal(@"{""root"":{""field1"":""b"",""field2"":""33"",""field3"":""-22.5"",""field4"":""false""}}", TestUtils.ReadFile("xmltojson.json").Replace("\r\n", "").Replace("  ", ""));
        }
Пример #17
0
        private static void BaseTest(string literal)
        {
            var xml = new JsonParser().ParseXml(literal);

            Console.WriteLine(xml);
            var json = new XmlToJsonConverter().ConvertToJson(xml);

            json = Simplify(json);
            Console.WriteLine(json);
            Assert.AreEqual(Simplify(literal), json);
        }
        public void testCycleConvertation()
        {
            TestUtils.WriteFile("jsontoxml.json", @"{""root"":{ ""field1"":""b"", ""field2"" : 33, ""field3"" : -22.5, ""field4"" : false }}");

            JsonToXmlConverter converter  = new JsonToXmlConverter();
            XmlToJsonConverter converter1 = new XmlToJsonConverter();

            converter.convert("jsontoxml.json", "jsontoxml.xml");
            converter1.convert("jsontoxml.xml", "jsontoxml.json");

            Assert.Equal(@"{""root"":{""field1"":""b"",""field2"":""33"",""field3"":""-22.5"",""field4"":""false""}}", TestUtils.ReadFile("jsontoxml.json").Replace("\r\n", "").Replace("  ", ""));
        }
        public void testCycleConvertation()
        {
            TestUtils.WriteFile("xmltojson.xml", @"<root><field1>b</field1><field2>33</field2><field3>-22.5</field3><field4>false</field4></root>");

            JsonToXmlConverter converter  = new JsonToXmlConverter();
            XmlToJsonConverter converter1 = new XmlToJsonConverter();

            converter1.convert("xmltojson.xml", "xmltojson.json");
            converter.convert("xmltojson.json", "xmltojson.xml");

            Assert.Equal(@"<root><field1>b</field1><field2>33</field2><field3>-22.5</field3><field4>false</field4></root>", TestUtils.ReadFile("xmltojson.xml").Replace("\r\n", "").Replace("  ", ""));
        }
Пример #20
0
        public bool TryConvert(byte[] incomingBody, string contentType, string messageType, out byte[] convertedBody)
        {
            convertedBody = new byte[0];
            if (!TryParseMessageType(messageType, out var bodyType))
            {
                return(false);
            }
            switch (contentType)
            {
            case XmlToJsonConverter.ContentTypeConverter:
                return(TryConvert(() => XmlToJsonConverter.Convert(incomingBody, bodyType), out convertedBody));

            case JsonToXmlConverter.ContentTypeConverter:
                return(TryConvert(() => JsonToXmlConverter.Convert(incomingBody, bodyType), out convertedBody));

            default:
                return(false);
            }
        }
Пример #21
0
        public void XmlToJsonConverterPcDoesNotRemovesAtTheRateCharactersWhenRemoveAtTheRateCharIsSetToFalse()
        {
            //Arrange
            IBaseMessage inputMessage =
                PTL.MessageHelper.CreateFromStream(MessageHelper.LoadMessage("PurchaseOrder.xml"));
            var xmlToJsonConverter = new XmlToJsonConverter {
                RemoveAtTheRateChar = false
            };

            PTL.SendPipelineWrapper testPipelineWrapper = PTL.PipelineFactory.CreateEmptySendPipeline();
            testPipelineWrapper.AddComponent(xmlToJsonConverter, PTL.PipelineStage.Encode);
            //Act
            IBaseMessage outputMessages = testPipelineWrapper.Execute(inputMessage);

            //Assert
            Assert.IsTrue(outputMessages.BodyPart.Data.Position == 0, "The stream position should be zero");
            var    rdr    = new StreamReader(outputMessages.BodyPart.Data);
            string outMsg = rdr.ReadToEnd();

            Debug.WriteLine("Output Message: " + outMsg);
            Assert.IsTrue(outMsg.IndexOf('@', 0) > 0);
        }
        public void canConvertAcceptanceTestSample()
        {
            const string testSample     = "<TRANS><HPAY><ID>103</ID><STATUS>3</STATUS><EXTRA><IS3DS>0</IS3DS><AUTH>031183</AUTH></EXTRA><INT_MSG/><MLABEL>501767XXXXXX6700</MLABEL><MTOKEN>project01</MTOKEN></HPAY></TRANS>";
            const string expectedResult = @"{
  ""TRANS"": {
    ""HPAY"": {
      ""ID"": ""103"",
      ""STATUS"": ""3"",
      ""EXTRA"": {
        ""IS3DS"": ""0"",
        ""AUTH"": ""031183""
      },
      ""INT_MSG"": null,
      ""MLABEL"": ""501767XXXXXX6700"",
      ""MTOKEN"": ""project01""
    }
  }
}";
            var          converter      = new XmlToJsonConverter();

            var result = converter.Convert(testSample);

            Assert.AreEqual(removeAllBlanks(expectedResult), removeAllBlanks(result));
        }