how to pass date in $http.get request - angularjs

i have list of task in my database. i want to filter by date(completed date)
how to pass date with $http get request.i tried some code.it is giving exception.
can any one help me.
angular:
$scope.date=1468175400000;
var deadline = new Date($scope.date);
$http.get(
'/user/task/gettasks/?status=' + $scope.status
+ '&priority=' + $scope.priority
+ '&projectId=' + $scope.project+'&deadline='+deadline).success(
function(response) {
debugger
$scope.tasks = response;
}).error(function(error) {
console.log(error)
})
service(spring):
#RequestMapping("/gettasks")
#JsonView({ TaskJsonView.Summary.class })
public List<Task> getTasks(#RequestParam(value="status" ) String status,
#RequestParam("priority") String priority,
#RequestParam("projectId") String projectId,#RequestParam("deadline") Long deadline) {
System.out.println(deadline);
return taskControllerService.getTasks(status, priority, projectId,deadline);
}
error:
Object {
timestamp: 1468819101831,
status: 400,
error: "Bad Request",
exception: "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
message: "Failed to convert value of type [java.lang.String]… "
MonJul11201600: 00: 00 GMT0530(IndiaStandardTime)
""…
}
error: "Bad Request"
exception: "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException"
message: "Failed to convert value of type [java.lang.String] to required type [java.lang.Long]; nested exception is java.lang.NumberFormatException: For input string: "
MonJul11201600: 00: 00 GMT0530(IndiaStandardTime)
""
path: "/user/task/gettasks/"
status: 400 timestamp: 1468819101831 proto: Object

For deadline you are passing a date object.
Pass this instead new Date($scope.date).getTime() this will send the deadline as long timestamp.
var deadline = new Date($scope.date).getTime();

From the exception i can see the deadline date is not parsed correctly. From UI you are sending Date object and at server side you are accepting as Long value. Please make sure you keep the data type same at both end.
If the date is epochtime format then first convert like this and attach it to request.
var time = new Date(0);
var deadLineDate = deadLineDate / 1000;
time.setUTCSeconds(deadLineDate);
requestObject = time.toISOString().slice(0, 10);
Now requestObject is string, please accept as String # server side.
Let me know if it helps.

Related

how to retrieve values of the map returned by jsonPath().getMap methods of rest assured

how to retrieve values of the map returned by jsonPath().getMap methods of rest assured
I am trying to get the response on below api in Map, which I am able to successfully get but when I try to access the value of key "id" in the below code, I get cast Error on line "String id = test.get("id");"
public void testRestAssured() {
Response apiResponse = RestAssured.given().get("https://reqres.in/api/user/2");
Map<String, String> test = apiResponse.jsonPath().getMap("data");
System.out.println(test);
String id = test.get("id");
System.out.println("ID : " + id);
}
Error
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
I tried to do many things like
String id = test.get("id").toString();
or
String id = String.valueOf(test.get("id"));
but nothing helped in resolution
api response is as follows
{
"data": {
"id": 2,
"name": "fuchsia rose",
"year": 2001,
"color": "#C74375",
"pantone_value": "17-2031"
}
}
Try the below code, it is working fine for me:
Response apiResponse = RestAssured.given().get("http://reqres.in/api/user/2");
Map<Object, Object> test = apiResponse.jsonPath().getMap("data");
System.out.println(test);
String id = test.get("id").toString();
System.out.println("ID : " + id);
The changes I have done is: change Map of (String, String) to Map (Object, Object) because we know that each key of map is string but value could be of any data type.
I hope it will solve your problem.
Correct code is
Response apiResponse = RestAssured.given().get("http://reqres.in/api/user/2");
Map<Object, Object> test = apiResponse.jsonPath().getMap("data");
System.out.println(test);
for (Object e : test.keySet()) {
System.out.println(" Key is " + e + " , value is " + test.get(e));
simply try this:
import com.jayway.restassured.path.json.JsonPath;
JsonPath extractor = JsonPath.from(apiResponse.toString());
String id = extractor.getString("data.id");
You should define Object for map value. Because your json values are different types (String and int).
// define Object type for map values
Map<String, Object> test = apiResponse.jsonPath().getMap("data");
// use casting for assigning
int id = (int) test.get("id");
Do you really need to make from your response map object?
If not you can use this one:
String id = RestAssured.given().get("https://reqres.in/api/user/2")
.then().extract().jsonPath().getString("data.id");

Error in JSON.parse() (when called from API Gateway)

I'm working on AWS lambda + API Gateway, and I need to pass an array of numbers in the url (GET method) for a REST call. It seems a good way is to pass the numbers as string (comma separated) and then use JSON.parse for the conversion to an array of numbers.
Following is the AWS lambda code I'm using;
exports.handler = (event, context, callback) => {
var arr = JSON.parse('[' + event.numbers + ']');
console.log("array: " + arr);
// TODO implement
callback(null, 'Hello from Lambda');
};
I'm testing this function in AWS Lambda using this Input test event;
{
"numbers": "1,5"
}
And everything works as expected; no errors.
However, when I test it via API Gateway, and passing the numbers as string in the query, I get following error (observed via CloudWatch);
*19:19:02
START RequestId: eabab882-8cee-11e7-8e2f-79d3086e061f Version: $LATEST
19:19:02
2017-08-29T19:19:02.688Z eabab882-8cee-11e7-8e2f-79d3086e061f SyntaxError: Unexpected token u in JSON at position 1 at Object.parse (native) at exports.handler (/var/task/index.js:4:20)
19:19:02
END RequestId: eabab882-8cee-11e7-8e2f-79d3086e061f
19:19:02
REPORT RequestId: eabab882-8cee-11e7-8e2f-79d3086e061f Duration: 215.25 ms Billed Duration: 300 ms Memory Size: 128 MB Max Memory Used: 18 MB
19:19:02
RequestId: eabab882-8cee-11e7-8e2f-79d3086e061f Process exited before completing request*
This is the request passed to lambda as shown in the log;
"body-json" : {},
"params" : {
"path" : {
}
,"querystring" : {
"numbers" : "1,6"
}
,"header" : {
}
},
"stage-variables" : {
},
I can't figure out what the problem is, since I'm passing same string in both cases.
I would appreciate any help.
Thanks
Gus
With this input json informed, you need to get it like this:
var arr = JSON.parse('[' + event.params.querystring.numbers + ']');
rather than:
var arr = JSON.parse('[' + event.numbers + ']');
Or make a body mapping template to stay the way you want:
{ "number": "$input.params('number')" }
http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
I hope I have helped!

Collect errors with Gatling?

In my long, but simple awesome Gatling simulation, I have few responses that ended with error 500. Is it possible to tell gatling to collect these error responses messages in a file during the simulation?
No in production mode. You only have them when debug logging is enabled.
It is possible to collect what ever you want and save it into simulation.log file. Use extraInfoExtractor method when you define protocol:
val httpProtocol = http
.baseURL(url)
.check(status.is(successStatus))
.extraInfoExtractor { extraInfo => List(getExtraInfo(extraInfo)) }
Then define in your getExtraInfo(extraInfo: ExtraInfo) method whatever criteria you want. Example bellow outputs request and response in case of debug is enables via Java System Property OR response code is not 200 OR status of request is KO (it can be KO if you have setup some max time and this max time gets increased)
private val successStatus: Int = 200
private val isDebug = System.getProperty("debug").toBoolean
private def getExtraInfo(extraInfo: ExtraInfo): String = {
if (isDebug
|| extraInfo.response.statusCode.get != successStatus
|| extraInfo.status.eq(Status.valueOf("KO"))) {
",URL:" + extraInfo.request.getUrl +
" Request: " + extraInfo.request.getStringData +
" Response: " + extraInfo.response.body.string
} else {
""
}
}

Trying to post an array with `pg`, but keep getting wrong type error - Postgres, Express, Node

I have a route in my express app that takes an array and I am trying to update my db with the array. Here is my route:
exports.postUser = function(req, res) {
var query = client.query('insert into user_subservices(user_id, subservice_id) select $1 id, x from unnest(ARRAY[$2]) x', [req.body.id, req.body.services]);
query.on('row', function(row, result) {
result.addRow(row);
});
query.on('end', function(result) {
res.json(result);
});
} ;
I am trying to do a query where I add each element in the array individually like this:
INSERT INTO user_subservices(user_id, subservice_id)
SELECT 1 id, x
FROM unnest(ARRAY[1,2,3,4,5,6,7,8,22,33]) x;
But I keep getting an error that says that my type is wrong:
Error: column "subservice_id" is of type integer but expression is of type text
I assumed my body coming in on my REST call was text, so then I tried to convert the array with this:
var intArray = _.map(req.body.services, function(a) {
return parseInt(a);
});
But I still got the same error that it was of type text. What else do I need to do to make this work?

Sending array to populate geospatial field using Mongoose + NodeJS

I'm trying to save a geospatial array into a Schema. Here is my Schema (I'm using Moongose + Express + NodeJS):
var Route = new schema({
route: String,
time: Number,
distance: Number,
geo: {type: [Number], index: '2d'},
created: { type: Date, default: Date.now }
}, {collection: 'route'});
var routeModel = mongoose.model('Route', Route);
And here is an example of the data I'm sending to populate an instance of that schema:
{
distance: 6.899893863658173,
geo:[ [13.695901, -89.24937], [13.706500876975248, -89.24967010761316],
[13.711430396814366, -89.2561502488519] ],
route: "Running route",
time: 31
}
First noob question is: is it possible to do what I'm doing? sending an array of arrays in geo?
And here is how I save the data:
socket.on('new_route', function (data){
var route = new routeModel();
route.route = data.route;
route.time = data.time;
route.distance = data.distance;
route.geo = data.geo;
route.save(function(err) {
if (err) throw err;
socket.emit("route_saved", {mensaje: "Well done!"});
app.listen(8080);
});
});
If I send and empty array on geo, all works fine. However, I'm getting the following error
"Cast to number failed for "13.695901, -89.24937, 13.706500876975248, -89.24967010761316..." at path "geo".
whenever I send an array (like the one posted above) on "geo".
So second question, any ideas on why I'm getting my array threated like a big string?
Mongoose doesn't support arrays of arrays of any type ([[Number]]). It may be supported in the future.
If your use case requires this schema, use a Mixed type which allows ad-hoc structures but provides no change tracking or casting.
new Schema({ geo: { type: Schema.Types.Mixed, index: '2d' }})
As for arrays being treated as a big string, mongoose converts the invalid argument to a string and what you observe is an artifact of how javascript converts arrays to strings.
var a = [3,4,5]
console.log(String(a)) // '3,4,5'

Resources