JavaScript front-end and Progress4GL back-end - json

I want to create an application with front-end HTML + JavaScript and back-end Progress4GL.
I found this documentation: http://communities.progress.com/pcom/docs/DOC-106147 (see Introducing AJAX and Introducing JSON). In the example described it is used GET method when requesting data:
xmlhttp.open("GET", "http://localhost/cgi-bin/cgiip.exe/WService=wsbroker1/getcustomersJSON_param.p?piCustNum="+ custval, true);
xmlhttp.send();
and on Progress4GL procedure for getting the param it is used get-value("piCustNum").
In my application I want to use POST method. So the request will be, for example:
xmlhttp.open("POST","http://localhost/cgi-bin/cgiip.exe/WService=wsbroker1/getcustomersJSON_param.p",true);
xmlhttp.send("piCustNum=" + custval);
But I don't know how to get the sent param on Progress side. Actually I want to send a stringify JSON.
Can anyone help me with this? Thanks!

If you want to POST JSON data to a webspeed program, check out WEB-CONTEXT:FORM-INPUT or if you post more than 32K, check out WEB-CONTEXT:FORM-LONG-INPUT.
Now... regarding reading the JSON data, it depends on your OpenEdge version. In 10.2B Progress started supporting JSON, however it is very limited, especially if you have little control of how the JSON gets created. Since you are the one creating the JSON data it may work for you. Version 11.1 has much better support JSON including a SAX streaming implementation.
We were on version 10.2 so I had to resort to using this C library to convert the JSON into a CSV file. If you have access to Python on your server it is very easy to convert to a CSV file

For the front-end I'd recommend you to use some library (like jQuery) to handle the ajax's request for you, instead of dealing with the complexity to work with different browsers, etc. You can use jQuery's functions like $.ajax, $.get or $.post to make your requests.
A post to a webspeed page could easily be done like this:
var data = {
tt_param: [ { id: 1, des: 'Description 1' } ]
}
var params = { data: JSON.stringify(data) }
$.post(
'http://<domain>/scripts/cgiip.exe/WService=<service>/ajax.p',
params,
function (data) {
alert('returned:' + data);
},
'text'
);
And the back-end would receive the JSON string using get-value('data'):
{src/web2/wrap-cgi.i}
def temp-table tt_param no-undo
field id as int
field des as char.
def var lc_param as longchar no-undo.
procedure output-header:
output-content-type("text/text").
end.
run output-header.
assign lc_param = get-value('data').
temp-table tt_param:read-json('longchar', lc_param).
find first tt_param no-error.
{&OUT} 'Cod: ' tt_param.id ', Des: ' tt_param.des.
It's a good place to start, hope it helps.
Cheers,

There is a library from Node for calling Progress Business Logic dynamically. I hope this would help.
node4progress

Related

MongoDB not returning a proper JSON

When I run db.collection.explain().find(), it gives the following error;
The last field in this json object has a double quote problem: `"totalChildMillis" : NumberLong(2)`.
When I parse this object, I got an exception saying that NumberLong(2) should be double quoted. Is there a way for MongoDB returns a standard JSON object?
{
"executionStages":{
"stage": "SINGLE_SHARD",
"nReturned": 10000,
"executionTimeMillis": 3,
"totalKeysExamined": 0,
"totalDocsExamined": 10000,
"totalChildMillis": NumberLong(2)
}
}
EDIT1
I am currently using Javascript NodeJS to create a sub-process of a mongo-shell. And send explain command to that process and listen on its output. Once I got the output, I need to parse it to a javascript object by JSON.parse() method. Based on this use case, what is the easier way for me to adapt mongo json extension to be a standard javascript object?
See the docs on MongoDB Extended JSON. Basically it comes down to the fact that MongoDB extends JSON to add additional datatypes that JSON does not support. In order to preserve that type information, various tools use either "strict" mode (which confirms to the JSON RFC) or "mongo shell" mode, which uses notations like NumberLong() and ISODate() to represent datatypes and is generally not parseable using a JSON parser.
Depending on what you're doing, you can use mongoexport which has an option to output in strict mode. But if you're trying to evaluate the explain plan of a query, I don't think that's going to work unless you insert the explain plan into a temp collection and then mongoexport it out.
Your best bet is to do whatever scripting you're trying to accomplish using a programming language (e.g. Java, Perl, Python, C#, etc.) and one of the corresponding MongoDB drivers. There you'll have much more flexibility and power with how you retrieve and parse data.
Since you mentioned in your edit that you're using Node.js, you can use the explain option to get the explain output directly from Node without having to spawn a sub-process.
Here's a very basic example:
var url = 'mongodb://localhost:27017/test';
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
var collection = db.collection('test');
collection.find({}, {explain:true}).each(function(err, doc) {
if(doc != null)
console.dir(doc);
});
});

Oracle ords: How to create put/post method with collection

I created a post method to receive the geolocation data of customers:
Post method
When I call the post method with the JSON:
{"customer": 1, "latitude":-21.13179, "longitude":-47.736782 }
my PL/SQL Script works.
Now I'd like to send a group of records but I don't know how to do it.
I created a PUT method to receive a collections of geolocations and I constructed a script just to parse the parameter:
Put method
When I call the put method with the JSON:
{
"items":[
{
"customer":1,
"latitude":-21.13179,
"longitude":-47.736782
},
{
"customer":1,
"latitude":-21.13179,
"longitude":-47.736782
}
]
}
PL/SQL code:
declare
l_values apex_json.t_values;
begin
apex_json.parse (
p_values => l_values,
p_source => :items );
end;
I received the message:
400 - Bad Request - Expected a value but got: START_ARRAY.
What I'm doing of wrong?
I want to create a post/put method to receive a collection.
Thanks for your help.
There is an example in OracleBase that shows a way to use 'JSON_Table' in 12c and 'JSON_Obect_t' pl/sql in 12Cr2. The JSON data is passed as a blob to the stored proc which then parses and updates/whatever. I have not tested it yet but it looks like a good approach to deal with collections which apparently cannot be handled by ORDS "out of the box". I had experimented with using the bulkload approach to load a temp table but it was for csv only and a bit tedious. Here's Jeff Smiths blog post on that
I have not tested this yet, I rebuilt my approach to send each entry individually but eventually I'll need to use this. I'll update this answer when I do with examples.
I am facing the same issue and the reason would be what is posted in the below URL.
https://community.oracle.com/thread/2182167?start=0&tstart=0
"In APEX Listener 1.1 the PL/SQL Hander will automatically convert JSON properties to implicit parameters. Note this will only work for simple JSON objects, arrays or nested object are not supported."
Basically - one can't pass collections/arrays. I'm not sure if this has changed now or if there are any plans to change this in the roadmap.

Accessing data from API json response. Arrays? Laravel

I am trying to access the steamid data in a json response returned by an API, specifically the Steam API.
The responses look like this:
I've made it return json but why do I see array all over the place?
How would I access the steamid data? I'm getting a bit confused as I thought this would be json.
I'm using guzzle to get the data and converting it to json using the guzzle json() method:
Any help would be appreciated.
Thanks!
The API is indeed using JSON to send/receive , however JSON is just a string, so in order to use that data PHP must parse it, which is automatically handled by guzzle, so as soon as you get the data back it has automatically decoded the data into a usable format for yourself.
It does this using the json_encode() and json_decode() functions.
You'd be able to access the steamid with the following.
// Assuming $data is your response from the API.
$players = array_get($data, 'response.players', []);
foreach($players as $player)
{
$steamId = array_get($player, 'steamid', null);
}
Using the laravel helper array_get() function is a great way of ensuring you return a sane default if the data doesn't exist as well as eliminating the need to keep doing things like isset() to avoid errors about undefined indexes, etc. http://laravel.com/docs/5.1/helpers
Alternativly not using the laravel helpers you could use something similar to below, although I'd advise you add checks to avoid the aforementioned problems.
foreach($data['response']['players'] as $player)
{
$steamId = $player['steamid'];
}
If you didn't want guzzle to automatically decode the API's JSON I believe you should just be able to call the getBody() method to return the JSON string.
$json = $response->getBody();

Convert JSON contents into HTML

This has probably been asked a load of times for, so forgive me for asking again.
I have a need to display the contents of a Json string as a formatted HTML fragment. It will be purely a read only view, the Json will vary as well.
I have seen modules out there that deal with form generation based of Json schemas but in my case there is no schema.
Is there anything out there anyone can recommend?
If you are looking for a library to use a quick google search found this.
www.json2html.com
I'm not sure if you are trying to use json data that pre-exists or starting from scratch as you did not provide an example but if you are starting from scratch this might be a good tool to design around.
This may be too limited, but if you're just looking for a pretty-printed view of your json, JSON.stringify supports that out of the box. I use this custom filter:
.filter('pretty', function () {
return function (json) {
return JSON.stringify(json, undefined, 2);
};
})
<pre ng-bind="myData | pretty"></pre>
I haven't come across anything standalone that does this in a generic sense... my approach has been to 'roll my own' so to speak and build to suit my needs like so:
$.each(retrievedStatusData, function(i, val){
$('ul').append('<li class="gamer-list-item">' + val.gamertagis + '</li>');
$('li').eq(i).prepend('<img src="' + val.gamercard.gamerpicSmallImagePath + '" class="gamer-pic">');
});
... which would produce an unordered list with the gamertag / name and a small thumbnail photo for each object in the JSON data source Im working with.
Now I HAVE on occasion, when inspecing JSON structures at a birds eye view sometimes done a loop over JSON and used sort of a for each key loop that displays ALL the JSON data in a 2 column table, the key on the left and value on the right. But that is only really useful for simple JSON data I guess.

Wrapping JSON payload with key in EmberJS

Ok basically I am sending a POST request with some JSON payload in it to Codeigniter. I use RESTAdapater. JSON get sent there with no key, so I have no access to it.
Here is model:
App.Bookmark = DS.Model.extend({
title: DS.attr("string"),
url : DS.attr("string")
});
Here is controller:
App.BookmarksNewController = Ember.ObjectController.extend({
save: function(){
this.get("model.transaction").commit();
this.get("target").transitionTo("bookmarks");
}
});
In REST implementation in CI that I use standard way to access the post request is $this->input("key"). But when the above request is generated, only raw JSON data is sent. Therefore I don't seem to have a way to reference it in any way.
Take this example:
function post(){
$this->response(var_dump(file_get_contents("php://input")),200);
}
Gives me this output:
string(48) "{"bookmark":{"title":"sdffdfsd","url":"sdfsdf"}}"
what I would like to see is:
string(48) payload="{"bookmark":{"title":"sdffdfsd","url":"sdfsdf"}}"
Then is server I would be able to access this JSON with something like $this->post("payload").
So 1 of 2. Anyway to wrap the JSON payload with key? Or anyway to access raw JSON data in CI with no key available??
Ok figured it out myself (or rather read properly the examples).
When using Adam Whitney's fork of Phil Sturgeons REST controller for CodeIgniter the JSON payload will be available in $this->_post_args. And in the underlying implementation he uses my already mentioned file_get_contents("php://input").
EDIT: Same convention applies for other type of requests as well, for example DELETE request data will be available in $this->_delete_args. Or $this->_args is the "magic" place where all types of args can be found.