public static void Main(string[] args) { Book abook = new Book(); //Here's an instance of our type to serialize abook.setAuthorName("Michael Feathers"); abook.setBookID(1337); abook.setTitle("Working Effectively with Legacy Code"); // // SimplTypesScope book_example_sts = new SimplTypesScope("book_example", typeof(Book)); //Serialize to JSON String jsonResult = SimplTypesScope.Serialize(abook, StringFormat.Json); //Serialize to XML // (Just change the StringFormat parameter!) String xmlResult = SimplTypesScope.Serialize(abook, StringFormat.Xml); Object result1 = book_example_sts.Deserialize(jsonResult, StringFormat.Json); Book r1 = (Book)result1; Object result2 = book_example_sts.Deserialize(xmlResult, StringFormat.Xml); Book r2 = (Book)result2; Console.WriteLine(jsonResult); Console.WriteLine(xmlResult); Console.ReadLine(); }
/// <summary> /// /// </summary> /// <param name="inputSimplTypesScope"></param> /// <param name="inputContext"></param> /// <param name="hookStrategy"></param> protected PullDeserializer(SimplTypesScope inputSimplTypesScope, TranslationContext inputContext, IDeserializationHookStrategy hookStrategy) { simplTypesScope = inputSimplTypesScope; translationContext = inputContext; deserializationHookStrategy = hookStrategy; }
public void OnMetadataExtracted(object sender, JSCallbackEventArgs args) { if (args.Arguments.Length == 0) { Console.WriteLine("No value returned"); return; } JSValue value = args.Arguments[0]; String metadataJSON = value.ToString(); //Console.WriteLine(metadataJSON); Console.WriteLine("Extraction time : " + DateTime.Now.Subtract(parseStart).TotalMilliseconds); Console.WriteLine("Done getting value. Serializing JSON string to ElementState."); TranslationContext context = new TranslationContext(); context.SetUriContext(_puri); SimplTypesScope metadataTScope = SemanticsSessionScope.MetadataTranslationScope; Document myShinyNewMetadata = (Document)metadataTScope.Deserialize(metadataJSON, context, new MetadataDeserializationHookStrategy(SemanticsSessionScope), StringFormat.Json); Console.WriteLine("Extraction time including page load and deserialization: " + DateTime.Now.Subtract(timeStart).TotalMilliseconds); _webView.LoadCompleted -= WebView_LoadCompleted; SemanticsSessionScope.GlobalDocumentCollection.AddDocument(myShinyNewMetadata, _puri); SemanticsSessionScope.WebBrowserPool.Release(_webView); _requestTimedOut.Stop(); _closure.TaskCompletionSource.TrySetResult(myShinyNewMetadata); }
private async void BtnGetMetadata_Click(object sender, RoutedEventArgs e) { // string serializedMetadata = UrlBox.Text; // Object o = RepositoryMetadataTranslationScope.Get().Deserialize(serializedMetadata, StringFormat.Xml); // StringBuilder sb = new StringBuilder(); // SimplTypesScope.Serialize(o, sb, StringFormat.Xml); // String reserializedMetadatata = sb.ToString(); // Console.WriteLine(reserializedMetadatata); //Expander expander = new Expander(); //TextBox metadataXML = new TextBox { TextWrapping = TextWrapping.Wrap, MinHeight = 100 }; //metadataXML.Text = reserializedMetadatata; string urls = UrlBox.Text; List <Task <Document> > extractionRequests = new List <Task <Document> >(); Dictionary <ParsedUri, DateTime> timeStamps = new Dictionary <ParsedUri, DateTime>(); foreach (var s in urls.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)) { Console.WriteLine("Requesting async extraction of: " + s); ParsedUri puri = new ParsedUri(s); { Task <Document> t = _semanticsSessionScope.GetDocument(puri); timeStamps.Add(puri, DateTime.Now); //Alternate, if you want the document here: //Document doc = await _semanticsSessionScope.GetDocument(puri); extractionRequests.Add(t); } } while (extractionRequests.Count > 0) { Task <Document> completedTask = await Task.WhenAny(extractionRequests); extractionRequests.Remove(completedTask); Document parsedDoc = await completedTask; if (parsedDoc == null) { continue; } Expander expander = new Expander { Header = parsedDoc.Title }; TextBox metadataXML = new TextBox { TextWrapping = TextWrapping.Wrap, MinHeight = 100 }; var s = timeStamps[parsedDoc.Location.Value]; Console.WriteLine(" ---------------------------------- Time to complete: " + DateTime.Now.Subtract(s).TotalMilliseconds); metadataXML.Text = await Task.Run(() => SimplTypesScope.Serialize(parsedDoc, StringFormat.Xml)); expander.Content = metadataXML; MetadataTitleXMLContainer.Children.Add(expander); } }
public void BeforeSemanticOperationTest()// throws SIMPLTranslationException { // test FilterLocation.paramOps & alternativeHosts String url1 = "http://dl.acm.org/citation.cfm?id=2063231.2063237&coll=DL"; // test FilterLocation.stripPrefix String url2 = "http://www.amazon.co.uk/gp/bestsellers/books/515344/ref=123"; // test FilterLocation.Regex // added in file products.xml in meta_metadata name="amazon_bestseller_list": // <before_semantic_actions> // <filter_location> // <regex match="http://([w]+)\.amazon\.com/gp" replace="http://t$1.gstatic.com/images" /> // </filter_location> // </before_semantic_actions> String url3 = "http://www.amazon.com/gp/bestsellers/books/6"; SimplTypesScope _repositoryMetadataTranslationScope = RepositoryMetadataTranslationScope.Get(); SemanticsGlobalScope _semanticsSessionScope = new SemanticsSessionScope( _repositoryMetadataTranslationScope, MetaMetadataRepositoryInit.DEFAULT_REPOSITORY_LOCATION); Document metadata = _semanticsSessionScope.GetOrConstructDocument(new ParsedUri(url1)); MetaMetadata metaMetadata = (MetaMetadata)metadata.MetaMetadata; SemanticOperationHandler handler = new SemanticOperationHandler(_semanticsSessionScope, null); handler.TakeSemanticOperations(metaMetadata, metadata, metaMetadata.BeforeSemanticActions); }
public void RssTestJson() { SimplTypesScope simplTypesScope = SimplTypesScope.Get("rss", typeof(Rss), typeof(Channel), typeof(Item)); List <String> categorySet = new List <String> { "cate\\dgory1", "category2" }; Item item1 = new Item("testItem1", "testItem1Description", new ParsedUri("http://www.google.com"), "asdf", "nabeel", categorySet); Item item2 = new Item("testItem2", "testItem2Description", new ParsedUri("http://www.google.com"), "asdf", "nabeel", categorySet); Channel c = new Channel("testTile", "testDesc", new ParsedUri("http://www.google.com"), new List <Item> { item1, item2 }); Rss rss = new Rss(1.4f, c); TestMethods.TestSimplObject(rss, simplTypesScope, Format.Json); }
private string MessageForXml(ElementState requestObj, int uidUsed) { string msg = SimplTypesScope.Serialize(requestObj, StringFormat.Xml); string ret = String.Format("content-length:{0}\r\nuid:{1}\r\n\r\n{2}", msg.Length, uidUsed, msg); return(ret); }
private void CustomizeFieldDescriptorInClass(SimplTypesScope metadataTScope, MetadataClassDescriptor metadataCd) { MetadataFieldDescriptor oldFD = (MetadataFieldDescriptor)metadataCd.GetFieldDescriptorByFieldName(GetFieldName(false)); String newTagName = MetadataFieldDescriptor.TagName; metadataCd.Replace(oldFD, MetadataFieldDescriptor); MetadataFieldDescriptor wrapperFD = (MetadataFieldDescriptor)MetadataFieldDescriptor.Wrapper; if (wrapperFD != null) { MetadataFieldDescriptor clonedWrapperFD = wrapperFD.Clone(); clonedWrapperFD.TagName = newTagName; clonedWrapperFD.WrappedFd = metadataFieldDescriptor; metadataCd.Replace(wrapperFD, clonedWrapperFD); } int fieldType = MetadataFieldDescriptor.FdType; if (fieldType == FieldTypes.CollectionElement || fieldType == FieldTypes.MapElement) { if (!MetadataFieldDescriptor.IsWrapped) { string childTagName = MetadataFieldDescriptor.CollectionOrMapTagName; oldFD = (MetadataFieldDescriptor)metadataCd.GetFieldDescriptorByTag(childTagName); metadataCd.Replace(oldFD, MetadataFieldDescriptor); } } }
public ChatClient() { chatTranslation = ChatTranslations.Get(); clientScope = new Scope <object>(); clientScope.Add(ChatConstants.ChatUpdateLisener, this); _client = new WebSocketOODSSClient(ServerAddress, PortNumber, chatTranslation, clientScope); }
protected override void CustomizeFieldDescriptor(SimplTypesScope metadataTScope, MetadataFieldDescriptorProxy fdProxy) { base.CustomizeFieldDescriptor(metadataTScope, fdProxy); MetaMetadata thisMmd = TypeMmd; if (thisMmd == null) { return; } MetaMetadataNestedField inheritedField = (MetaMetadataNestedField)SuperField; if (inheritedField != null) { MetaMetadata superMmd = inheritedField.TypeMmd; if (thisMmd == superMmd || thisMmd.IsDerivedFrom(superMmd)) { MetadataClassDescriptor elementMetadataCD = thisMmd.GetMetadataClassDescriptor(metadataTScope); if (elementMetadataCD != null) { fdProxy.SetElementClassDescriptor(elementMetadataCD); } else { Debug.WriteLineIf(BigSemanticsSettings.DebugLevel > 5, "can't bind FieldDescriptor because metadata class does not exist for: " + thisMmd.ToString()); } } else { throw new MetaMetadataException("incompatible types: " + inheritedField + " => " + this); } } }
public static SimplTypesScope ComposeTranslations(Type[] newTranslations, int portNumber, IPAddress ipAddress, SimplTypesScope requestTranslationSpace, String prefix = "server_base: ") { return(SimplTypesScope.Get(prefix + ipAddress + ":" + portNumber, requestTranslationSpace, newTranslations)); }
/// <summary> /// Generate String from requestMessage /// </summary> /// <param name="request">request message</param> /// <returns>request message in serialized form</returns> private string GenerateStringFromRequest(RequestMessage request) { StringBuilder requestStringBuilder = new StringBuilder(); SimplTypesScope.Serialize(request, requestStringBuilder, StringFormat.Xml); return(requestStringBuilder.ToString()); }
/// <summary> /// helper function to generate and send byte array message to client session. /// </summary> /// <param name="uid">uid of the received message</param> /// <param name="message">oodss message</param> /// <param name="session">client's websocket session</param> /// /// out message format /// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 .......n /// |length | uid | message ....| /// private void CreatePacketFromMessageAndSend(long uid, ServiceMessage message, WebSocketSession session) { StringBuilder responseMessageStringBuilder = new StringBuilder(); SimplTypesScope.Serialize(message, responseMessageStringBuilder, StringFormat.Xml); string req = responseMessageStringBuilder.ToString(); //Console.WriteLine("send message: "+ req + " uid "+uid); byte[] uidBytes = BitConverter.GetBytes(uid); byte[] messageBytes = Encoding.UTF8.GetBytes(req); byte[] lengthBytes = BitConverter.GetBytes(uidBytes.Length + messageBytes.Length); if (BitConverter.IsLittleEndian) { Array.Reverse(lengthBytes); } byte[] outMessage = new byte[lengthBytes.Length + uidBytes.Length + messageBytes.Length]; Buffer.BlockCopy(lengthBytes, 0, outMessage, 0, lengthBytes.Length); Buffer.BlockCopy(uidBytes, 0, outMessage, lengthBytes.Length, uidBytes.Length); Buffer.BlockCopy(messageBytes, 0, outMessage, lengthBytes.Length + uidBytes.Length, messageBytes.Length); session.SendResponse(outMessage); //session.SendResponseAsync(Encoding.UTF8.GetString(outMessage)); }
public static string GetJsonMMD(MetaMetadata mmd) { if (mmd == null) { return(null); } string result = null; lock (mmdJSONCache) { mmdJSONCache.TryGetValue(mmd, out result); } if (result == null) { StringBuilder mmdJSON = new StringBuilder(); mmdJSON.Append("mmd = "); mmdJSON.Append(SimplTypesScope.Serialize(mmd, StringFormat.Json)); mmdJSON.Append(";"); result = mmdJSON.ToString(); lock (mmdJSONCache) { mmdJSONCache.Add(mmd, result); } } return(result); }
/// <summary> /// Creates an instance of an NIOServer of some flavor. Creates the backend using the information /// in the arguments. /// Registers itself as the MAIN_START_AND_STOPPABLE in the object registry. /// </summary> /// <param name="portNumber"></param> /// <param name="ipAddresses"></param> /// <param name="requestTranslationScope"></param> /// <param name="objectRegistry"></param> /// <param name="idleConnectionTimeout"></param> /// <param name="maxMessageLength"></param> protected AbstractServer(int portNumber, IPAddress[] ipAddresses, SimplTypesScope requestTranslationScope, Scope <object> objectRegistry, int idleConnectionTimeout = -1, int maxMessageLength = -1) { Console.WriteLine("setting up server..."); TranslationScope = requestTranslationScope; ApplicationObjectScope = objectRegistry; }
// [TestMethod] public void TestAdvGenerics1()//ported from simplTranslators/test ecologylab.translators.java.generics.JavaTranslatorGenericTest.java { SimplTypesScope.EnableGraphSerialization(); SimplTypesScope scope = SimplTypesScope.Get("test-adv-generics-1", typeof(SearchResult), typeof(Search <>), typeof(SocialSearchResult), typeof(SocialSearch), typeof(TypedSocialSearch <>)); SimplTypesScope.DisableGraphSerialization(); }
// [TestMethod] public void CircleTlv() { Circle c = new Circle(new Point(1, 3), 3); SimplTypesScope circleTransaltionScope = SimplTypesScope.Get("circleTScope", typeof(Circle), typeof(Point)); TestMethods.TestSimplObject(c, circleTransaltionScope, Format.Tlv); }
public TestServiceClient(string serviceAddress, int port) { _serviceAddress = serviceAddress; _port = port; _testTypesScope = TestClientTypesScope.Get(); _clientScope = new Scope <object>(); _clientScope.Add(TestServiceConstants.ServiceUpdateListener, this); _client = new WebSocketOODSSClient(_serviceAddress, _port, _testTypesScope, _clientScope); }
public SemanticsSessionScope(SimplTypesScope metadataTranslationScope, string repoLocation, ParsedUri serviceUri, EventHandler <EventArgs> onCompleted) : base(metadataTranslationScope, repoLocation, onCompleted) { SemanticsSessionScope.Get = this; MetadataServiceUri = serviceUri; HttpClient = new HttpClient(); }
private void ReceiveMessageWorker() { Console.WriteLine("Entering OODSS Recieve Message loop"); while (_isRunning) { try { Receive(_clientSocket); ReceiveDone.Wait(_cancellationTokenSource.Token); int uidIndex = _response.IndexOf("uid:") + 4; string intString = _response.Substring(uidIndex, _response.IndexOf("\r\n", uidIndex) - uidIndex); int responseUid = int.Parse(intString); ServiceMessage serviceMessage = (ServiceMessage)SimplTypesScope.Deserialize(_response.Substring(_response.IndexOf('<')), StringFormat.Xml); if (serviceMessage == null) { throw new ArgumentNullException(string.Format("Received a null {0} object. Deserialization failed?", "serviceMessage")); } if (serviceMessage is UpdateMessage) { var updateMessage = serviceMessage as UpdateMessage; updateMessage.ProcessUpdate(ObjectRegistry); } else if (serviceMessage is ResponseMessage) { var responseMessage = serviceMessage as ResponseMessage; responseMessage.ProcessResponse(ObjectRegistry); QueueObject queueObject; _pendingRequests.TryGetValue(responseUid, out queueObject); if (queueObject == null) { Console.WriteLine("No pending request with Uid: {0}", responseUid); } else { TaskCompletionSource <ResponseMessage> taskCompletionSource = queueObject.Tcs; if (taskCompletionSource != null) { Console.WriteLine("--- Finished Request : {0}", queueObject.Uid); taskCompletionSource.TrySetResult(responseMessage); } } } } catch (OperationCanceledException e) { Console.WriteLine("The operation was cancelled." + e.TargetSite); } catch (Exception e) { Console.WriteLine("Caught Exception :\n " + e.StackTrace); } } }
public void NotConditionTest()// throws SIMPLTranslationException { String xml = "<not><and><or><and /><or /></or><not_null /></and></not>"; NotCondition not = (NotCondition)MetaMetadataTranslationScope.Get().Deserialize(xml, StringFormat.Xml); Console.WriteLine(not); Console.WriteLine(not.Check); Console.WriteLine(SimplTypesScope.Serialize(not, StringFormat.Xml)); }
public void OrConditionTest()// throws SIMPLTranslationException { String xml = "<or><or /><not_null /></or>"; OrCondition or = (OrCondition)MetaMetadataTranslationScope.Get().Deserialize(xml, StringFormat.Xml); Console.WriteLine(or); Console.WriteLine(or.Checks); Console.WriteLine(SimplTypesScope.Serialize(or, StringFormat.Xml)); }
public void AndConditionTest() { String xml = "<and><or><and /><or /></or><not_null /></and>"; AndCondition and = (AndCondition)MetaMetadataTranslationScope.Get().Deserialize(xml, StringFormat.Xml); Console.WriteLine(and); Console.WriteLine(and.Checks); Console.WriteLine(SimplTypesScope.Serialize(and, StringFormat.Xml)); }
public void MapsWithinMapsTestJson() { TranslationS test = MapsWithinMaps.CreateObject(); SimplTypesScope tScope = SimplTypesScope.Get("testScope", typeof(TranslationS), typeof(ClassDes), typeof(FieldDes)); TestMethods.TestSimplObject(test, tScope, Format.Json); }
public void CompositeSubOneXml() { Container c = new Container(new WcSubOne("testing", 1)); SimplTypesScope simplTypesScope = SimplTypesScope.Get("compositeTScope", typeof(Container), typeof(WcBase), typeof(WcSubOne), typeof(WcSubTwo)); TestMethods.TestSimplObject(c, simplTypesScope); }
public void CompositeSubTwoJson() { Container c = new Container(new WcSubTwo(true, 1)); SimplTypesScope simplTypesScope = SimplTypesScope.Get("compositeTScope", typeof(Container), typeof(WcBase), typeof(WcSubOne), typeof(WcSubTwo)); TestMethods.TestSimplObject(c, simplTypesScope, Format.Json); }
public BaseSessionManager(string sessionId, SimplTypesScope translationScope, Scope <object> applicationObjectScope, ServerProcessor frontend) { FrontEnd = frontend; SessionId = sessionId; TranslationScope = translationScope; LocalScope = GenerateContextScope(applicationObjectScope); LocalScope.Add(SessionObjects.SessionId, sessionId); LocalScope.Add(SessionObjects.ClientManager, this); }
public override void Parse() { SimplTypesScope metadataTScope = SemanticsSessionScope.MetadataTranslationScope;; Document parsedDoc = metadataTScope.Deserialize(Simpl.Fundamental.Net.PURLConnection.Stream, Format.Xml) as Document; DocumentClosure.TaskCompletionSource.TrySetResult(parsedDoc); // post parse: regex filtering + field parser }
public void ContainingClassCc1Json() { SimplTypesScope translationScope = SimplTypesScope.Get("test", typeof(ContainingClass), typeof(ChildClass1), typeof(ChildClass2), typeof(BaseClass)); ContainingClass cc1 = new ContainingClass { TheField = new ChildClass1() }; TestMethods.TestSimplObject(cc1, translationScope, Format.Json); }
internal Type GetMetadataClass(SimplTypesScope metadataTScope) { Type result = metadataClass; if (result == null) { MetadataClassDescriptor descriptor = this.MetadataClassDescriptor; result = (descriptor == null ? null : descriptor.DescribedClass); metadataClass = result; } return(result); }
/// <summary> /// /// </summary> /// <param name="pSimplTypesScope"></param> /// <param name="pTranslationContext"></param> /// <param name="pDeserializationHookStrategy"></param> /// <param name="format"></param> /// <returns></returns> public static PullDeserializer GetPullDeserializer(SimplTypesScope pSimplTypesScope, TranslationContext pTranslationContext, IDeserializationHookStrategy pDeserializationHookStrategy, Format format) { switch (format) { case Format.Xml: return new XmlPullDeserializer(pSimplTypesScope, pTranslationContext, pDeserializationHookStrategy); case Format.Json: return new JsonPullDeserializer(pSimplTypesScope, pTranslationContext, pDeserializationHookStrategy); case Format.Bibtex: throw new SimplTranslationException("bibtex serialization is not supported"); case Format.Tlv: return new TlvPullDeserializer(pSimplTypesScope, pTranslationContext, pDeserializationHookStrategy); default: throw new SimplTranslationException(format + "format not supported"); } }
/// <summary> /// /// </summary> /// <param name="inputSimplTypesScope"></param> /// <param name="inputContext"></param> protected PullDeserializer(SimplTypesScope inputSimplTypesScope, TranslationContext inputContext) : this(inputSimplTypesScope, inputContext, null) { }
// private String test; /// <summary> /// /// </summary> /// <param name="inputSimplTypesScope"></param> /// <param name="inputContext"></param> /// <param name="deserializationHookStrategy"></param> public JsonPullDeserializer(SimplTypesScope inputSimplTypesScope, TranslationContext inputContext, IDeserializationHookStrategy deserializationHookStrategy) : base(inputSimplTypesScope, inputContext, deserializationHookStrategy) { }
/// <summary> /// /// </summary> /// <param name="inputSimplTypesScope"></param> /// <param name="inputContext"></param> protected BinaryPullDeserializer(SimplTypesScope inputSimplTypesScope, TranslationContext inputContext) : base(inputSimplTypesScope, inputContext) { }
/// <summary> /// /// </summary> /// <param name="inputSimplTypesScope"></param> /// <param name="inputContext"></param> /// <param name="deserializationHookStrategy"></param> protected BinaryPullDeserializer(SimplTypesScope inputSimplTypesScope, TranslationContext inputContext, IDeserializationHookStrategy deserializationHookStrategy) : base(inputSimplTypesScope, inputContext, deserializationHookStrategy) { }
/// <summary> /// /// </summary> /// <param name="inputSimplTypesScope"></param> /// <param name="inputContext"></param> public JsonPullDeserializer(SimplTypesScope inputSimplTypesScope, TranslationContext inputContext) : base(inputSimplTypesScope, inputContext) { }