Iterating over PagedList result retrieved from the Facebook Graph API - java

Trying to retrieve all marketing accounts of a Facebook business account using the spring social framework for Facebook .
I want to know if there is any better way to it other than what i did below ?
Does what i did for paging the query result is the right way to do it ?
Is there another way to retrieve data from the Facebook Marketing API ?
I really appreciate any help you can provide.
public List<String> getListAdAccountsId(String businessAccountId) {
final List<String> accountsId = new ArrayList<String>();
final MultiValueMap<String, String> queryParameters = new LinkedMultiValueMap<String, String>();
queryParameters.add("fields", "account_id");
queryParameters.add("offset", "0");
PagedList<Map> pagedResultSubSet = facebook.fetchConnections(businessAccountId, "adaccounts", Map.class,
queryParameters);
do {
queryParameters.set("offset", pagedResultSubSet.getNextPage().getOffset().toString());
pagedResultSubSet = facebook.fetchConnections(businessAccountId, "adaccounts", Map.class, queryParameters);
accountsId.addAll(pagedResultSubSet.parallelStream().map(e -> e.get("id").toString())
.collect(Collectors.toList()));
} while (pagedResultSubSet.getNextPage() != null);
return accountsId;
}

Related

How to pass json data as query parameter in GET call using Restassured

I am able to pass the JSON data as Query Parameters in which I am passing particular kit_config_id in the form of HasMap. Now I want the API to return the data related to only specified kit_config_id but its giving me all records.
What wrong I am doing here?
// Request object using RestAssured
RequestSpecification httpRequest = RestAssured.given();
HashMap<String, String> params = new HashMap<String, String>();
params.put("kit_config_id", "60db53ec7a334172b005b692");
Response response = httpRequest.given().baseUri("https://qa-api-test.com").param("query", params).when().get("/imageProps");
Complete Url of GET call is : https://qa-api-tests.com/imageProps?params={"query": {"kit_config_id": "60db53ec7a334172b005b692"}}
If you want query like this
/imageProps?params={"query":{"kit_config_id":"60db0d5d7a334172b005b665"}}
Using this:
HashMap<String, Object> kit_config = new HashMap<>();
kit_config.put("kit_config_id", "60db0d5d7a334172b005b665");
HashMap<String, Object> query = new HashMap<>();
query.put("query", kit_config);
RestAssured.given().log().all().baseUri("your-url")
.queryParams("params", query)
.when().get("/imageProps");
If you want query like this
/imageProps?kit_config_id=60db53ec7a334172b005b692
Just need:
HashMap<String, Object> kit_config = new HashMap<>();
kit_config.put("kit_config_id", "60db0d5d7a334172b005b665");
RestAssured.given().log().all().baseUri("https://postman-echo.com")
.queryParams(kit_config)
.when().get("/imageProps");

Android-Stripe add missing parameters while account creating

I was trying to implemented stripe payment gateway. Every thing is going fine. I was able to create connected account for the user in my stripe dashboard, but the problem is I'm missing following parameter
Website
SSN
Industry
Now I want to know how to add these parameters while creating account.
I have add the screen shot from stripe dashboard and here is the code:
Map<String, Object> dob =
new HashMap<>();
dob.put("day", "12");
dob.put("month", "1");
dob.put("year", "1991");
Map<String, Object> address =
new HashMap<>();
Map<String, Object> address_pram =
new HashMap<>();
address_pram.put("city", "Baton Rouge");
address_pram.put("line1", "1 Calais Ave");
address_pram.put("postal_code", "70806");
address_pram.put("state", "Louisiana");
address.put("address", address_pram);
address.put("dob", dob);
address.put("email", "ahmad#example.com");
address.put("first_name", "ahmad");
address.put("last_name", "bajwa");
address.put("phone", "+12015551023");
//address.put("website", "www.goldenkeystone.com");
//address.put("industry", "");
// address.put("ssn", "000000000");
Map<String, Object> acceptance =
new HashMap<>();
acceptance.put("date", System.currentTimeMillis() / 1000L);
acceptance.put("ip", ipString);
Map<String, Object> cardPayments =
new HashMap<>();
cardPayments.put("requested", true);
Map<String, Object> transfers = new HashMap<>();
transfers.put("requested", true);
Map<String, Object> capabilities =
new HashMap<>();
capabilities.put("card_payments", cardPayments);
capabilities.put("transfers", transfers);
Map<String, Object> params = new HashMap<>();
params.put("type", "custom");
params.put("country", "US");
params.put("tos_acceptance", acceptance);
params.put("business_type", "individual");
params.put("individual", address);
params.put("capabilities", capabilities);
Account account = Account.create(params, requestOptions);
Note: If still question is unclear, I would be glad if you add your contribution.
That data and other sensitive information would be collected by Stripe during the onboarding via Account Links: stripe.com/docs/connect/connect-onboarding
It's not something that you can pass to the Accounts API. See here for more information: https://stripe.com/docs/connect/collect-then-transfer-guide?platform=web#create-an-account-link

No attached payment source for Stripe subscription creation

I'm currently migrating my app from using the Stripe Charges API to use the Stripe PaymentIntents API, in order to comply with SCA regulations.
My subscription creation code roughly looks like this:
Map<String, Object> srchOpts = new HashMap<>();
srchOpts.put("email", userEmail);
List<Customer> matchingCustomers = Customer.list(srchOpts).getData();
Customer customer = null;
Subscription subscription = null;
if ( matchingCustomers.isEmpty() ){
Map<String, Object> params = new HashMap<String, Object>();
params.put("email", userEmail);
params.put("payment_token", stripeToken);
customer = Customer.create(params);
}
else if (matchingCustomers.size() == 1) {
customer = matchingCustomers.get(0);
Map<String, Object> params = new HashMap<String, Object>();
params.put("source", stripeToken);
PaymentSourceCollection paymentSources = customer.getSources();
paymentSources.create(params);
}
Map<String, Object> item = new HashMap<String, Object>();
item.put("plan", planId); // e.g. my-pro-plan (no trial days)
Map<String, Object> items = new HashMap<String, Object>();
items.put("0", item);
Map<String, Object> params = new HashMap<String, Object>();
params.put("items", items);
params.put("customer", customer.getId());
params.put("off_session", false);
subscription = Subscription.create(params);
I can see on the Stripe dashboard (in test mode) that the customer is created and has the card which I specified, but the Subscription.create call fails with:
com.stripe.exception.InvalidRequestException: This customer has no attached payment source; code: resource_missing
The customer has a card set (there is only 1 so it has to be the default card), the customer creation call happens before the subscription creation call and the customer ID is being passed to the sub creation call. Is there some other parameter I need to pass in?
I've tried setting Customer.invoice_settings.default_payment_method when the customer is being created, and that gets me past the subscription creation. Everything looks fine from the Stripe dashboard, except that I'm testing with an SCA test card, so the transaction is incomplete until the customer has authenticated further.
I need the client secret token from the response to continue, and I thought that I would get it from #Subscription.getLatestInvoiceObject().getPaymentIntentObject().getClientSecret() but the getLatestInvoiceObject() call is returning null.
I'm not setting collection_method on the Subscription object which defaults to charge_automatically. This is what I want because the customer is on-session and so the Invoice being null probably makes sense, but how do I get the client secret to pass back to the frontend? The SetupIntent object returned by the subscription response exposes a client secret, but that object is null too.
Subscription Invoices will use whichever of these three payment options are available (in order of preference):
The Subscription's default_payment_method (reference) or default_source (reference)
The Customer's invoice_settings.default_payment_method (reference)
The Customer's default_source (note: there is no concept of a default PaymentMethod on Customers)
Also worth noting is that PaymentMethods and Sources are two distinct resources. Cards (objects with ids prefixed with card_) can be used as either type.

How to fix JSON format issue in JAVA?

This is my 1st project in java spring. So i m trying to figure out the best way to do things.
I have several Rest Apis in my project for which different kinds of API response will be sent.
Somewhere i m getting data in List Format, somewhere else another format. So i m trying to figure out the best way to send response in JSON format.
One of the API Response i have is this:
{
"result": "true",
"message": null,
"data": "{\"id\":1,\"firstName\":\"test\",\"lastName\":\"test\",\"emailId\":\"test#test.com\",\"mobileNo\":\"1234567890\",\"alternateMobileNo\":\"1234567890\",\"username\":\"test\",\"password\":\"7c4a8d09ca3762af61e59520943dc26494f8941b\",\"status\":\"active\",\"userRole\":\"test\",\"dateCreated\":\"Feb 6, 2019\",\"permissions\":\"\"}"
}
My biggest issue is the formatting of data key in the above JSON.
This is my controller action:
#RequestMapping(value = "/admin/staff/get", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public Map get(HttpServletRequest request, #RequestParam Map<String, String> parameters) {
Map<String, String> response = new HashMap<>();
Gson gson = new Gson();
Staff staff = new Staff();
staff.setId(new Integer(parameters.get("id")));
List validateToken = loginAuthTokenService.validateToken(new Integer(request.getHeader("loginId")), request.getHeader("loginType"), request.getHeader("token"));
if (validateToken.size() > 0) {
Staff staffDetails = staffService.getStaff(staff.getId());
response.put("result", "true");
response.put("data", gson.toJson(staffDetails));
} else {
response.put("result", "false");
response.put("message", "No records found.");
}
return response;
}
Should I create a separate Class for sending API Response or anyone please guide me the proper way of sending response.
Thanks
Gson#toJson(Object) returns a String and that String is mapped as JSON key in your map.
You don't have to convert your object to a JSON, Spring will do it for you (it uses Jackson as JSON mapper so you don't have add Gson dependency to your project.
A simple and working implementation could be something like:
#RequestMapping(value = "/admin/staff/get", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<?> get(
#RequestParam("id") Integer id,
#RequestHeader("loginId") Integer loginId,
#RequestHeader("loginType") String loginType,
#RequestHeader("token") String token) {
List validateToken = loginAuthTokenService.validateToken(loginId, loginType, token);
if (!validateToken.isEmpty()) {
Stuff stuff = staffService.getStaff(id);
return ResponseEntity.ok(stuff);
}
return ResponseEntity.notFound().body("No records found.");
}
Also consider to not return a generic map from your method, but the Stuff object your front-end needs. In case of failure you should return a failure object with a specific http response code (e.g. 404, 400, 500...).
Take a look at this guide.
To format the the data attribute , you can store it in a map :-
Map<String, Object> map1= new HashMap<String, Object>();
and is you have multiple data attributes you can create an ArrayList of Maps :-
ArrayList<Map<String, Object>> dataClerk = new ArrayList<Map<String,Object>>();
I had a similar usecas so i used the below code :-
obj = parser.parse(response);
JSONObject jobj = (JSONObject)parser.parse(response);
JSONArray jsonarr_1 = (JSONArray) jobj.get(item);
for(int i=0 ;i<jsonarr_1.size();i++) {
Map<String, Object> entry = new HashMap<String, Object>();
org.json.simple.JSONObject temp= (org.json.simple.JSONObject)
jsonarr_1.get(i);
Set<String> attributes= temp.keySet();
for(String s: attributes) {
entry.put(s, temp.get(s));
}
}

How to read a table from dynamodb using Java?

I created a table in Amazon dynamodb with primary key Issue(String) which has data stored in it.I want to read the values from my table. I'm using the following code..
#DynamoDBTable(tableName="Incident")
AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient();
String tableName = "Incident";
Table table = dynamoDBClient.getTable("Incident");
Item getItem=dynamoDBClient.getItem();
I'm getting an error when calling the getTable method.... is it a predefined method just like createTable() or do we need to write our own..if so how?
And also what method should be used to read all items in the table..?
I used this link to write some of the code... http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/JavaDocumentAPIItemCRUD.html#JavaDocumentAPIGetItem
I'm new to Java please help..
Scan API can be used to get all the items from the table.
The scan should be done until LastEvaluatedKey is not null which is very important to get all the items. Otherwise, you will not get all the items if the table has many items i.e. the API will return 1 MB of data per scan.
A Scan operation performs eventually consistent reads by default, and
it can return up to 1 MB (one page) of data.
Scan API
Map<String, AttributeValue> lastKeyEvaluated = null;
do {
ScanRequest scanRequest = new ScanRequest()
.withTableName("ProductCatalog")
.withLimit(10)
.withExclusiveStartKey(lastKeyEvaluated);
ScanResult result = client.scan(scanRequest);
for (Map<String, AttributeValue> item : result.getItems()){
printItem(item);
}
lastKeyEvaluated = result.getLastEvaluatedKey();
} while (lastKeyEvaluated != null);
Here is example how to read data using Scan API :
#Override
protected ArrayList<String> doInBackground(String... params) {
String tableName = params[0];
ArrayList<String> tempList = new ArrayList<String>();
AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient (
new BasicAWSCredentials(Constants.ACCESS_KEY_ID,
Constants.SECRET_KEY));
ScanRequest scanRequest = new ScanRequest()
.withTableName(tableName);
//.withAttributesToGet("name");
com.amazonaws.services.dynamodb.model.ScanResult result = dynamoDBClient.scan(scanRequest);
for (Map<String, AttributeValue> item : result.getItems()) {
tempList.add(item.toString());
//analizeItem(tempList, item);
}
return tempList;
}
Reference from programcreeks
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().withRegion(Regions.AP_SOUTH_1).build();
DynamoDB dynamoDB = new DynamoDB(client);
Table table = dynamoDB.getTable("Student");
Item item = table.getItem("PK", "portion Key","SK","Sort Key");
System.out.println(item.toJSONPretty());

Categories

Resources