use nlog to write to rest service - json

been at this for some time now,
i have a rest service that takes some parameter that i send via the query string. other then that i need to send via the request body some fields.
the format needs to be json.
here is a successful request made from postman for example:
{
"TransactionLogId": "6e6279a3-22d9-458d-b1c9-9b03a81556be",
"CreatedDate": "2015-08-17T15:05:50.0143866Z",
"LogType": "Info",
"TransactionCode": "2831b7bc-9fc8-424d-857a-182397a5eb11",
"ServiceName": "ESBService.WCF",
"ServiceId": "8664e362-f63d-4d10-8a23-3b86b9f22cc7",
"Servers": "******************",
"Context": "EmployersSite",
"RequestIPs": "**************",
"UserId": "258a8c83-3f18-40d6-aea7-986dc0d97656",
"ActivityTime": "2015-08-17T15:05:50.0143866Z",
"LogSubType": "Info.RequestBegin",
"Title": "RequestBegin",
"Details": "",
"RequestData": "{\r\n \"Filters\": {\r\n \"Mode\": \"Automatic\",\r\n \"Type\": \"Applicant\"\r\n }\r\n}",
"EntityClass": "SavedSearch",
"EntityId": "",
"Methods": "SavedSearch_Search; SetSession",
"SourceFilePath": "*******************\\PortalService.svc.cs",
"SourceLineNum": 1025,
"RunTime": 0.015
}
here is my config. lets say that all i want right now is just to send the exception message in details field.
here is my config:
<nlog throwExceptions="true" internalLogFile="c:\\Data\\Logs\\IES\\nlog_debug.txt" internalLogLevel="Warn">
<variable name="LogBaseFolder" value="c:\\Data\\Logs\\tester" />
<targets>
<target type='WebService'
name='ws'
url='somesvc.vc/TransactionLog/Create?Context=Portal&UserToken=a441b37f-3403-43fd-8f58-d1da3024133a'
protocol='HttpPost'
encoding='UTF-8'>
<parameter name='details' type='System.String' layout=" ${message}"/>
</target>
</targets>
<rules>
<logger name="*" writeTo="ws" />
</rules>
</nlog>
and my code:
Log.Site.Error("erorrrr")
but the request never makes it it get error that the body is not right:
message=Unexpected character encountered while parsing value: M. Path
'', line 0, position 0.
this is killing me could realy use some help. thanks

don't worry it's actually something newbies encounters a lot and there is a simple solution for that! – so REST your mind :)
So basically, when you pass the JSON back in the respond you need to Super-Serialize the object prior the response.Write(), do
response.super(Object name_Object)
What it does it handles "deeper" encapsulation processes ('DIYA Encapsulation') which includes nested objects (methods and members)
But without the core functions (constructor, destructor..)
Hope it helps, and good luck.
BTW, Recommend you to read more about classes, nest objects, what is a constructor etc.
It will help you further more as you develop as a developer! Cheers :)

Related

Configuring Kafka Appenders with Log4j2 json configuration

I am using log4j2 with a JSON properties file I am naming log4j2.json and attempting to add a kafka appender. There are plenty of examples using the older formats or xml, but struggling to get the correct format in JSON. This is most likely a silly question, but I have been struggling to get this to work and can find no examples anywhere. I am tempted to abandoned configuring log4j2 in json and moving to XML, but I feel this should be rather simple.
Here is a sample kafka appender defined in XML.
'<Appenders>
<Kafka name="Kafka" topic="devglan-test">
<PatternLayout pattern="%date %message"/>
<Property name="bootstrap.servers">localhost:9092</Property>
</Kafka>
<Async name="Async">
<AppenderRef ref="Kafka"/>
</Async>
</Appenders>
How does the
'localhost:9092
entry map to JSON.
I have tried a number of styles such as the following:
'"Kafka": {
"name":"Kafka",
"topic":"FEEDPROCESSING_Dev",
"PatternLayout": {
"pattern": "%date %message"
},
"bootstrap.servers": [{"name":"localhost:9092"}]}
}
That did not work. I also tried..
'"Kafka": {
"name":"Kafka",
"topic":"FEEDPROCESSING_SYNC_Dev",
"PatternLayout": {
"pattern": "%date %message"
},
"Property": {"bootstrap.servers":"localhost:9092"}}
}
I am getting errors like:
Property contains an invalid element or attribute "bootstrap.servers"
THis configuration gives me the error "Unable to locate plugin type for bootstrap.servers":
'"Property": {"bootstrap.servers":[{"name":"localhost:9092"}]}}},
I know I have the correct maven dependencies..
What is the correct way to configure a Kafka appender, particular the bootstrap server property,using JSON and log4j2?
This is the correct format I think:
"Kafka": {
"name": "Kafka",
"topic": "FEEDPROCESSING_Dev",
"PatternLayout": {
"pattern": "%date %message"
},
"Property": {
"name": "bootstrap.servers",
"value": "localhost:9092"
}
}

JSON request using Postman

I am sending a raw Json requet using postman to an API service which feeds it to another web service and finally a database. I want to attach a file to the raw Json request.
I am attaching below the current request I am sending. Is it the right way? The first name and other information is going through but the attachment is not. Any suggestions?
{
"Prefix": "",
"FirstName": "test-resume-dlyon",
"LastName": "test-dlyon-resume",
"AddressLine1": "test2",
"AddressLine2": "",
"City": "Invalid Zipcode",
"State": "GA",
"Zip": "99999",
"Phone": "9999999999",
"Email": "testresumedlyon#gmail.com",
"Source": "V",
"WritingNumber": "",
"AgeVerified": true,
"AdditionalSource": "",
"EnableInternetSource": true,
"InternetSource": "",
"ExternalResult": "",
"PartnerID": "",
"SubscriberID": "15584",
"Languages": [
"English",
"Spanish"
],
"fileName": "resume",
"fileExtension": "docx",
"fileData": "UELDMxE76DDKlagmIF5caEVHmJYFv2qF6DpmMSkVPxVdtJxgRYV"
}
There is no "correct" format to attach a file to a JSON.
JSON is not multipart/form-data (which is designed to include files).
JSON is a text-based data format with a variety of data types (such as strings, arrays, and booleans) but nothing specific for files.
This means that to attach a file, you have to get creative.
For example, you could encode a file in text format (e.g. using base64), but it wouldn't be very efficient, and any Word document would result in you getting a much longer string than "UELDMxE76DDKlagmIF5caEVHmJYFv2qF6DpmMSkVPxVdtJxgRYV".
Of course, the method you use to encode the file has to be the method that whatever is reading the JSON expects you to use. Since there is no standard for this, and you have said nothing about the system which is consuming the JSON you are sending, we have no idea what that method is.
First of all, I'd recommend reading the postman API docs. They have some extremely useful information on there for using the API. Two particular articles that might of interest here are these:
Looking at it and running it through a validator like this one shows that there are no syntax errors so it must be to do with the JSON parameters the API is expecting.
Here's something you can try:
In postman, set method type to POST.
Then select Body -> form-data -> Enter your parameter name (file according to your code)
and on right side next to value column, there will be dropdown "text, file", select File. choose your image file and post it.
For rest of "text" based parameters, you can post it like normally you do with Postman. Just enter parameter name and select "text" from that right side dropdown menu and enter any value for it, hit send button. Your controller method should get called.

Fhir json - how to suppress attributtes (ex. #Value, #id) in java app

I have a REST API that needs to produce both Fhir xml and Fhir json. I generated java classes using xsd. XML works 100%. however, the json object looks funny as it includes attributes which I'd like to suppress.
I have specified on my REST API: #Produces({"application/json+fhir",MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
XML output:
<Bundle xmlns="http://hl7.org/fhir" xmlns:ns2="http://www.w3.org/1999/xhtml">
<meta>
<versionId value="urn:uuid:b6bfc48a-7b03-4bf3-ba94-d05a3b52979a"/>
<lastUpdated value="2017-07-10T08:32:44.670+02:00"/>
</meta>
<type value="collection"/>
<entry>
<resource>
<Coverage>
<id value="47000340200"/>
<subscriber>
<display value="AB SMITH"/>
</subscriber>
<period>
<start value="2017-01-01"/>
</period>
<payor>
<display value="XXX040TXX"/>
</payor>
<grouping>
<extension url="some URL">
<valueUri value="Hyperlink goes here"/>
</extension>
<group value="XXX"/>
<groupDisplay value="XXX MEDICAL FUND"/>
<plan value="OPT1"/>
<planDisplay value="OPTION1"/>
<class value="Active"/>
</grouping>
</Coverage>
</resource>
</entry>
JSON output:
{"Bundle": {
"meta": {
"versionId": {"#value": "urn:uuid:b6bfc48a-7b03-4bf3-ba94-d05a3b52979a"},
"lastUpdated": {"#value": "2017-07-10T08:32:44.670+02:00"}
},
"type": {"#value": "collection"},
"entry": [
{"resource": {"Coverage": {
"id": {"#value": "47000340200"},
"subscriber": {"display": {"#value": "AB SMITH"}},
"period": {"start": {"#value": "2017-01-01"}},
"payor": {"display": {"#value": "XXX040TXX"}},
"grouping": {
"extension": {
"#url": "some URL",
"valueUri": {"#value": "Hyperlink goes here"}
},
"group": {"#value": "XXX"},
"groupDisplay": {"#value": "XXX MEDICAL FUND"},
"plan": {"#value": "OPT1"},
"planDisplay": {"#value": "OPTION1"}
}
}}}
]
}}
How do I get rid of the "#Value" attribute?
The FHIR XML and JSON (and TTL) syntaxes are all tuned to their syntax and thus manifest a slightly different model. If you try running an instance with extensions on a simple type (date, boolean, etc.), you'll find even more significant differences in your generated object model. If you generate your object model from the XML schema, the JSON schema or the OWL, you'll find there's a decent chunk of hand-coding you'll have to add on afterwards to generate and parse the other syntaxes correctly. The alternative is to use one of the existing reference implementations - those handle the conversion for you and provide a whole bunch of helper classes and methods that might also be helpful for you. The reference implementations can be found on the downloads page.

how to call a service (or parameter of one service) from another service in wso2 ESB

I am using wso2 ESB for creating a rest API in json format. I have a restful json webservice which gives the response. I need to use one of the parameter of this response in another service call.
How can i do this kind of service chaining in wso2 ESB.
for ex:-
i have a restful url as abc.com/cusotmer. I got the response back. Suppose "id" is one of the parameter of response.
I want to use this parameter in another service call (say, xyz.com/sheet) which internally calls the first service (abc.com/cusotmer).
Could any of you please help me in this regard ?
This is service chaining. You can refer to WSO2 library article which explains this clearly trough a example
http://wso2.com/library/articles/2011/01/wso2-esb-by-example-service-chaining/
Service chaining is an important feature in any of the ESBs avaiable.
You can use Call Mediator which keeps the control in the sequence (say your insequence)
You can use call for first endpoint , for second endpoint i am assuming the id is available in response body, you can either use json-eval or xpath to get this value, depending on type of data second service uses you can use PayloadFactoryMediator and set id in desired body part
And in next line you can call again using Call Mediator or Send
A rough code will be like.
<payloadFactory media-type="json">
<format>
{ "A": "6", "tests": [{ "id": "xyz", "status": "new", "emp": [{ "Id": "12345" }] }], "student": [{ "Id": "65", "Name": "Ram" }] }
</format>
</payloadFactory>
<call>
<endpoint>
<http method="get" uri-template="http://192.168.1.10:8088/mockaxis2service"/>
</endpoint>
</call>
<!-- suppose id field comes as response in field name id2 -->
<payloadFactory media-type="json">
<format>
{
"inp2second":"$1"
}
</format>
<args>
<arg expression="$.emp.id2"/>
</args>
</payloadFactory>
<call> or <send>
You can use either call or send mediator now ,send mediator to move the control to outsequence.
for json expression used above as $.emp.id2 kindly refer json support page for example
An example of service chaining is also available here

creating RAML file for dynamic key/values for get/post

I was using a Mule application to get data from another system which is invoked by an HTTP endpoint, used java with jersey api to get the rest component.
Sample input data is given below, here keys and values are not fixed, it may vary based on user request. Array size will increase may be 2 to n entries. It is working fine with Mule and Java rest based component.
Input JSON data:
[
{
"Company": "BEG1",
"Account": "10011",
"Deptid": "111",
"Location": "SM1",
"Transaction Date": "2014-07-15",
"Description": "Invoice1",
"Debit": 0,
"Credit": 13.46,
"Invoice Nbr": "16824321"
},
{
"Company": "BEG92",
"Account": "10092",
"Deptid": "222",
"Location": "SL2",
"Transaction Date": "2014-07-19",
"Description": "Invoice End2",
"Debit": 13.46,
"Credit": 0,
"Invoice Nbr": "168243292"
}
]
Planning to migrate to APIkit with RAML: how can I make a RAML template for above case? Since keys are dynamic, this doesn't seem straightforward.
2) With same approach for GET, I will get the data for my get request, I am not sure what is the key and its corresponding values, only I was doing is get the data, parse it and send it to the user. How do I create RAML template on this situation.Will mule APIkit with RAML will work here?
My existing code:
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public List<GLExport> postOperation(#Payload String content) throws ParseException {
JSONParser jsonParser = new JSONParser();
Object jsonObjectInstance =null;
jsonObjectInstance = jsonParser.parse(new StringReader(content));
...
return glExportList;
<http:inbound-endpoint exchange-pattern="request-response" host="${hostname}" port="${glport}" path="QBJournalExport/QBGLRest" doc:name="HTTP"/>
<jersey:resources doc:name="REST">
<component class="com.qb.rest.GLExportService"/>
</jersey:resources>
It seems your question is more about JSON Schema than RAML. In essence, you are asking how to support unknown fields in a JSON Schema.
The answer is by adding:
"additionalProperties": true
to your JSON Schema object definition.
I strongly suggest that if there is set of fields are known, you declare them explicitly in your schema: users of your API will thank you for that.
Also, if some of these fields are guaranteed to be present, mark them as required as well.
APIkit should have no trouble dealing with additional properties.