Filter users except SubscriptionAdmin in Java - java

I am trying to apply certain business rules for all users, except Subscription Administrators in Java. When i set the filter as below,
user.setQueryFilter(new QueryFilter("SubscriptionAdmin", "=", "false"));
I get an error like this
Could not parse: Attribute "SubscriptionAdmin" on type User is not allowed in query expressions.
How do i achieve this? Any help is appreciated.

Per WS API documentation, SubscriptionAdmin field on a User object cannot be used in queries. You may iterate over users and use an if statement with a condition:
if (userQueryObject.get("SubscriptionAdmin").getAsBoolean() == false){
//your code here;
}
SubscriptionAdmin field must be included in the fetch. Here is a code fragment where the condition is evaluated:
QueryRequest userRequest = new QueryRequest("User");
userRequest.setFetch(new Fetch("UserName", "Subscription", "DisplayName", "SubscriptionAdmin"));
userRequest.setQueryFilter(new QueryFilter("UserName", "=", "someuser#co.com"));
QueryResponse userQueryResponse = restApi.query(userRequest);
JsonArray userQueryResults = userQueryResponse.getResults();
JsonElement userQueryElement = userQueryResults.get(0);
JsonObject userQueryObject = userQueryElement.getAsJsonObject();
String userRef = userQueryObject.get("_ref").getAsString();
System.out.println(userRef);
if (userQueryObject.get("SubscriptionAdmin").getAsBoolean() == false){
System.out.println(userQueryObject.get("SubscriptionAdmin"));
}

Related

Retrieve specific data from REST Json response based on condition

I looked at all related posts but I couldn't find what I am looking for.
Verified the query syntax by using https://codebeautify.org/jsonpath-tester and https://jsonpath.com/. In below code, I get correct response if I print just id. I am looking for title, based on specific userID and id.
Getting "Invalid JSON expression" as o/p. Can anyone pls help here!
public void restPost2(){
RestAssured.baseURI = "https://jsonplaceholder.typicode.com/posts";
RequestSpecification req = RestAssured.given().log().all();
String res1 = req.given().when().get().then().extract().asString();
JsonPath js = new JsonPath(res1);
System.out.println("list of Ids : " + js.get("id"));
System.out.println("specific title : " + js.get("(?(#.userId == '3') && (#.id == '23')).title"));
}
Following changes will solve your issue.
Use JsonPath.read to set json string to be queries
Syntax of jsonPath queries need to be corrected.
suggest you to refer jsonPath documentation again.
Please find a working example
json = <data fetched for the api>
Object x = JsonPath.read(json,"$..id");
Object y = JsonPath.read(json,"$[?(#.userId == 3 && #.id == 23)]");

AWS SSM parameter store not fetching all key/values

Could someone let me know why the below code only fetching few entries from the parameter store ?
GetParametersByPathRequest getParametersByPathRequest = new GetParametersByPathRequest();
getParametersByPathRequest.withPath("/").setRecursive(true);
getParametersByPathRequest.setWithDecryption(true);
GetParametersByPathResult result = client.getParametersByPath(getParametersByPathRequest);
result.getParameters().forEach(parameter -> {
System.out.println(parameter.getName() + " - > " + parameter.getValue());
});
GetParametersByPath is a paged operation. After each call you must retrieve NextToken from the result object, and if it's not null and not empty you must make another call with it added to the request.
Here's an example using DescribeParameters, which has the same behavior:
DescribeParametersRequest request = new DescribeParametersRequest();
DescribeParametersResult response;
do
{
response = client.describeParameters(request);
for (ParameterMetadata param : response.getParameters())
{
// do something with metadata
}
request.setNextToken(response.getNextToken());
}
while ((response.getNextToken() != null) && ! respose.getNextToken.isEmpty());
Here is the code, based on the code above, for the new 2.0 version of AWS SSM manager. Notice I have set the maxResults to 1 to prove out the loop. You will want to remove that. AWS has mentioned that in the new code they wanted to emphasize immutability.
Using this dependency:
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>ssm</artifactId>
<version>2.10.32</version>
</dependency>
I came up with this code:
private void refreshCache() {
StopWatch sw = StopWatch.createStarted();
GetParametersByPathRequest request = GetParametersByPathRequest.builder()
.path(prefix)
.withDecryption(useDecryption)
.maxResults(1)
.build();
GetParametersByPathResponse response;
do {
response = ssm.getParametersByPath(request);
for (Parameter p : response.parameters()) {
//do something with the values.
}
request = GetParametersByPathRequest.builder()
.path(prefix)
.withDecryption(useDecryption)
.nextToken(response.nextToken())
.maxResults(1)
.build();
}
while (StringUtils.isNotBlank(response.nextToken()));
LOG.trace("Refreshed parameters in {}ms", sw.getTime());
}
private void getSsmParams() {
AWSSimpleSystemsManagement client = AWSSimpleSystemsManagementClientBuilder.defaultClient();
GetParametersByPathRequest request = new GetParametersByPathRequest();
request.withRecursive(true);
request.withPath('/your/path/parameterName').setWithDecryption(true);
GetParametersByPathResult response;
do {
response = client.getParametersByPath(request);
for (Parameter p : response.parameters()) {
//do something with the values. maybe add to a list
}
request.setNextToken(response.getNextToken())
}
while (StringUtils.isNotBlank(response.getNextToken()));
}
Above piece of code worked for me .ssm only sends 10 parameters at a time, so if you want to fetch more than 10 parameters from ssm parameter store programatically you will have to use multiple calls to fetch them. here the token is important , if there are more values in the path (request.withPath('/your/path/parameterName')) you have given, it will send a token indicating that there are more values in the given path ,and you will have to make the following request with the token received from the previous request in order to get the rest of the values.

How to exclude some fields when listing Grails domain?

I'm wondering how can I list Grails domain and exclude some fields at same time. I'm guessing solution must be simple but I just can not see it.
I prepared some example with domain User:
class User implements Serializable {
String username
String email
Date lastUpdated
String password
Integer status
static constraints = { }
static mapping = { }
}
At this point I want to list all users which have status below 2.
render User.findAllByStatusLessThen(2) as JSON
I want to render JSON response to clientside without some fields. For example I just want to render users with fields username and lastUpdated so rendered JSON would look like this:
[{"username": "user1", "lastUpdated":"2016-09-21 06:49:46"}, {"username": "user2", "lastUpdated":"2016-09-22 11:24:42"}]
What's the easiest way to achieve that?
Yeah.It's simple.Try below solutions
Solution 1
List userList = User.where{ status < 2 }.property("username").property("lastUpdated").list()
render userList as JSON
output
[{"user1", "2016-09-21 06:49:46"}, {"user2", "2016-09-22 11:24:42"}]
Solution 2 - using this you will get output in the Key-Value pair
List userList = User.findAllByStatusLessThen(2)?.collect{
[username : it.username, lastUpdated: it.lastUpdated]}
render userList as JSON
output
[{"username": "user1", "lastUpdated":"2016-09-21 06:49:46"}, {"username": "user2", "lastUpdated":"2016-09-22 11:24:42"}]
You are looking for Grails projections.
def result = Person.createCriteria().list {
lt("status", 2)
projections {
property('username')
property('lastUpdated')
}
} as JSON
Well if you want the result to be in key-value pair you can take advantage of HQL query
def query = """select new map(u.username as username, u.lastUpdated as lastUpdated) from User u where status < 2"""
def result = User.executeQuery(query)
println (result as JSON)
This will give you the output as below
[{"username": "user1", "lastUpdated":"2016-09-21 06:49:46"}, {"username": "user2", "lastUpdated":"2016-09-22 11:24:42"}]

Flexible search with parameters return null value

I have to do this flexible search query in a service Java class:
select sum({oe:totalPrice})
from {Order as or join CustomerOrderStatus as os on {or:CustomerOrderStatus}={os:pk}
join OrderEntry as oe on {or.pk}={oe.order}}
where {or:versionID} is null and {or:orderType} in (8796093066999)
and {or:company} in (8796093710341)
and {or:pointOfSale} in (8796097413125)
and {oe:ecCode} in ('13','14')
and {or:yearSeason} in (8796093066981)
and {os:code} not in ('CANCELED', 'NOT_APPROVED')
When I perform this query in the hybris administration console I correctly obtain:
1164.00000000
In my Java service class I wrote this:
private BigDecimal findGroupedOrdersData(String total, String uncDisc, String orderPromo,
Map<String, Object> queryParameters) {
BigDecimal aggregatedValue = new BigDecimal(0);
final StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("select sum({oe:").append(total).append("})");
queryBuilder.append(
" from {Order as or join CustomerOrderStatus as os on {or:CustomerOrderStatus}={os:pk} join OrderEntry as oe on {or.pk}={oe.order}}");
queryBuilder.append(" where {or:versionID} is null");
if (queryParameters != null && !queryParameters.isEmpty()) {
appendWhereClausesToBuilder(queryBuilder, queryParameters);
}
queryBuilder.append(" and {os:code} not in ('");
queryBuilder.append(CustomerOrderStatus.CANCELED.getCode()).append("', ");
queryBuilder.append("'").append(CustomerOrderStatus.NOT_APPROVED.getCode()).append("')");
FlexibleSearchQuery query = new FlexibleSearchQuery(queryBuilder.toString(), queryParameters);
List<BigDecimal> result = Lists.newArrayList();
query.setResultClassList(Arrays.asList(BigDecimal.class));
result = getFlexibleSearchService().<BigDecimal> search(query).getResult();
if (!result.isEmpty() && result.get(0) != null) {
aggregatedValue = result.get(0);
}
return aggregatedValue;
}
private void appendWhereClausesToBuilder(StringBuilder builder, Map<String, Object> params) {
if ((params == null) || (params.isEmpty()))
return;
for (String paramName : params.keySet()) {
builder.append(" and ");
if (paramName.equalsIgnoreCase("exitCollection")) {
builder.append("{oe:ecCode}").append(" in (?").append(paramName).append(")");
} else {
builder.append("{or:").append(paramName).append("}").append(" in (?").append(paramName).append(")");
}
}
}
The query string before the search(query).getResult() function is:
query: [select sum({oe:totalPrice}) from {Order as or join CustomerOrderStatus as os on {or:CustomerOrderStatus}={os:pk}
join OrderEntry as oe on {or.pk}={oe.order}} where {or:versionID} is null
and {or:orderType} in (?orderType) and {or:company} in (?company)
and {or:pointOfSale} in (?pointOfSale) and {oe:ecCode} in (?exitCollection)
and {or:yearSeason} in (?yearSeason) and {os:code} not in ('CANCELED', 'NOT_APPROVED')],
query parameters: [{orderType=OrderTypeModel (8796093230839),
pointOfSale=B2BUnitModel (8796097413125), company=CompanyModel (8796093710341),
exitCollection=[13, 14], yearSeason=YearSeasonModel (8796093066981)}]
but after the search(query) result is [null].
Why? Where I wrong in the Java code? Thanks.
In addition, if you want to disable restriction in your java code. You can do like this ..
#Autowired
private SearchRestrictionService searchRestrictionService;
private BigDecimal findGroupedOrdersData(String total, String uncDisc, String orderPromo,
Map<String, Object> queryParameters) {
searchRestrictionService.disableSearchRestrictions();
// You code here
searchRestrictionService.enableSearchRestrictions();
return aggregatedValue;
}
In the above code, You can disabled the search restriction and after the search result, you can again enable it.
OR
You can use sessionService to execute flexible search query in Local View. The method executeInLocalView can be used to execute code within an isolated session.
(SearchResult<? extends ItemModel>) sessionService.executeInLocalView(new SessionExecutionBody()
{
#Override
public Object execute()
{
sessionService.setAttribute(FlexibleSearch.DISABLE_RESTRICTIONS, Boolean.TRUE);
return flexibleSearchService.search(query);
}
});
Here you are setting DISABLE RESTRICTIONS = true which will run the query in admin context [Without Restriction].
Check this
Better i would suggest you to check what restriction exactly applying to your item type. You can simply check in Backoffice/HMC
Backoffice :
Go to System-> Personalization (SearchRestricion)
Search by Restricted Type
Check Filter Query and analysis your item data based on that.
You can also check its Principal (UserGroup) on which restriction applied.
To confirm, just check by disabling active flag.
Query in the code is running not under admin user (most likely).
And in this case the different search Restrictions are applied to the query.
You can see that the original query is changed:
start DB logging (/hac -> Monitoring -> Database -> JDBC logging);
run the query from the code;
stop DB logging and check log file.
More information: https://wiki.hybris.com/display/release5/Restrictions
In /hac console the admin user is usually used and restrictions will not be applied because of this.
As the statement looks ok to me i'm going to go with visibility of the data. Are you able to see all the items as whatever user you are running the query as? In the hac you would be admin obviously.

Can We Pass Multiple Parameters to RestCypherQueryEngine.query?

I want to implement a log in portal using java, neo4j REST API and Spring Framework. I am using the RestCypherQueryEngine class to send a cypher query to the server.
The query looks like -->
String query = "MATCH n WHERE n.Email = {email} AND n.Password = {pass} RETURN n;"
final QueryResult<Map<String,Object>> result = engine.query(query, Map.Util("Email", email), Map.Util("Password", pass);
.
"email" and "pass" are both Strings with the respective values.
I wanted to know if this is a valid query and can two parameters be passed like this ?
and how to know if a node has been returned or not or if the the login is authenticated. ?
Thank you.
You need to put all parameters into one map:
Map<String,Object> params = new HashMap<>();
params.put("email", email");
params.put("password", pass);
QueryResult<Map<String,Object>> result = engine.query(query,params);
NB: Query parameters are case sensitive.

Categories

Resources