building async httpbuilder similar to httpbuilder - java

Might be the wrong place to post this but I have been messing around with async http builders trying to get basic cypher queries to work. It works with Http Builders but can't get it to work with the async version.
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6' )
#Grab(group='net.sf.json-lib', module='json-lib', version='2.4', classifier='jdk15' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
def query(statement, params,success, error) {
def http = new HTTPBuilder( 'http://localhost:7474' )
http.request( POST, JSON ) {
uri.path = '/db/data/cypher/'
headers.'X-Stream' = 'true'
requestContentType = JSON
body = [ query : statement , params : params ?: [:] ]
// uri.query = [ param : 'value' ]
response.success = { resp, json ->
if (success) success(json)
else {
println "Status ${resp.statusLine} Columns ${json.columns}\nData: ${json.data}"
}
}
response.failure = { resp, message ->
def result=[status:resp.statusLine.statusCode,statusText:resp.statusLine.reasonPhrase]
result.headers = resp.headers.collect { h -> [ (h.name) : h.value ] }
result.message = message
if (error) {
error(result)
} else {
println "Status: ${result.status} : ${result.statusText} "
println 'Headers: ${result.headers}'
println 'Message: ${result.message}'
}
}
}
}
query("MATCH n RETURN n;",[],{ println "Success: ${it}" },{ println "Error: ${it}" })
However I have tried this with the AsyncHttpBuilder. Couldn't get it to work. Now I am trying a simple thing and have been unable to get it to give anytype of useful result.
#Test
public void testQueue()
{
def http = new AsyncHTTPBuilder( poolSize : 1 ,
uri : 'http://localhost:7474/db/data/cypher' )
def responses = []
responses << http.post(query : [q: "MATCH n RETURN n;"]) {return it}
if (!responses.every{it.done})
{
println 'waiting...'
Thread.sleep(2000)
}
responses.each {
println(it)
}
http.shutdown()
}
Any thoughts? Thanks!

for reference: I've answered this at https://groups.google.com/forum/?fromgroups#!topic/neo4j/5Cle5vBsMXQ
you need to pass in the cypher query in the request's body and not as
query param. See https://gist.github.com/sarmbruster/8114445 for a
working example

Related

Unable to filter object from json array in groovy

In groovy, I have below object. (Type: [Ljava.lang.Object)
test = [
{
"id":"rod_1565173117796",
"userName":"rod",
"displayName":"Rod",
"date":1565173117796,
"comment":"ok"
},
{
"id":"rod_1565173139923",
"userName":"rod",
"displayName":"Rod",
"date":1565173139923,
"comment":"fine"
}
]
I want to modify / delete this list of JSON array based on id.
I tried below thing filter the required json object from list.
parsedJSON = parser.parseText(test);
parsedJSON.findAll{ it.id == 'rod_1565173139923' });
Which is giving me that
No such property: id for class: java.lang.String
What wrong i am doing?
Thanks!
just several syntax fixes and your code works:
def test = '''[
{
"id":"rod_1565173117796",
"userName":"rod",
"displayName":"Rod",
"date":1565173117796,
"comment":"ok"
},
{
"id":"rod_1565173139923",
"userName":"rod",
"displayName":"Rod",
"date":1565173139923,
"comment":"fine"
}
]'''
def parser = new groovy.json.JsonSlurper()
def parsedJSON = parser.parseText(test);
def filtered = parsedJSON.findAll{ it.id == 'rod_1565173139923' }

How to get value from jquery each loop when controller returns list

I have list and return from controller and i'm trying to show in a mvc view using jquery each loop function.I can get to list and send to view but when jquery loop start i cannot get index and value.I checked Console and Sources,values are there.
This is my controller codes
public JsonResult electric()
{
int id = Convert.ToInt32(Session["id"]);
string cs = "data source=LNPC;initial catalog=db;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework";
SqlConnection connection = new SqlConnection(cs);
SqlCommand command = new SqlCommand("electrcic_bills", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddWithValue("#id", id);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
List<analiz> TestList = new List<analiz>();
analiz electric;
while (reader.Read())
{
electric= new analiz();
electric.jan= Convert.ToDouble(reader["jan"].ToString());
electric.feb= Convert.ToDouble(reader["feb"].ToString());
electric.march= Convert.ToDouble(reader["march"].ToString());
electric.april = Convert.ToDouble(reader["april"].ToString());
TestList.Add(electric);
}
return Json(new { List = TestList }, JsonRequestBehavior.AllowGet);
}
Jquery codes
$("#electric").click(function () {
$("canvas#myCharts").remove();
$("#canvas1").append('<canvas id="myCharts" width="200" height="200"></canvas>');
$.ajax({
type: "GET",
url: "/MainController/electric",
dataType: "json",
success: function (List) {
var data = List.List;
$.each(data, function (index, value) {
alert(data);
});
},
});
});
With this method i cannot get value but when i write electric.push(List.List[0].jan._bills_electric) like this i can get value manualy perfctly.
This my Source codes from browser
Local List:List: Array(1)
0:
jan_bills: null
jan_bills_electric: 135
dec_bills: null
dec_bills_electric: 60
You are using List word in your return Json() statement. This may be ambiguous for Java.
Try using another name with camel case typography to solve the problem.
In your Javascript, try to use
var data = List["List"];
instead of
var data = List.List;
Okey i found my answer and where l am wrong.
First- there is nothing wrong in my controller
Second- in each loop function,my array not only array,it is array in OBJECT.I've found this link and try each loop in a each loop and i got my items from jquery loop.
var json = [
{ 'red': '#f00' },
{ 'green': '#0f0' },
{ 'blue': '#00f' }
];
$.each(json, function () {
$.each(this, function (name, value) {
console.log(name + '=' + value);
});
});

groovy grails async promise execute immediately

In the below code, inside controllerMethod , onComplete event execute immediately without waiting for the finishing of promiseList in the callApisInParallel method in groovy/grails
import grails.async.Promise
import grails.async.PromiseList
class asyncProgram {
def getReportTask() {
return task {
def res = reportService.fetchReport()
// api request
res
}
}
private def callApisInParallel() {
def promiseList = new PromiseList()
def reportTask = getReportTask()
promiseList << reportTask
//def apiResults = waitAll(promiseList)
//def results = apiResults[0]
// def res = results[0]
promiseList
}
def execute() {
Promise p = task {
def promiseList = callApisInParallel()
promiseList.onComplete { result ->
println "Promise returned $result"
//manipulate the data and then return the result
//resolve()
}
}
return p
}
def controllerMethod() {
Promise p = execute()
p.onComplete { result ->
}
}
}
I need something like "resolve" method in javascript which can tells the onComplete event of execute method that the onComplete is done and mark the current promise complete
I found one link
Groovy/Grails promises/futures. There is no .resolve(1,2,3) method. Strange?
but I am not able to understand in the above approach properly
If you are creating a promiseList with task here:
def promiseList = callApisInParallel()
then why are you not using it here?
p.onComplete { result ->
println "Promise returned $result"
//manipulate the data and then return the result
//resolve()
}
Change p.onComplete to promiseList.onComplete

Testing Grails App Generating pdf file Cannot get property 'config' on null object

I am trying to test a service class that will generate a pdf file but this error occurs:
[getDocument] EXCEPTION: variables: [input, input, input], message:
Cannot get property 'config' on null object
My Service class is:
class TemplateService {
static transactional = false
def grailsApplication
def getDocument(inputs, idTemp) {
def result
if(inputs) {
long dateBeginTransaction = System.currentTimeMillis()
try {
def http = new HTTPBuilder(grailsApplication.config.tempdoc.url?.replace("COI", idTemp))
http.auth.basic grailsApplication.config.rest.login, grailsApplication.config.rest.password
http.request(POST,JSON) { req ->
headers.'Accept' = 'application/json'
headers.'Content-type' = 'application/json'
body = [
inputs: inputs
]
response.success = { resp, json ->
log.info "[getDocument] time: " + (System.currentTimeMillis() - dateBeginTransaction) / 1000 + " ms"
result = json?.pdf
}
response.failure = { resp, reader ->
log.error "[getDocument] inputs: " + inputs + ", response: " + resp + ", message: " + reader?.message
}
}
} catch (Exception e) {
log.error "[getDocument] EXCEPTION: inputs: " + inputs + ", message: " + e.message
}
} else {
log.error "[getDocument] params sense valors"
}
result
}
}
This is my Test:
*Note inputs is an arraylist
void "generate document"() {
given: "generate document"
def TemplateService = new TemplateService()
when:
def result = TemplateService.getDocument(inputs, idTemp)
then:
result != null
result.size() > 0
where:
inputs = [ "input", "input", "input"]
idTemp = "12AD"
}
At the very least, you'll have to mock the config in your test. In Grails 3.3.5:
class PlaServiceSpec extends Specification implements ServiceUnitTest<Plaservice>, DataTest {
Closure doWithConfig() {{ config ->
config.plantidoc.url = 'my url'
}}
void "generate document"() {
given:
def variables = ["input:input", "input:input"]
def idPlantitlla = "12AD"
when:
def result = service.getDocument(variables, idPlantitlla)
then:
// test the result
}
}
you can make your test an Integration Test (move it to test/integration-test folder) and in this way grailsApplication will be injected into your service

Send two parameters from angular UI in post method and handled by java API

Just need guidance...
From controller to service, variables are accessible. But not available when they are send to api side. (With one variable it's working perfectly fine)
The variable values are coming after some calculations.
Service.js code...
function MySvcFunction(value1, value2) {
console.log('value1 : ', value1); //printing value1
console.log('value2 : ', value2); //printing value2
return $http.post('http://' + api_url + value1, value2).then(
function (response) {
//manage success
},
function (error) {
//manage error;
});
}
Controller.js code...
$scope.someFunction = function(){
console.log('value1 : ', value1); //printing value1
console.log('value2 : ', value2); //printing value2
MySvcController.MySvcFunction($scope.value1, $scope.value2).then(
function (response) {
//display on screen
});
And now api code in java...
Scenario-1 exception (with two #RequestBody)
#PostMapping(value = "/api_url")
public ResponseEntity<Object> MyFunction(#RequestBody Integer value1, #RequestBody Integer value2) {
System.out.println("value1 : "+ value1);
System.out.println("value2 : "+ value2);
}
//Exception:
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Stream closed; nested exception is java.io.IOException*/
Scenario-2 exception (with one #RequestBody)
#PostMapping(value = "/api_url")
public ResponseEntity<Object> MyFunction(#RequestBody Integer value1, Integer value2) {
System.out.println("value1 : "+ value1); //value1 : int val
System.out.println("value2 : "+ value2); //value2 : null
}
//Exception:
nested NullPointerException with root cause.
I got it working not sure whether right or not?
Controller.js
$scope.someFunction = function(){
var bothVar = {'value1': $scope.value1, 'value2': $scope.value2};
MySvcController.MySvcFunction(bothVar).then(
function (response) {
//display on screen
});
Service.js
function MySvcFunction(bothVar) {
return $http.post('http://' + api_url + bothVar).then(
function (response) {
//manage success
},
function (error) {
//manage error;
});
}
API side java code
#PostMapping(value = "/api_url")
public ResponseEntity<Object> suggestBreakfast(#RequestBody Map bothVar){
System.out.println("value1 is : "+ bothVar.get("value1"));
System.out.println("value2 is : "+ bothVar.get("value2"));
}
// And i am getting those two values here successfully

Categories