Calling an actual API with vertx in Test - java

I want to check the data returned by the call, its suppose to be an array with name "data"
"success": true,
"serverName": "mma.tour.com",
"data": [
[
"01.08.2018",
[
"01.08"
],
"Ср",
8,
"09.08",
[....... etc
My api call goes like this
public static JsonObject clientTest() {
Vertx vertx = Vertx.vertx();
WebClient client = WebClient.create(vertx);
client
.get("https://www.mma-tour.com/tariffsearch/getResult?" +
"priceMin=0&priceMax=1500000&currency=533067&nightsMin=6&nightsMax=8" +
"&hotelClassId=269506&accommodationId=2&rAndBId=15350&tourType=1&" +
"locale=ru&cityId=786&countryId=1104&after=01.08.2018&before=01.08.2018&" +
"hotelInStop=false&specialInStop=false&version=2&tourId=1285&" +
"tourId=12689&tourId=12706&tourId=143330&tourId=9004247&" +
"tourId=4433&tourId=5736&tourId=139343&tourId=4434&tourId=12691&" +
"tourId=21301&tourId=12705&tourId=149827&tourId=4151426&hotelClassBetter=true&" +
"rAndBBetter=true&noTicketsTo=false&noTicketsFrom=false&searchTypeId=3&" +
"recommendedFlag=false&salePrivateFlag=false&onlineConfirmFlag=false&contentCountryId=1102")
.send(ar -> {
if (ar.succeeded()) {
// Obtain response
HttpResponse<Buffer> response = ar.result();
Tour tour = new Tour.TourBuilder().build();
JsonObject myTourJson = response.bodyAsJsonObject();
myTourJson.getJsonArray("data"); //here
} else {
}
});
return null;
}
Above i tried to get data and write a test to check some data is returned but it fails during debug doesnt even get to "data"

Related

how to insert an array to JSONArray with rest assured

I want to insert the array with Rest Assured.
tokenUUIDs - is an array ( A variable that I defined in a previous step).
When I run the code - tokenUUIDs received a correct value But ArraytokenUUIDs have not received something good. He received : [[Ljava.lang.String;#6fc0bbc6]
This is my Method:
public static void releaseTokens(String[] tokenUUIDs )
{
try{
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
JSONObject releaseTokens = new JSONObject();
releaseTokens.put("partnerCode", commonOps.partnerCode);
releaseTokens.put("apiAccessToken",commonOps.openAccessToken);
releaseTokens.put("sessionUUID",SessionUUID);
releaseTokens.put("taskUUID","TaskUUID");
JSONArray ArraytokenUUIDs = new JSONArray();
ArraytokenUUIDs.add(tokenUUIDs);
releaseTokens.put("tokenUUIDs", ArraytokenUUIDs);
request.body(releaseTokens.toJSONString());
Response response = request.post((getData("APIenv") + "/api/sessions/releaseTokens.php"));
int code = response.getStatusCode();
Assert.assertEquals(code, 200);
System.out.println("Status code for releaseTokens.php is" +code );
ResponseBody bodyreleaseTokens = response.getBody();
System.out.println("Body bodyreleaseTokens.php " + bodyreleaseTokens.asString() );
String statusbodyreleaseTokens = bodyreleaseTokens.asString();
String status = response.getBody().jsonPath().getString("status");
Assert.assertEquals(status, "OK");
test.log(LogStatus.PASS, "bodyreleaseTokens is done" );
}
catch (Exception e)
{
test.log(LogStatus.FAIL, "bodyreleaseTokens is not done");
test.log(LogStatus.FAIL, e.getMessage());
fail ("bodyreleaseTokens is not done");
}
Try to add every token individually
for (String s : tokenUUIDs){
ArraytokenUUIDs.add(s);
}
Change
ArraytokenUUIDs.add(tokenUUIDs);
to
for (String tokenUUID : tokenUUIDs) {
ArraytokenUUIDs.add(tokenUUID);
}
Also consider that variables in java are named with lowercase first letter as a standard to avoid confusion with classes.

How can I get specific object from methods response JSON

I want to call another method if the condition is satisfied with the response of first method. But the response is in JSON and has many objects. I want to check if "RESPCODE" is "01" and if it is call a method.
Method:
#Override
public void onTransactionResponse(Bundle inResponse) {
Log.d("LOG", "Payment Transaction is successful " + inResponse);
if(inResponse.toString().equals("01")) {
CheckoutProcess();
} else {
Toast.makeText(getApplicationContext(), "Transaction Failed ", Toast.LENGTH_LONG).show();
Log.d("LOG", "Payment Transaction : " + inResponse);
}
}
Response:
TXNAMOUNT = 1000.00
PAYMENTMODE = PPI
CURRENCY = INR
TXNDATE = 2018-04-17 18:56:08.0
STATUS = TXN_SUCCESS
RESPCODE = 01
RESPMSG = Txn Success
GATEWAYNAME = WALLET
BANKTXNID =
BANKNAME = WALLET
org.json library should be enough if it is only one or two properties you are interested in.
Use org.json library to parse it and create JsonObject:
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values:
int respcode = jsonObj.getInt("RESPCODE");
You can see a complete example here:
How to parse JSON in Java

How do I look up a cognito user by their sub/UUID?

I want to look up a user in my Cognito user pool by their sub, which as far as I can tell, is just their UUID. I would like to do this in Java within a Lambda function but cannot find how to do this in AWS's documenation. Any thoughts?
Now it works.
http://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html
"sub" in list of supported attributes.
Example for JavaScript:
var cog = new AWS.CognitoIdentityServiceProvider();
var filter = "sub = \"" + userSub + "\"";
var req = {
"Filter": filter,
"UserPoolId": "your pool id" // looks like us-east-9_KDFn1cvys
};
cog.listUsers(req, function(err, data) {
if (err) {
console.log(err);
}
else {
if (data.Users.length === 1){ //as far as we search by sub, should be only one user.
var user = data.Users[0];
var attributes = data.Users[0].Attributes;
} else {
console.log("Something wrong.");
}
}
});
As of today this is not possible with Cognito User Pools.
Users can only be looked up using their username or aliases. ListUsers API also allows users to be searched by providing search filters on some standard attributes but sub is not one of them.
// class var
protected final AWSCognitoIdentityProviderClient identityUserPoolProviderClient;
// initialize the Cognito Provider client. This is used to talk to the user pool
identityUserPoolProviderClient = new AWSCognitoIdentityProviderClient(new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY));
identityUserPoolProviderClient.setRegion(RegionUtils.getRegion(USER_POOL_REGION));
// ...some init code omitted
// build the request
AdminGetUserRequest idRequest = new AdminGetUserRequest();
idRequest.withUserPoolId(USER_POOL_ID);
idRequest.withUsername(username);
// call cognito for the result
AdminGetUserResult result = identityUserPoolProviderClient.adminGetUser(idRequest);
// loop through results
List<UserType> userTypeList = result.getUsers();
// loop through them
for (UserType userType : userTypeList) {
List<AttributeType> attributeList = userType.getAttributes();
for (AttributeType attribute : attributeList) {
String attName = attribute.getName();
String attValue = attribute.getValue();
System.out.println(attName + ": " + attValue);
}
}
Old question, but you the username parameter is overloaded in Cognito's adminGetUser method. It is, unfortunately, not documented: adminGetUser SDK
Here's a snippet:
const params = {
UserPoolId: 'someUserPoolId'
Username: 'random-string-sub-uuid',
};
CognitoService.adminGetUser(params,(err, data) => {
console.log(data);
})
Returns:
{ Username: 'random-string-sub-uuid',
UserAttributes:
[ { Name: 'sub', Value: 'random-string-sub-uuid' },
{ Name: 'custom:attributeName', Value: 'someValue' },
{ Name: 'email_verified', Value: 'false' },
{ Name: 'name', Value: 'nameValue' },
{ Name: 'email', Value: 'user#stackoverflow.com' } ],
UserCreateDate: 2018-10-12T14:04:04.357Z,
UserLastModifiedDate: 2018-10-12T14:05:03.843Z,
Enabled: true,
UserStatus: 'CONFIRMED' }

Better Java API for elasticsearch?

I am starting out on Elasticsearch. The scalability and performance is awesome, but I'm having trouble with the java API. Given some profile data where the id is a username and the profile contains attributes and scores (eg strength : 30, dexterity : 72, magic : 48) I want to get the top profiles for a particular combination of attributes eg strength + dexterity, or strength + magic etc.
Here is a query that I've used in Sense, which does exactly what I need:
GET_search{
"size": 0,
"aggs": {
"group by profile": {
"terms": {
"field": "profileId",
"order": {
"score_return": "desc"
}
},
"aggs": {
"score_return": {
"sum": {
"script": "doc['strength'].value + doc['dexterity'].value"
}
}
}
}
}
}
So now I want to port this query into my Java code. I managed to get it working, but it feels like it's extremely ugly - is there a better way of querying this data, or perhaps some library out there with a nice API, that can bind results to fields with annotations etc? Any suggestions welcome. This is what I have so far (it works, I just don't like the look of the code):
private void run() throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByName(HOST_IP);
InetSocketTransportAddress transportAddress = new InetSocketTransportAddress(inetAddress, HOST_PORT);
Client client = TransportClient.builder().build().addTransportAddress(transportAddress);
String queryString = "{ \"aggs\": { \"group by profile\": { \"terms\": { \"field\": \"profileId\", \"order\": { \"score_return\": \"desc\" } }, \"aggs\": { \"score_return\": { \"sum\": { \"script\": \"doc['dexterity'].value + doc['strength'].value\" } } } } } }";
//Sample Query - JSONObject
//We convert the raw query string to JSONObject to avoid query parser error in Elasticsearch
JSONObject queryStringObject = new JSONObject(queryString);
//Elasticsearch Response
SearchResponse response = client.prepareSearch("profiles").setTypes("profile").setSource(queryStringObject.toString()).execute().actionGet();
//Elasticsearch Response Hits
SearchHits hits = response.getHits();
Aggregations aggregations = response.getAggregations();
Map<String, Aggregation> aggsMap = aggregations.asMap();
Aggregation groupBy = aggsMap.get("group by profile");
System.out.println(groupBy);
StringTerms st = ((StringTerms)groupBy);
System.out.println(st);
List<Bucket> buckets = st.getBuckets();
for(Bucket bucket : buckets) {
System.out.println(bucket.getKeyAsString());
Aggregation score = bucket.getAggregations().get("score_return");
String value = ((InternalSum)score).getValueAsString();
System.out.println(value);
}
client.close();
}

building async httpbuilder similar to httpbuilder

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

Categories