how to split java spring to use repository - java

I have Request by status = PENDING_PAYMENT,DONE, I want to split by comma with java spring to search
data by find to repository.
how can I resolved this?
#Override
public Map<String, Object> getAllOrderDetails(String status, String productName, String page, String limit) {
Map<String, Object> result = new HashMap<>();
String[] statusSplit = status.split(",");
OrderStatus os = OrderStatus.valueOf(status.toUpperCase());
List<Order> orders = orderRepo.findByStatus(os);
if(orders == null){
throw new NonexistentEntityException(ErrCode.ERR_UNKNOWN, "Order not listed");
}
List<OrderResult> order = new ArrayList<>();
// order = serviceDataList.getOrderDetails(o);
result.put("order", order);
return result;
}

Related

MongoDB Morphia distinct

public Collection<OwnerDetail> getAllOwners() {
final MorphiaCursor<Listing> listings = datastore.find(Listing.class)
.iterator(new FindOptions()
.projection().include("ownerDetail"));
Map<String, OwnerDetail> map = new HashMap<>();
while (listings.hasNext()) {
final Listing next = listings.next();
if (next.getOwnerDetail() != null) {
map.put(next.getOwnerDetail().getEmail(), next.getOwnerDetail());
}
}
return map.values();
}
I want to remove java code that distinct values by email and handle it by mongodb morphia. How can I do that?

Ljava.lang.Object; cannot be cast to .model.ISOVER at java.util.ArrayList.forEach

Am trying to get data from 3 tables and every time I end up getting an error
Ljava.lang.Object; cannot be cast to .model.ISECO at
java.util.ArrayList.forEach
This are my entities
#Entity
public class IS01 {
private String IEA;
private String INUM;
private String ILINE;
private String I0103;
#Entity
public class ISOVER {
private String IEA;
private String ILINE;
private String INUM;
private String IRESULT;
private String ICON;
private String IBCON;
private String CASE;
private String RPTID
#Entity
public class POSTCO {
private String CEA;
private String CNUM;
private String CLINE;
private String PSCONTACT;
And this is my Repository
public interface LineSummary extends CrudRepository<ISOVER , String> {
#Query("select c.ILINE , c.IRESULT,e.PSCONTACT, \n" +
"c.ICON,c.IBCON, c.RPTID, c.CASE, d.i0103 as age\n" +
"FROM ISOVER c \n" +
"inner join IS01 d \n" +
"on c.IEA = d.IEA and c.INUM = d.INUM and c.ILINE = d.ILINE\n" +
"inner join POSTCO e on d.IEA = e.CEA and d.INUM = e.CNUM and d.ILINE = e.CLINE\n" +
"where c.CASE like %?1%")
Iterable<ISOVER> findEntriesByUserId(#Param("Case") String Case);
And this is my service
public ResponseEntity<Map<String, Object>> retrieveLineListingSQL(String Case){
Iterable <ISOVER > stud = lineSummary.findEntriesByUserId(Case);
Map<String, Object> parents = new HashMap<>();
parents.put("totalMembers", 9);
parents.put("questionaryinfo", new ArrayList<HashMap<String,Object>>());
ArrayList<HashMap<String,Object>> listings = (ArrayList<HashMap<String,Object>>) parents.get("questionaryinfo");
if (stud != null) {
stud.forEach(d -> {
HashMap<String,Object> entry = new HashMap<>();
entry.put("adultquestionary","Yes");
entry.put("caseNumber", d.getCASE());
listings.add(entry);
});
}
parents.put("DMStatus", "No review");
parents.put("ages", new HashMap<String, Object>());
return ResponseEntity.ok().body(parents);
}
How can I return the results from the query and map them accordingly?
I believe this is your culprit:
if (stud != null) {
stud.forEach(d -> {
HashMap<String, Object> entry = new HashMap<>(); // < -- here
entry.put("adultquestionary","Yes");
entry.put("caseNumber", d.getCASE());
listings.add(entry);
});
}
Have your tried using *.model.ISECO instead of java.lang.Object? Does that work, any particular limitation?
Additionally, you could refactor you code to something way more simple, if you follow the same explanation provided in here: How to make nested JSON response with Array from a Stored procedure
Create a response model that outputs the format you expect as response.
There is no need for you to do all that collections handling one-by-one. The representation of an object in JSON is a MAP, basically let the
Jackson JSON library do all that work for you.

Retrofit — Multiple query parameters of same name where name is set dynamically

I'm trying to migrate an old project to Retrofit library and this project has quite tricky API. So I have a query template like this:
#GET(value = "products/search")
Single<ProductSearchResponse> productSearch();
And I have to add some parameters here of following template:
filter[attributeId]=attributeValueId
For example:
products/search?filter[1]=10&filter[1]=11&filter[2]=20&filter[2]=21
That's how API works and I can't change it. I know that we can pass a list as a parameter, like this:
#Query("filter") List<Integer> attributeValueIds
But how can I also set parameter's name dynamically?
You can use an arrayList! Something like the code below.
#GET(value = "products/search")
Single<ProductSearchResponse> productSearch(
#Query("status") List<Integer> status
);
ArrayList<Integer> queryStatus = new ArrayList<>();
queryStatus.add(0);
queryStatus.add(1);
queryStatus.add(2);
productService.productSearch(queryStatus);
Your url will be like that -> {url}?status=0&status=1&status=2
Thanks to the link, posted by #ILLIA DEREVIANKO (https://github.com/square/retrofit/issues/1324), I've managed to solve the problem with this class:
public class ProxyRetrofitQueryMap extends HashMap<String, Object> {
public ProxyRetrofitQueryMap(Map<String, Object> m) {
super(m);
}
#Override
public Set<Entry<String, Object>> entrySet() {
Set<Entry<String, Object>> originSet = super.entrySet();
Set<Entry<String, Object>> newSet = new HashSet<>();
for (Entry<String, Object> entry : originSet) {
String entryKey = entry.getKey();
if (entryKey == null) {
throw new IllegalArgumentException("Query map contained null key.");
}
Object entryValue = entry.getValue();
if (entryValue == null) {
throw new IllegalArgumentException(
"Query map contained null value for key '" + entryKey + "'.");
}
else if(entryValue instanceof List) {
for(Object arrayValue:(List)entryValue) {
if (arrayValue != null) { // Skip null values
Entry<String, Object> newEntry = new AbstractMap.SimpleEntry<>(entryKey, arrayValue);
newSet.add(newEntry);
}
}
}
else {
Entry<String, Object> newEntry = new AbstractMap.SimpleEntry<>(entryKey, entryValue);
newSet.add(newEntry);
}
}
return newSet;
}
}
With this we can just use a map, where key is a unique parameter name and value is a List of Strings, that are values for this parameter. Something like this:
ProxyRetrofitQueryMap map = new ProxyRetrofitQueryMap();
List<String> values1 = new ArrayList<>();
values1.add("10");
values1.add("11");
map.put("filter[1]", values1);
List<String> values2 = new ArrayList<>();
values1.add("20");
values1.add("21");
map.put("filter[2]", values2);
You can use #QueryMap annotation like this:
public interface NewsService() {
#GET("/news")
Call<List<News>> getNews(
#QueryMap Map<String, String> options
);
}
Map<String, String> data = new HashMap<>();
data.put("author", "Marcus");
data.put("page", String.valueOf(2));
...
newsService.getNews(data);
More details: https://futurestud.io/tutorials/retrofit-2-add-multiple-query-parameter-with-querymap

How to see created order in square pos

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.

is this the right way for doing aggregation in elasticsearch using spring data template

I have a type in elasticsearch which has field called created (which is a date). I need to do a dateHistogram aggregation on this field. Is this the right way? Can someone provide me a better code snippet?
List<Result> results = new ArrayList<>();
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
RangeFilterBuilder rangeBuilderForDate = FilterBuilder.getRangeBuilderForDate(searchCriteria.getCreatedFrom(), searchCriteria.getCreatedTo(), Field.CREATED.getFieldName());
TermFilterBuilder statusTermFilter = FilterBuilder.getTermFilter("Active", Field.STATUS.getFieldName());
BoolFilterBuilder boolFilterBuilder = boolFilter();
BoolFilterBuilder should = boolFilterBuilder.must(rangeBuilderForDate, statusTermFilter);
DateHistogramBuilder dateAggs = AggregationBuilders.dateHistogram("created").interval(getInterval(searchCriteria)).field("created");
FiltersAggregationBuilder filterAggs = AggregationBuilders.filters("dateRange").filter(should).subAggregation(dateAggs);
NativeSearchQuery searchQuery = nativeSearchQueryBuilder.withIndices(index).withTypes(type).addAggregation(filterAggs).build();
Aggregations aggregations = template.query(searchQuery, new ResultsExtractor<Aggregations>() {
#Override
public Aggregations extract(SearchResponse response) {
return response.getAggregations();
}
});
Map<String, Aggregation> asMap = aggregations.getAsMap();
InternalFilters aggregation = (InternalFilters)asMap.get("dateRange");
Collection<Bucket> buckets = aggregation.getBuckets();
for(Filters.Bucket filterBuckets : buckets) {
Aggregations subAggs = filterBuckets.getAggregations();
InternalDateHistogram dateSubAggs = (InternalDateHistogram) subAggs.asMap().get("created");
for(Histogram.Bucket bucket : dateSubAggs.getBuckets()) {
Result result = new Result();
DateHistogram.Bucket dateBucket = (DateHistogram.Bucket) bucket;
result.setAggCriteria(dateBucket.getKey());
result.setCount(dateBucket.getDocCount());
results.add(result);
}
}
return results;

Categories