Drools : Getting the catched word in a list in THEN - drools

Below is my pojo class
-----------------------------------pojo_Classes2.RootDoc.java-----------------------------------
package pojo_Classes2;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"content",
"person"
})
public class RootDoc {
#JsonProperty("content")
private String content;
#JsonProperty("person")
private List<String> person = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("content")
public String getContent() {
return content;
}
#JsonProperty("content")
public void setContent(String content) {
this.content = content;
}
#JsonProperty("person")
public List<String> getPerson() {
return person;
}
#JsonProperty("person")
public void setPerson(List<String> person) {
this.person = person;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Here is the type of rule which i want to apply
$list1=[gaurav,gagan,anshu....]
...................................................................................................................
Rule1
If
content contains any of the above $list1
Then
Retrieve which name was captured in content and set person the person name in then
............................................................................................................
For eg. gaurav and gagan were captured in content then set get that gaurav and gagan were matched in content and get them back in then part.
Is it possible in drools

Yes, but create object of your class like:
when
$rd : Rootdoc(****your query****);
then
rd.setPerson(query);
end

Related

Post get data from request body, and return json Jakarta.ws.rs

I am tasked with creating a simple web api using JAVA EE and I cant use other external frameworks such as Spring Boot.
I got the get requests to work that was simple, however when I try to return a JSON to the api all I see is {} in postman or browser even though I created a user.
here is my current code
package ab.service;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
#Path("/MyRestService")
#ApplicationPath("resources")
public class RestService extends Application {
// http://localhosts:8080/BankTaskV1/ressources/MyRestService/sayHello
#GET
#Path("/sayHello")
public String getHelloMsg() {
return "Hello World";
}
#GET
#Path("/echo")
public Response getEchoMsg(#QueryParam("message") String msg) {
return Response.ok("you message was: " + msg).build();
}
#GET
#Path("/User")
public Response getUser() {
// Gson gson = new Gson();
User user = new User(1, "Ahmad");
return Response.status(Response.Status.OK).entity(user).type(MediaType.APPLICATION_JSON).build();
// return gson.toJson(user);
}
#POST
#Path("/CreateUser")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void createUser(UserRequest requestBody) {
System.out.println("create ran");
System.out.println(requestBody.UserName);
}
}
as you can see in the User endpoint I used GSON to convert user object to a json string and that worked, however I read online that it should work without it if I did it by returning an entity, something called POJO?
but that just gives me an empty {}
furthermore in the endpoint CreateUser I set it to consume json and gave it a request body with class that i defined. but when I try to print the username it gives me null, andd the create ran system output shows that the function ran.
here is my User class
package ab.service;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class User {
private int id;
private String name;
public User() {
}
public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
int getId() {
return id;
}
void setId(int id) {
this.id = id;
}
}
and my userrequest class
package ab.service;
import javax.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlElement;
#XmlRootElement
public class UserRequest {
#XmlElement
String UserName;
#XmlElement
int Id;
}

Supporting Multiple data sources of Mongo using Spring data

I am trying to configure two different mongo data sources using spring data.According to my requirement I need to change my scanning of base package dynamically at run time. The user can select the data source for a particular entity via property file by providing datasource and entity mapping.
Eg: entity1:dataSource1, entity2:dataSource2. Depending on this mapping I need to package names and need to replace in the #EnableMongoRepositories(basePackages="xxx.xxx.xxxx") at run time. I tired a lot using both Xml configuration and java configuration.But I could not find a possible way.Could some one please provide a solution for the problem if it is there.I am pasting the Entity classes ,Repositories and Configuration both XML and Java Config
package com.account.entity;
import java.io.Serializable;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "SampleAccount")
public class Account {
#Id
private String acntName;
#Indexed
private Date startDate;
#Indexed
private String accntType;
private Long acntId;
private Byte byteField;
public String getAcntName() {
return this.acntName;
}
public void setAcntName(String acntName) {
this.acntName = acntName;
}
public Date getStartDate() {
return this.startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public String getAccntType() {
return this.accntType;
}
public void setAccntType(String accntType) {
this.accntType = accntType;
}
public Long getAcntId() {
return this.acntId;
}
public void setAcntId(Long acntId) {
this.acntId = acntId;
}
public Byte getByteField() {
return this.byteField;
}
public void setByteField(Byte byteField) {
this.byteField = byteField;
}
}
public interface AccountRepository extends MongoRepository<Account, String>{
public Page<Account> findByAcntNameOrStartDate(String acntName, Date startDate, Pageable pageable);
public Page<Account> findByAccntTypeOrStartDate(String accntType, Date startDate, Pageable pageable);
public Account findByAcntName(String acntName);
public Page<Account> findByAcntNameIn(List<String> pkIdList, Pageable pageable);
}
package com.user.entity;
import java.io.Serializable;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "SampleUser")
public class User {
#Id
private String acntName;
#Indexed
private Date startDate;
#Indexed
private String accntType;
private Long acntId;
private Byte byteField;
public String getAcntName() {
return this.acntName;
}
public void setAcntName(String acntName) {
this.acntName = acntName;
}
public Date getStartDate() {
return this.startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public String getAccntType() {
return this.accntType;
}
public void setAccntType(String accntType) {
this.accntType = accntType;
}
public Long getAcntId() {
return this.acntId;
}
public void setAcntId(Long acntId) {
this.acntId = acntId;
}
public Byte getByteField() {
return this.byteField;
}
public void setByteField(Byte byteField) {
this.byteField = byteField;
}
}
package com.user.repo;
import java.util.Date;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import com.account.entity.Account;
import com.user.entity.User;
public interface UserRepository extends MongoRepository<User, String>{
public Page<Account> findByAcntNameOrStartDate(String acntName, Date startDate, Pageable pageable);
public Page<Account> findByAccntTypeOrStartDate(String accntType, Date startDate, Pageable pageable);
public Account findByAcntName(String acntName);
public Page<Account> findByAcntNameIn(List<String> pkIdList, Pageable pageable);
}
JavaConfig Files:
MongoConfig.class
package com.Config;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.CustomConversions;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
#Configuration
#EnableMongoRepositories(basePackages = {"xxx.xxx.xxx"},mongoTemplateRef="primaryTemplate")
public class MongoConfig {
#Resource
Environment environment;
public #Bean(name = "primarydb")
MongoDbFactory mongoDbFactory() throws Exception {
MongoCredential credential = MongoCredential.createCredential(
(environment.getProperty("xxx.datastore.mongo.server.userName")),
environment.getProperty("xxx.datastore.mongo.server.database"),
environment.getProperty("xxx.datastore.mongo.server.password").toCharArray());
List<MongoCredential> mongoCredentials = new ArrayList<>();
mongoCredentials.add(credential);
MongoClientOptions options = MongoClientOptions.builder()
.connectionsPerHost(
Integer.parseInt(environment.getProperty("xxx.datastore.mongo.server.connectionsPerHost")))
.build();
List<ServerAddress> serverAddress = new ArrayList<>();
prepareServerAddress(serverAddress);
MongoClient mongoClient = new MongoClient(serverAddress, mongoCredentials, options);
return new SimpleMongoDbFactory(mongoClient,
environment.getProperty("xxx.datastore.mongo.server.database"));
}
private void prepareServerAddress(List<ServerAddress> serverAddress) throws UnknownHostException {
String serverAddressList[] = environment.getProperty("XDM.datastore.mongo.server.address")
.split("\\s*,\\s*");
for (String svrAddress : serverAddressList) {
String address[] = svrAddress.split("\\s*:\\s*");
String host = Objects.nonNull(address[0]) ? address[0] : "127.0.0.1";
Integer port = Objects.nonNull(address[1]) ? Integer.valueOf(address[1]) : 27017;
serverAddress.add(new ServerAddress(host, port));
}
}
#Primary
public #Bean(name = "primaryTemplate")
MongoTemplate mongoTemplate(#Qualifier(value = "primarydb") MongoDbFactory factory) throws Exception {
MongoTemplate mongoTemplate = new MongoTemplate(factory);
return mongoTemplate;
}
}

How to iterate over a list of String and change it in RHS in drools

My use case i want to iterate over a List of String and Change the entries that match with the condition in LHS
Here is the json
{
"name":[
"james",
"harry",
"potter",
"james"
]
}
And Here is my drl
when
$names:Names($nameslist:name)
$value:String() from $nameslist
Boolean(booleanValue == true) from $value == "james"
then
System.out.println("Pojo Welcome-------");
end
My requirement is i want to change list such that
where name is james i want to chnage it into Peter.
How should i do it?
Here is my pojo class
package pojo_Classes;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"name"
})
public class Assignment1News {
#JsonProperty("name")
private List<String> name = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("name")
public List<String> getName() {
return name;
}
#JsonProperty("name")
public void setName(List<String> name) {
this.name = name;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
My requirement is i want to change list such that
where name is james i want to chnage it into Peter.
How should i do it?
There is no point in avoiding a simple function (or static method) that does the simple work of updating the list.
rule "james to peter"
when
$names:Names($nlist:name contains "james")
then
modify( $names ){ setName( replace( $nlist, "james", "peter" ) ); }
end

How to set a global custom Jackson deserializer in Camel w/o spring using REST

I would like to set a global custom date/Time deserializer on a camel route that is configured with rest.
What I already found is Camel + Jackson : Register a module for all deserialization
But I do not have the unmarshal() method in the route, but use the
RestDefinition rest(String path)
method from
org.apache.camel.builder.RouteBuilder.
We do not use Spring, but plain Camel with Scala and REST all configuration done programmatically (no xml).
My current solution is to use
#JsonDeserialize(using = classOf[MyDeserializer])
annotation on every date/time field, but that is not a satisfying solution.
Does anybody have a clue how to configure Camel to use the custom deserializer everywhere?
By default camel use DATES_AS_TIMESTAMPS feature. to disable this featuer just add .dataFormatProperty("json.out.disableFeatures", "WRITE_DATES_AS_TIMESTAMPS")
Also you can add custom serializer:
module.addSerializer(Date.class, sample.new DateSerializer());
and binding with name json-jackson
jndiContext.bind("json-jackson", jackson);
example:
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jackson.JacksonDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.rest.RestBindingMode;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.util.jndi.JndiContext;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class Samlpe3 {
public static void main(String[] args) throws Exception {
Samlpe3 sample = new Samlpe3();
//custom mapper
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule("DefaultModule", new Version(0, 0, 1, null, null, null));
module.addSerializer(Date.class, sample.new DateSerializer());
module.addSerializer(Person.class, sample.new PersonSerializer());
objectMapper.registerModule(module);
JacksonDataFormat jackson = new JacksonDataFormat(objectMapper, null);
JndiContext jndiContext = new JndiContext();
jndiContext.bind("json-jackson", jackson);
CamelContext context = new DefaultCamelContext(jndiContext);
context.addRoutes(new RouteBuilder() {
public void configure() throws Exception {
restConfiguration().component("jetty").bindingMode(RestBindingMode.json)
.host("0.0.0.0").contextPath("/test").port(8080)
//disableFeatures WRITE_DATES_AS_TIMESTAMPS
.dataFormatProperty("json.out.disableFeatures", "WRITE_DATES_AS_TIMESTAMPS")
;
rest("/v1/").produces("application/json")
.get("persons")
.to("direct:getPersons");
from("direct:getPersons")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody(new Person("Sergey", new GregorianCalendar().getTime()));
}
})
;
}
});
context.start();
Thread.sleep(60000);
context.stop();
}
public class DateSerializer extends JsonSerializer<Date> {
#Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(value);
gen.writeString(date);
}
}
public class PersonSerializer extends JsonSerializer<Person> {
#Override
public void serialize(Person value, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException {
gen.writeStartObject();
gen.writeFieldName("Changed_n");
gen.writeObject(value.getName() + " Changed");
gen.writeFieldName("Changed_b");
gen.writeObject(value.getBirthday());
gen.writeEndObject();
}
}
}
Person.java:
import java.util.Date;
public class Person {
private String name;
private Date birthday;
Person(String name, Date birhday){
System.out.println("Person");
this.setBirthday(birhday);
this.setName(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}

Error in annoting camel swagger Rest Service

I have created a rest Service using Apache Camel Swagger component. The rest service works fine but the request and response schema is not what i intended of.
The schema that i am trying to create is :
{
"GetStudentData": [
{
"RollNumber": "1",
"Name": "ABC",
"ClassName": "VII",
"Grade": "A"
}]
}
For this i have created a model as:
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "GetStudentData")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name="", propOrder={"studentInfo"})
public class StudentInfoWrapper {
#XmlElement(required=true)
private List<Student> studentInfo;
private double visiteddate;
public double getVisiteddate() {
return visiteddate;
}
public void setVisiteddate(double visiteddate) {
this.visiteddate = visiteddate;
}
public List<Student> getStudentInfo() {
return studentInfo;
}
public void setStudentInfo(List<Student> studentInfo) {
studentInfo = studentInfo;
}
}
And my student class is:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name="", propOrder={"RollNumber", "Name", "ClassName", "Grade"})
public class Student {
private String RollNumber;
private String Name;
private String ClassName;
private String Grade;
public String getRollNumber() {
return RollNumber;
}
public void setRollNumber(String rollNumber) {
RollNumber = rollNumber;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getClassName() {
return ClassName;
}
public void setClassName(String className) {
ClassName = className;
}
public String getGrade() {
return Grade;
}
public void setGrade(String grade) {
Grade = grade;
}
}
So when i load the above service into the swaggerUI it doesn't show the schema that i want.
How can i i get the desired schema. Looking forward to your answers.
Thanks in advance.