Retrieving "$ref" field in swagger.json - swagger

I am trying to use the swagger parser to parse and retrieve information in the "swagger.json" (io.swagger.parser.SwaggerParser;)
Below is an excerpt of the "swagger.json".
I am trying to retrieve "$ref" : "#/definitions/abc".
"responses" : {
"200" : {
"description" : "abc",
"schema" : {
"$ref" : "#/definitions/abc"
}
},
This is the code to parse it.
SwaggerParser sparse = new SwaggerParser();
Swagger swagger = sparse.read("swagger.json");
// This next line is what I am having a problem with.
swagger.getPath("/endpointurl").getGet().getResponses().get("200").getSchema();
At this point, the ".getSchema()" in the above line has only "getType()" in it I can call. It doesn't have "get$ref()". This is because ".getSchema()" returns a "Property" (io.swagger.models.properties.Property). It doesn't have "get$ref()".
get$ref() is available in "RefProperty" (io.swagger.models.properties.RefProperty)
But ".getSchema()" doesn't return a "RefProperty".
Typecast the result of ".getSchema()" to a "RefProperty" also doesn't work. It ends up in this error.
java.lang.ClassCastException: io.swagger.models.properties.ArrayProperty cannot be cast to io.swagger.models.properties.RefProperty
Has anyone tried parsing a "swagger.json" and was able to retrieve the "$ref": line under "schema" in the "response" block?
Any idea how might I be able to do that?

I figured out a way to do that. Maybe not the best way to do it, but it retrieves the information in "#ref".
Object obj = xxxxx.getSchema(); // xxxxx is whatever your code that gives you ".getSchema()". Mine is in a map and I don't want to distract people.
ArrayProperty arrProp = new ArrayProperty();
arrProp = (ArrayProperty)obj; // .getSchema() returns an ArrayProperty
RefProperty refProperty = (RefProperty) arrProp.getItems(); // .getItems() will return the RefProperty type you need to call ".get$ref()".
String refStr = refProperty.get$ref(); // Voila, there's your content in "#ref".
String simpleRefStr = refProperty.getSimpleRef();
I had to do a few type castings. If you have a more elegant way of doing this, please post here.

Related

Serilog Filter Expressions: What is the syntax to filter against dictionaries?

I'm struggling to find the correct syntax to use in a Serilog filter expression to find a particular key/value pair in a dictionary within the event properties.
This is a contrived example, but illustrates the issue.
The relevent setup looks like this:
string exceptionFilter = "SomeDictionary.Other = 'Nope'";
LoggerConfiguration config = new LoggerConfiguration()
.Destructure.JsonNetTypes()
.MinimumLevel.ControlledBy(LevelSwitch)
.Enrich.FromLogContext()
.Enrich.With(new ExceptionEnricher())
.Filter.ByExcluding(exceptionFilter)
.WriteTo.MSSqlServer(
connectionString: ConnectionString,
sinkOptions: SinkOptions,
columnOptions: ColumnOptions
);
Logger = config.CreateLogger();
Then I log an event like this:
Log.Fatal(
ex,
"Real Bad {#SomeDictionary}",
new Dictionary<string, string>() {
{"Test", "Test"},
{"Other", "Nope"}
}
)
What should the expression to exclude SomeDictionary['Other'] = 'Nope' be?
If I pass in the event details as an object:
Log.Fatal(
ex,
"Real Bad {#SomeObject}",
new {
Test = "Test",
Other = "Nope"
}
)
Then the following expression works as expected:
SomeObject.Other = 'None'
Unfortunately, I am enriching our logs with a number of dictionaries that I need to be able to filter by and that syntax doesn't seem to work with them.
EDIT
If I serialize the log event properties, it appears that the issue is probably due to escaped quotation marks within the dictionary keys:
"SomeDictionary": {
"Elements": {
"\"Test\"": {
"Value": "Test"
},
"\"Other\"": {
"Value": "Nope"
}
}
}
Still not sure what I need to do to be able to filter on one of the elements.
Resolution
I switched from using Serilog.Filters.Expressions to Serilog.Expressions and the issue resolved itself. Now I can filter on dictionaries using expected syntax:
SomeDictionary['Other'] = 'Nope'

Neo4j and json creating multiple nodes with multiple params

I tried many things but of no use.
I have already raised a question on stackoverflow earlier but I am still facing the same issue.
Here is the link to old stackoverflow question
creating multiple nodes with properties in json in neo4j
Let me try out explaining with a small example
This is the query I want to execute
{
"params" : {
"props" : [
{
"LocalAsNumber" : 0,
"NodeDescription" : "10TiMOS-B-4.0.R2 ",
"NodeId" : "10.227.28.95",
"NodeName" : "BLR_WAO_SARF7"
}
]
},
"query" : "MATCH (n:Router) where n.NodeId = {props}.NodeId RETURN n"}
For simplicity I have added only 1 props array otherwise there are around 5000 props. Now I want to execute the query above but it fails.
I tried using (props.NodeId}, {props[NodeID]} but everything fails.
Is it possbile to access a individual property in neo4j?
My prog is in c++ and I am using jsoncpp and curl to fire my queries.
If you do {props}.nodeId in the query then the props parameter must be a map, but you pass in an array. Do
"props" : {
"LocalAsNumber" : 0,
"NodeDescription" : "10TiMOS-B-4.0.R2 ",
"NodeId" : "10.227.28.95",
"NodeName" : "BLR_WAO_SARF7"
}
You can use an array of maps for parameter either with a simple CREATE statement.
CREATE ({props})
or if you loop through the array to access the individual maps
FOREACH (prop IN {props} |
MERGE (i:Interface {nodeId:prop.nodeId})
ON CREATE SET i = prop
)
Does this query string work for you?
"MATCH (n:Router) RETURN [p IN {props} WHERE n.NodeId = p.NodeId | n];"

Update field of embedded documents on multiple Mongoid documents [duplicate]

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 5 years ago.
I recently started using MongoDB and I have a question regarding updating arrays in a document.
I got structure like this:
{
"_id" : ObjectId(),
"post" : "",
"comments" : [
{
"user" : "test",
"avatar" : "/static/avatars/asd.jpg",
"text" : "....."
}
{
"user" : "test",
"avatar" : "/static/avatars/asd.jpg",
"text" : "....."
}
{
"user" : "test",
"avatar" : "/static/avatars/asd.jpg",
"text" : "....."
}
...
]
}
I'm trying to execute the following query:
update({"comments.user":"test"},{$set:{"comments.$.avatar": "new_avatar.jpg"}},false,true)
The problem is that it update all documents, but it update only the first array element in every document. Is there any way to update all array elements or I should try to do it manually?
Thanks.
You cannot modify multiple array elements in a single update operation. Thus, you'll have to repeat the update in order to migrate documents which need multiple array elements to be modified. You can do this by iterating through each document in the collection, repeatedly applying an update with $elemMatch until the document has all of its relevant comments replaced, e.g.:
db.collection.find().forEach( function(doc) {
do {
db.collection.update({_id: doc._id,
comments:{$elemMatch:{user:"test",
avatar:{$ne:"new_avatar.jpg"}}}},
{$set:{"comments.$.avatar":"new_avatar.jpg"}});
} while (db.getPrevError().n != 0);
})
Note that if efficiency of this operation is a requirement for your application, you should normalize your schema such that the location of the user's avatar is stored in a single document, rather than in every comment.
One solution could be creating a function to be used with a forEach and evaling it (so it runs quickly). Assuming your collection is "article", you could run the following:
var runUpdate = function(){
db.article.find({"comments.user":"test").forEach( function(article) {
for(var i in article.comments){
article.comments[i].avatar = 'new_avatar.jpg';
}
db.article.save(article);
});
};
db.eval(runUpdate);
If you know the indexes you want to update you can do this with no problems like this:
var update = { $set: {} };
for (var i = 0; i < indexesToUpdate.length; ++i) {
update.$set[`comments.${indexesToUpdate[i]}. avatar`] = "new_avatar.jpg";
}
Comments.update({ "comments.user":"test" }, update, function(error) {
// ...
});
be aware that must of the IDE's will not accept the syntax but you can ignore it.
It seems like you can do this:
db.yourCollection.update({"comments.user":"test"},{$set:{"comments.0.avatar": "new_avatar.jpg", "comments.1.avatar": "new_avatar.jpg", etc...})
So if you have a small known number of array elements, this might be a little easier to do. If you want something like "comments.*.avatar" - not sure how to do that. It is probably not that good that you have so much data duplication tho..

Accessing specific values in array of JSON-Objects

I am using rails 3 with backbone.js 0.53 and currently receive a GET with the following array:
[{"credit_card":
{"id":2,"cc_number":"12345678912345","cc_type":"stack","owner":"overflow"}},
....next objects....]
I have read a lot of the other threads but can't figure out how to access the values.
Is there any way to do this with the backbone-given methods like .get()?
I tried
myArray = eval(arrayJSON)
alert myArray.length #works
but any other way of accessing the single values in an array or iterating over it fails.
Probably I am just missing something here.
Quick example of how to iterate through all your results via underscore:
/* received results mocking */
model.attributes = [
{ "credit_card" : { "id":2, "cc_number":"12345678912345" },
{ "credit_card" : { "id":3, "cc_number":"44444444455555" },
{ "credit_card" : { "id":4, "cc_number":"66666655554332" }
]
/* lets get all results */
results = model.toJSON()
/* loop through all results */
_(results).each(item) {
console.log(item.credit_card.id);
}
/* get result by array pos */
console.log(results[1]); // get 2nd item
Cheers
It might be useful to see more details, but in general you should be able to access elements just fine with the following syntax: alert(myArray[0].credit_card.cc_number);
I even pasted your sample array into jsFiddle and had no issues: http://jsfiddle.net/P4w7T/1/

How do I avoid a circular reference while serializing Entity Framework class

I have an MVC-3 (RC1) application using Entity Framework 4.
I wish to return a JSON object from a controller action. This object is referenced by other objects, which obviously return the reference.
I thus receive the following circular reference error:
Server Error in '/' Application.
A circular reference was detected
while serializing an object of type
'Application.Models.ReferenceObject'.
Description: An unhandled exception
occurred during the execution of the
current web request. Please review the
stack trace for more information about
the error and where it originated in
the code.
Exception Details:
System.InvalidOperationException: A
circular reference was detected while
serializing an object of type
'Application.Models.ReferenceObject'.
NB: Application & ReferenceObject are obviously replacements for the actual namespace / object.
According to Stack Overflow: Circular reference exception when serializing LINQ to SQL classes, this can be overcome using JSON.Net; however I would like to avoid this and instead try to exclude the offending reference properties from the object being serialized.
What do I mean?
I want to do something like this:
IList<ReferenceObject> list = Repository.GetReferenceObjects();
return Json(list.**<method>**("ObjectsReferencingThis"));
where **<method>** is some method that does the opposite to the ObjectQuery(Of T).Include method and ObjectsReferencingThis is the property that is causing the circular reference.
NB: I do not wish to remove these properties or create POCOs as this only affects the Json serialization.
Anyone able to help please?
:)
I had a similar problem when worked on one of my previous project.
Here is what I ended up doing:
IList<Product> list = Repository.GetProducts();
var collection = products.Select(product => new
{
id = product.Id,
name = product.Name,
detailUrl = product.DetailUrl,
imageLargeUrl = product.ThumbNailUrl,
tagtitle = product.Name.ToUpper(),
tagheader = "Words our cherished patrons use to describe this product",
tagwords = from tag in product.Tags group tag by tag.Name into words select new { name = words.Key, weight = words.Count() }
});
var result = new {id = inquiry.Id, products = collection, };
return this.Jsonp(result);
Here is how the result Json would look like:
{
"id" : 2,
"products" : [{
"id" : "3605970008857",
"name" : "TITLE1",
"detailUrl" : "http://www.urlhere.com",
"tagwords" : [{
"name" : "roses",
"weight" : 1
},
{
"name" : "cotton",
"weight" : 1
},
{
"name" : "happy",
"weight" : 1
}]
},
{
"id" : "3605970019891",
"name" : "TITLE2",
"detailUrl" : "http://www.urlhere.com",
"tagwords" : []
}],
}
You can also add any other properties from you referenced objects to the result as you wish,to be shown in your Json object :)
I made a very trivial solution which is not recommended if you have very big list
letters=UserOperations.GetDepartmentLettersForSecretary(pageNumber, pageSize,(Session["User"] as User).DepartmentID.Value, (Session["User"] as User).ID);
foreach (Letter letter in letters)
{
letter.LetterStatus.Letters = null;
}
the problem of circular reference in my case is in LetterStatus.Letters
so I Iterated through the list and assigned it to null
as I told you its not recommended if you have very big list

Resources