Can somebody please help me to restructure the following code using java8 features.
Here is my code.
private List<CreateChildItemResponse> createChildItems(String[] childUpcNumbers, String[] childItemNbrs,
ItemVo parentItem, UserVo user, boolean isEnableReverseSyncFlag, Integer parentItemNbr, Long parentUpcNbr,int childUpcNbrsize, ItemManagerDelegate managerDelegate) throws NumberFormatException, ValidationException,ChildNotFoundException, ResourceException, ChildItemException {
List<ItemVo> resultList = new ArrayList<ItemVo>();
List<CreateChildItemAssortmentResponse> relations = null;
CreateChildItemResponse response = new CreateChildItemResponse();
try {
for (int i = 0; i < childUpcNumbers.length; i++) {
// parentItem.setItemNbr(itemNumberList.get(i));
logger.info("-------Item Nbrs-----" + parentItem.getItemNbr());
ItemVo child = createItemForMigration(
populateChildItemVo(parentItem, getGtin(childUpcNumbers[i]), Integer.valueOf(childItemNbrs[i])),
user, isEnableReverseSyncFlag, managerDelegate);// null scales for all except scales integration
resultList.add(child);
}
relations = this.populateAssortmentRelationVo(parentItem.getItemNbr(), resultList);
response = getSuccessResponse(parentItemNbr, relations, parentUpcNbr);
// utx.commit();
} catch (Exception e) {
logger.info("Exception occurs while creating child item", e);
relations = this.populateAssortmentRelationVoForException(e, resultList);
response = getFailureResponseForException(parentItemNbr, relations, parentUpcNbr, e, resultList.size(),
childUpcNbrsize);
finalResponse.add(response);
throw new ChildItemException(e.getMessage(), finalResponse, e);
}
finalResponse.add(response);
return finalResponse;
}
here I am calling the below method in the above code
relations = this.populateAssortmentRelationVo(parentItem.getItemNbr(), resultList);
And the implementation is
private List<CreateChildItemAssortmentResponse> populateAssortmentRelationVo(Integer parentItemNumber,
List<ItemVo> childs) {
List<CreateChildItemAssortmentResponse> relationList = new ArrayList<CreateChildItemAssortmentResponse>();
for (ItemVo child : childs) {
CreateChildItemAssortmentResponse relation = new CreateChildItemAssortmentResponse();
relation.setItemNbr(child.getItemNbr());
relation.setUpcNbr(convertUpcToString(child.getEachGtin().getGtinNbr()));
relation.setStatus("SUCCESS");
relation.setMessage("");
relationList.add(relation);
}
return relationList;
}
Here I want to take a constructor for the populateAssortmentRelationVo() and how to use stream and mapper inside this.
First declare a mapping function:
private CreateChildItemAssortmentResponse> itemVoToResponse(ItemVo item) {
CreateChildItemAssortmentResponse response = new CreateChildItemAssortmentResponse();
response.setItemNbr(item.getItemNbr());
response.setUpcNbr(convertUpcToString(item.getEachGtin().getGtinNbr()));
response.setStatus("SUCCESS");
response.setMessage("");
return relationList;
}
and simply map all the elements of one list into another one:
relations = resultList.stream()
.map(this::itemVoToResponse)
.collect(toList());
I have ProductInfo object which looks like this
ProductInfo.java
public class ProductInfo
{
private List<String> servicetagInfo;
}
I have Order object like this which has list of Products info
OrderDetail.java
public class OrderDetail
{
private String orderNum;
private List<ProductInfo> productInfo;
}
And then I have a Response object which basically has List of Order objects
Response.java
public class Response
{
private List<OrderDetail> orderInfo;
}
I am getting response as expected.But right now in this format
orderInfo:
0: {orderNum: "162293591",...}
productInfo:
0: {servicetag_info: ["7LSMW33", "49SMW33"]}
1: {servicetag_info: ["JF6XN33", "CQ5XN33"]}
2: {servicetag_info: ["5VRR523", "13LR523"]}
Here I am trying to merge productInfo List to be like this
productInfo:
0: {servicetag_info: ["7LSMW33", "49SMW33","JF6XN33", "CQ5XN33","5VRR523", "13LR523"]}
Just add all strings into one main property.
Here is my code
List<String> serviceTagList = new ArrayList<>();
for (OrderDetail orderDetail : arInvoiceOrderResponseBody.getOrders()) { //Here i am getting orders from external service
if (orderDetail != null) {
if (orderDetail.getProductInfo() != null && orderDetail.getProductInfo().size() > 0) {
for (ProductInfo productInfoDetail : orderDetail.getProductInfo()) {
if (productInfoDetail != null) {
if (productInfoDetail.getServicetagInfo() != null) {
for (String serviceTag : productInfoDetail.getServicetagInfo()) {
serviceTagList.add(serviceTag);
}
}
}
}
}
}
ProductInfo productInfo = new ProductInfo();
productInfo.setServicetagInfo(serviceTagList);
orderDetail.setProductInfo(Arrays.asList(productInfo));
}
Can anyone suggest how can i achieve same using streams in java so that it will be readable.
Try this:
Set<String> tags = order.stream()
.flatMap(order -> order.getProductInfo().stream())
.map(ProductInfo::getServicetagInfo)
.collect(Collectors.toSet());
Full implementation:
for (OrderDetail orderDetail : arInvoiceOrderResponseBody.getOrders()) {
if (orderDetail != null && orderDetail.getProductInfo() != null) {
orderDetail.getProductInfo().removeAll(null); // Remove any null elems
Set<String> tags = orderDetail.getProductInfo().stream()
.flatMap(product -> (product.getServicetagInfo() == null) ? null : product.getServicetagInfo().stream())
.collect(Collectors.toSet());
tags.remove(null); // Remove null if exists
}
ProductInfo productInfo = new ProductInfo();
productInfo.setServicetagInfo(tags);
orderDetail.setProductInfo(Arrays.asList(productInfo));
}
With streams your code could be like this:
arInvoiceOrderResponseBody.getOrders().stream()
.filter(Objects::nonNull)
.forEach(YourClassName::mergeProductInfo);
The method mergeProductInfo would be:
private static void mergeProductInfo(OrderDetail orderDetail) {
List<String> serviceTagList = new ArrayList<>();
if (orderDetail.getProductInfo() != null) {
serviceTagList = orderDetail.getProductInfo().stream()
.filter(Objects::nonNull)
.map(ProductInfo::getServicetagInfo)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
ProductInfo productInfo = new ProductInfo();
productInfo.setServicetagInfo(serviceTagList);
orderDetail.setProductInfo(Arrays.asList(productInfo));
}
It could be simplified if you could be sure that you are not going to receive null lists or elements.
I am able to create order using square(v2/locations/location_id/orders)api and getting order id. But I am not able to get this order details and also how I can see this created order on square dashboard? please help me.
I am using the below method for doing it:
public CreateOrderResponse createOrder(String locationId, CreateOrderRequest body) throws ApiException {
Object localVarPostBody = body;
// verify the required parameter 'locationId' is set
if (locationId == null) {
throw new ApiException(400, "Missing the required parameter 'locationId' when calling createOrder");
}
// verify the required parameter 'body' is set
if (body == null) {
throw new ApiException(400, "Missing the required parameter 'body' when calling createOrder");
}
// create path and map variables
String localVarPath = "/v2/locations/{location_id}/orders".replaceAll("\\{" + "location_id" + "\\}",
apiClient.escapeString(locationId.toString()));
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = { "application/json" };
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = { "application/json" };
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { "oauth2" };
GenericType<CreateOrderResponse> localVarReturnType = new GenericType<CreateOrderResponse>() {
};
CompleteResponse<CreateOrderResponse> completeResponse = (CompleteResponse<CreateOrderResponse>) apiClient
.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams,
localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames,
localVarReturnType);
return completeResponse.getData();
}
Thanks
The orders endpoint is only for creating itemized orders for e-commerce transactions. You won't see them anywhere until you charge them, and then you'll see the itemizations for the order in your dashboard with the transaction.
I am working on a JHipster project with an AngularJS front-end and a Java back-end. I am using Spring data with the MongoDb database.
I did a grouping operation on the field budgetCode. So, for each budgetCode, I succeded to have the list of all the linked taskCodes.
Here, the method aggregateAllTaskCodes which does the grouping operation:
Repository layer
public class ClarityResourceAffectationRepositoryImpl implements ClarityResourceAffectationRepositoryCustom {
#Override
public List<ClarityResourceAffectationReport> aggregateAllTaskCodes() {
Aggregation aggregation = newAggregation(
group("budgetCode").addToSet("budgetCode").as("budgetCode").addToSet("taskCode").as("taskCode"),
sort(Sort.Direction.ASC, previousOperation(),"budgetCode"));
AggregationResults groupResults = mongoTemplate.aggregate(aggregation, ClarityResourceAffectation.class,
ClarityResourceAffectationReport.class);
List<ClarityResourceAffectationReport> clarityResourceAffectationReports = groupResults.getMappedResults();
return clarityResourceAffectationReports;
}
}
Service layer
public class ClarityResourceAffectationServiceImpl implements ClarityResourceAffectationService{
#Override
public List<ClarityResourceAffectationReport> aggregateAllTaskCodes() {
log.debug("Request to aggregateByCodeBudgetForCodeTache : {}");
List<ClarityResourceAffectationReport> result = clarityResourceAffectationRepository
.aggregateAllTaskCodes();
return result;
}
}
REST API layer
public class ClarityResourceAffectationResource {
#GetMapping("/clarity-resource-affectations/list-task-codes")
#Timed
public ResponseEntity<List<ClarityResourceAffectationReport>> aggregateTabAllTaskCodes() {
log.debug("REST request to get aggregateTabAllTaskCodes : {}");
List<ClarityResourceAffectationReport> result = clarityResourceAffectationService.aggregateAllTaskCodes();
return new ResponseEntity<>(result, HttpStatus.OK);
}
}
ClarityResourceAffectation
#Document(collection = "clarity_resource_affectation")
public class ClarityResourceAffectation implements Serializable {
#Id
private String id;
#Field("budget_code")
private String budgetCode;
#Field("task_code")
private String taskCode;
public String getBudgetCode() {
return budgetCode;
}
public void setBudgetCode(String budgetCode) {
this.budgetCode = budgetCode;
}
public String getTaskCode() {
return taskCode;
}
public void setTaskCode(String taskCode) {
this.taskCode = taskCode;
}
}
ClarityResourceAffectationReport
public class ClarityResourceAffectationReport implements Serializable {
private static final long serialVersionUID = 1L;
private String budgetCode;
private String taskCode;
private String listTaskCode;
public String getBudgetCode() {
return budgetCode;
}
public void setBudgetCode(String budgetCode) {
this.budgetCode = budgetCode;
}
public String getTaskCode() {
return taskCode;
}
public void setTaskCode(String taskCode) {
this.taskCode = taskCode;
}
public String[] getListTaskCode() {
return listTaskCode;
}
public void setListTaskCode(String[] listTaskCode) {
this.listTaskCode = listTaskCode;
}
}
clarity-resource-affectation.service.js
(function() {
'use strict';
angular
.module('dashboardApp')
.factory('ClarityResourceAffectation', ClarityResourceAffectation);
ClarityResourceAffectation.$inject = ['$resource'];
function ClarityResourceAffectation ($resource) {
var resourceUrl = 'clarity/' + 'api/clarity-resource-affectations/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'aggregateAllTaskCodes': {
method: 'GET',
isArray: true,
url: 'clarity/api/clarity-resource-affectations/list-task-codes'
}
});
}
})();
When I call the function in the AngularJS front-end and I display that on a table, for each budgetCode, I have the list of the taskCodes in an array of one element. For example, for the budgetCode [ "P231P00"] I can have this list of taskCodes: [ "61985" , "43606" , "60671" , "43602"]
Well, I would like to have the list of the linked taskCodes, not in an array of one element but in an array of several elements like that:
[ ["61985"] , ["43606"] , ["60671"] , ["43602"] ]
What do I have to change in my code in order to do that?
Just for information, my javascript code which create the array based on the aggregate function:
clarity-resource-affectation-list-task-codes.controller.js
(function() {
'use strict';
angular
.module('dashboardApp')
.controller('ClarityResourceAffectationTableauBordNbCollaborateursController', ClarityResourceAffectationTableauBordNbCollaborateursController);
ClarityResourceAffectationTableauBordNbCollaborateursController.$inject = ['$timeout', '$scope', '$stateParams', 'DataUtils', 'ClarityResourceAffectation'];
function ClarityResourceAffectationTableauBordNbCollaborateursController ($timeout, $scope, $stateParams, DataUtils, ClarityResourceAffectation) {
var vm = this;
//Call of the function
allTaskCodes()
function allTaskCodes()
{
ClarityResourceAffectation.aggregateAllTaskCodes(function(readings) {
var dataAllTaskCodes;
dataAllTaskCodes = [];
alert(readings);
readings.forEach(function (item) {
dataAllTaskCodes.push({
label: item.budgetCode,
value: item.taskCode,
listvalue: item.listTaskCode
});
});
vm.dataAllTaskCodes = dataAllTaskCodes;
});
}
}
})();
Temporary solution:
Actually, I found a temporary solution by completing the method I created in the Service Layer:
#Override
public List<ClarityResourceAffectationReport> aggregateAllTaskCodes() {
log.debug("Request to aggregateAllTaskCodes : {}");
List<ClarityResourceAffectationReport> result = clarityResourceAffectationRepository
.aggregateAllTaskCodes();
Iterator<ClarityResourceAffectationReport> iterator = result.iterator();
while (iterator.hasNext())
{
ClarityResourceAffectationReport resAffectationReport = iterator.next();
String taskCodes = resAffectationReport.getTaskCode();
//Delete all exept letters, numbers and comma
taskCodes = taskCodes.replaceAll("[^a-zA-Z0-9,]","");
String[] listTaskCodes = taskCodes.split(",");
resAffectationReport.setListTaskCodes(listTaskCodes);
}
return result;
}
Also, I added an additional field to ClarityResourceAffectationReport which is listTaskCode. I updated the report class above. Finally, when I do an alert:
alert(readings[1].listvalue[0]), I have a result like 2630. So, I succeeded to have the first taskCode of a particular budgetCode.
I understood that what is important here is not the fact that as I told above for a budgetCode like [ "P231P00"], I must have a list like: [ "61985" , "43606" , "60671" , "43602"] or [ ["61985"] , ["43606"] , ["60671"] , ["43602"] ]. I just must have an array, not a string.
When I display alert(readings[1].listvalue), I have["2630","61297","61296","61299"] which is clearly an array because I can access each of the elements by calling alert(readings[1].listvalue[0]), alert(readings[1].listvalue[1]], etc...
I tried what you advised me
But, it is still not working. Here, my repository code:
#Override
public List<ClarityResourceAffectationReport> aggregateAllTaskCode() {
AggregationOperation project = new AggregationOperation() {
#Override
public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) {
return new BasicDBObject("$project", new BasicDBObject("budgetCode", "$budget_code").append("taskCode", Arrays.asList("$task_code")));
}
};
Aggregation aggregation = newAggregation(project,
group("budgetCode").addToSet("budgetCode").as("budgetCode").addToSet("taskCode").as("taskCode"),
sort(Sort.Direction.ASC, previousOperation(),"budgetCode"));
AggregationResults groupResults = mongoTemplate.aggregate(aggregation, ClarityResourceAffectation.class,
ClarityResourceAffectationReport.class);
List<ClarityResourceAffectationReport> clarityResourceAffectationReports = groupResults.getMappedResults();
log.debug("clarityResourceAffectationReports.size() => " + clarityResourceAffectationReports.size());
log.debug("aggregation.toString() => " + aggregation.toString());
return clarityResourceAffectationReports;
}
Here, you can find the logs:
clarityResourceAffectationReports.size() => 1
aggregation.toString() => {"aggregate" : "__collection__" , "pipeline" : [ { "$project" : { "budgetCode" : "$budget_code" , "taskCode" : [ "$task_code"]}} , { "$group" : { "_id" : "$budgetCode" , "budgetCode" : { "$addToSet" : "$budgetCode"} , "taskCode" : { "$addToSet" : "$taskCode"}}} , { "$sort" : { "_id" : 1 , "budgetCode" : 1}}]}
Thanks in advance
You need to use $project to change the taskCodes value into array of single value before $group.
I don't see any hook in the api to address this.
You can use AggregationOperation to create $project stage using mongodb (BasicDBObject) types.
AggregationOperation project = new AggregationOperation() {
#Override
public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) {
return new BasicDBObject("$project", new BasicDBObject("budgetCode", 1).append("taskCode", Arrays.asList("$taskCode")));
}
};
Something like
Aggregation aggregation = newAggregation(project,
group("budgetCode").addToSet("budgetCode").as("budgetCode").addToSet("taskCode").as("taskCode"),
sort(Sort.Direction.ASC, previousOperation(), "budgetCode"));
Using lambda
Aggregation aggregation = newAggregation(
aggregationOperationContext -> new BasicDBObject("$project", new BasicDBObject("budgetCode", 1).append("taskCode", Arrays.asList("$taskCode"))),
group("budgetCode").addToSet("budgetCode").as("budgetCode").addToSet("taskCode").as("taskCode"),
sort(Sort.Direction.ASC, previousOperation(), "budgetCode"));
Hey guys am new to this and I would appreciate any help.
I want to call getListTenant() from my save function below and clear the list using iterator before doing my save. Below is the code in my controller:
package controllers;
public class TenantController extends AppController {
Tenant tenant;
FacilityUnit unit;
// list tenants in selected facility
public Result listTenant() {
return ok(Json.toJson(getTenantList()));
}
private List<Tenant> getTenantList() {
List<Tenant> tenants = Tenant.find
.fetch("unit.facility")
.where().eq("unit.facility", currentFacility())
.findList();
return tenants;
}
public Result saveTenant() {
JsonNode submissionNode = request().body().asJson();
JsonNode itemsArray = submissionNode.get("items");
//clear tenant
// create the new tenant
if (itemsArray.isArray()) {
for (JsonNode itemNode : itemsArray) {
JsonNode tenantNode = itemNode.get("tenant");
String tenantId = tenantNode.get("id").asText();
JsonNode unitNode = itemNode.get("unit");
String unitId = unitNode.get("id").asText();
System.out.println("##### Tenant ID IS " + tenantId);
System.out.println("##### unit ID IS " + unitId);
// Tenant.find.where().eq("tenant.id",
// tenant.getTenant().getId()).eq("unit.id", unit.getId()
// ).delete();
// Util.isNotEmpty() &&
if (Util.isNotEmpty(tenantId) && Util.isNotEmpty(unitId)) {
// these two are the minimal criteria for an tenant
Tenant tenant = new Tenant();
tenant.setTenant(Person.find.byId(tenantId));
tenant.setUnit(FacilityUnit.find.byId(unitId));
tenant.save();
System.out.println("##### SAVED A TENANT");
}
}
}
System.out.println("##### DONE");
return ok(infoMessage("Update of " + tenant.getTenant() + "successful"));
}
Iterate over the Tenants from getTenantList() and call delete() on them to clear them.
For example:
private List<Tenant> getTenantList() {
List<Tenant> tenants = Tenant.find
.fetch("unit.facility")
.where().eq("unit.facility", currentFacility())
.findList();
return tenants;
}
public Result saveTenant() {
// Do something...
// ...
// Get the tenants list that we want to clear before saving.
// Best way to do this is loop over it and call delete.
for (Tenant tenant : getTenantList()) {
tenant.delete();
}
// Do some more things...
// ...
}