Empty List in Drools rule - java

I ran into a problem in a rule called "Due date for test1". I pass the list called "tests" as a parameter to
check it for Test.Test1, but the list is empty, despite the fact that before that I filled it in the rule "test for type1". What is the problem?
here is code of entity "Machine":
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Machine {
private String type;
public ArrayList<Test> tests= new ArrayList<Test>();
private List<String> functions = new ArrayList<String>();
private Date creationTime =null;
private Date testTime = null;
public Machine (String type) {
this.type= type;
}
public void setType(String type) {
this.type= type;
}
public String getType() {
return type;
}
public void setTests(ArrayList<Test> tests) {
this.tests = tests;
}
public void setFunctions(List<String> functions) {
this.functions = functions;
}
public List<String> functions() {
return functions;
}
public List<Test> getTests() {
return tests;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public Date getCreationTime() {
return creationTime;
}
public void setTestTime(Date testTime) {
this.testTime = testTime;
}
public Date getTestTime() {
return testTime;
}
}
here is code of entity "Test":
package com.sample;
import java.util.Calendar;
public enum Test {
Test1(1),Test2(2),Test3(3);
private Integer id;
Test(Integer id) {
this.id=id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setTestsDueTime(Machine m,int numOfDays) {
setTest(m,Calendar.DAY_OF_YEAR,numOfDays);
}
public void setTest(Machine m,int calendarType,int numOfDays) {
Calendar c = Calendar.getInstance();
c.setTime(m.getCreationTime());
c.add(calendarType, numOfDays);
m.setTestTime(c.getTime());
}
}
here is drl code:
package com.sample
import com.sample.Machine;
import com.sample.Test;
rule "test for type1"
when
m : Machine(type == "type1");
then
Test t1=Test.Test1;
Test t2 = Test.Test2;
Test t3 = Test.Test3;
m.getTests().add(t1);
m.getTests().add(t2);
m.getTests().add(t3);
insert(m);
insert(m);
insert(m) ;
end
rule "Due date for test1"
when
m:Machine(type == "type1", tests contains Test.Test1);
then
System.out.print("условие прошло");
//t.setTestsDueTime( m,3);
end
main class code:
package com.sample;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
public class DroolsTest {
public static final void main(String[] args) {
try {
// load up the knowledge base
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");
// go !
Machine m = new Machine("type1");
kSession.insert(m);
kSession.fireAllRules();
} catch (Throwable t) {
t.printStackTrace();
}
}
}

insert(m);
insert(m);
insert(m);
This doesn't make any sense. m is already in Working Memory.
What you need is one
update(m);
instead.

Related

How we can compare two values of flux using springreactor

Currently I am new in reactive programming ,
I have added data in 2 documents, so currently what I am trying to do is to return only those data to client whose tokenIdentifier is same in both document.
Please refer the code below:
I have 2 collection that has
package com.mainApp;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(value = "Token")
public class TokenData {
#Id
private String id;
private String tokenIdentifier;
private Date todayDate;
public TokenData(String id, String tokenIdentifier, Date todayDate) {
super();
this.id = id;
this.tokenIdentifier = tokenIdentifier;
this.todayDate = todayDate;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTokenIdentifier() {
return tokenIdentifier;
}
public void setTokenIdentifier(String tokenIdentifier) {
this.tokenIdentifier = tokenIdentifier;
}
public Date getTodayDate() {
return todayDate;
}
public void setTodayDate(Date todayDate) {
this.todayDate = todayDate;
}
}
package com.mainApp;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(value = "TURCollection")
public class TURCollection {
#Id
private String id;
private String turIdentifier;
private String tokenIdentifier;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTurIdentifier() {
return turIdentifier;
}
public void setTurIdentifier(String turIdentifier) {
this.turIdentifier = turIdentifier;
}
public String getTokenIdentifier() {
return tokenIdentifier;
}
public void setTokenIdentifier(String tokenIdentifier) {
this.tokenIdentifier = tokenIdentifier;
}
}
I have a controller which will return only those tokenData whose tokenData.getTokenIdentifier() == TURCollection.getTokenIdentifier().
So
#GetMapping(value = "/getAllToken")
public Flux<TokenData> getToken(){
/*List<TokenData> returnData = new ArrayList<TokenData>();
List<TokenData> tokenData = tokenDataRepository.findAll().collectList().block();
List<TURCollection> turCollection = turRepository.findAll().collectList().block();
turCollection.forEach(tur -> {
for(TokenData data : tokenData) {
if(tur.getTokenIdentifier().equals(data.getTokenIdentifier())) {
returnData.add(data);
}
}
});*/
but the block() code is not working in reactive programming
Can anyone help how I can compare values of two flux in reactive way?
You can use a combination of Flux.collectList and Mono.flatMap.
Mono<List<TokenData>> tokenData = tokenDataRepository.findAll().collectList();
Mono<List<TURCollection>> turCollection = turRepository.findAll().collectList();
Mono<List<TokenData>> result = turCollection.flatMap(turs ->
Set<String> ids = turs.stream().map(TURCollection::getId).collect(toSet());
return tokenData.map(tokens ->
tokens.stream().filter(token -> ids.contains(token.getId())).collect(toList())
);
);

What to put in this method? JAVA basic

Can anyone help me out? I am trying to figure out what to put in this getLecture body where the question marks are:
import java.util.ArrayList;
public class Schedule
{
private ArrayList<Lecture> lectures;
public Schedule(ArrayList<Lecture> lectures)
{
lectures = new ArrayList<Lecture>();
}
public Lecture getLecture(long date, long time)
{
???
}
public ArrayList<Lecture> getLectures() {
return lectures;
}
public void addLecture(Lecture lecture)
{
lectures.add(lecture);
}
public void removeLecture(Lecture lecture)
{
for(int i = 0; i < lectures.size(); i++)
{
if(lectures.get(i) == lecture)
{
lectures.remove(i);
}
}
}
}
I am trying to compare the time, with the parameters given to that method, then to make a for loop going through a list, preferably a for each loop. Inside of the loop I need to take the time of the Lecture object created inside the method, and compare it to the time of the Lecture from the list. This is the lecture class:
package application;
import java.util.ArrayList;
public class Lecture {
private String message;
private long time;
private long date;
private ArrayList<Object> materials;
public Lecture() {
int date;
int time;
}
public String sendMessage(String message) {
return message;
}
public void uploadMaterial(Object material) {
materials.add(material);
}
public Object getMaterial(Object material) {
return material;
}
public void removeMaterial(Object material) {
for(int i = 0; i < materials.size(); i++)
{
if(material == materials.get(i))
materials.remove(i);
}
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
}

ebean model update not permanent

Good day! I'm having a problem when updating an entity. When I click the "update" button, the changes are saved. However, when I go a different page, the recently changed (or added) items are there but the old items (that should be changed or removed) are also there. Particularly the relatedTags (the name and notes are updating just fine). Why is it not persistent or permanent?
Here is where the updating happens.
Form<Tag> filledForm = tagForm.fill(Tag.find.byId(id)).bindFromRequest();
Tag editedTag = RelatedTag.findTag(id);
if(filledForm.hasErrors()) {
return badRequest(editTagForm.render(user, editedTag, filledForm, tags));
}
else {
List<RelatedTag> relatedTagsAlloc = new ArrayList<RelatedTag>();
java.util.Map<String, String[]> map = request().body().asFormUrlEncoded();
String[] relatedTags = map.get("relatedTags.tag.name");
String[] relationship = map.get("relatedTags.relationship");
String[] relatedNotes = map.get("relatedTags.relatedNotes");
if (relatedTags != null) {
for (int i = 0; i < relatedTags.length; i++) {
if (RelatedTag.exists(relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "))) {
relatedTagsAlloc.add(RelatedTag.findByLabel(
relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "), relationship[i], relatedNotes[i].trim()));
} else {
Tag unknown = new Tag(relatedTags[i], "");
Tag.create(unknown);
relatedTagsAlloc.add(RelatedTag.findByLabel(
relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "), relationship[i], relatedNotes[i].trim()));
}
}
editedTag.getRelatedTags().clear();
}
editedTag.setName(filledForm.get().getName().toLowerCase().replaceAll("\\s+", " "));
editedTag.setRelatedTags(relatedTagsAlloc);
editedTag.update();
Application.log(user, editedTag, action);
writeToFile(editedTag);
return ok(summary.render(user, editedTag));
}
And here are the models:
Tag model:
package models;
import java.sql.Timestamp;
import java.util.*;
import javax.persistence.*;
import javax.validation.*;
import play.data.Form;
import play.data.validation.Constraints.*;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import scala.Int;
#Entity
public class Tag extends Model{
#Id
private int id;
#Required
#MaxLength(value=100)
#Column(unique=true)
private String name;
#MaxLength(value=200)
private String notes;
#OneToMany(cascade=CascadeType.ALL)
public List<RelatedTag> relatedTags = new ArrayList<RelatedTag>();
#Version
public Timestamp lastUpdate;
public static Finder<Integer, Tag> find = new Finder(Int.class, Tag.class);
public Tag() {
}
public Tag(String name, String notes){
this.name = name;
this.notes = notes;
}
public Tag(int id, String name, String notes, List<RelatedTag> relatedTags) {
this.id = id;
this.name = name;
this.notes = notes;
this.relatedTags = relatedTags;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public List<RelatedTag> getRelatedTags() {
return relatedTags;
}
public void setRelatedTags(List<RelatedTag> relatedTags) {
this.relatedTags = relatedTags;
}
public static List<Tag> all() {
return find.all();
}
public static void create(Tag tag){
tag.save();
}
public static void delete(int id){
find.ref(id).delete();
}
public static void update(int id, Tag tag) {
tag.update(id); // updates this entity, by specifying the entity ID
}
public static boolean exists(Tag newTag) {
for(Tag allTags : Tag.find.all()) {
if(allTags.getName().equals(newTag.getName()))
return true;
}
return false;
}
}
RelatedTag model
package models;
import java.sql.Timestamp;
import java.util.*;
import javax.persistence.*;
import javax.validation.*;
import play.data.Form;
import play.data.validation.Constraints.*;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import scala.Int;
#Entity
public class RelatedTag extends Model {
#Id
public int rtID;
private int id; //same as Tag's id
private String relationship;
private String relatedNotes;
#Version
public Timestamp lastUpdate;
public RelatedTag() {}
public RelatedTag(int id, String relationship, String relatedNotes) {
this.id = id;
this.relationship = relationship;
this.relatedNotes = relatedNotes;
}
public void setId(int id){
this.id = id;
}
public void setRelationship(String relationship){
this.relationship = relationship;
}
public void setRelatedNotes(String relatedNotes) {
this.relatedNotes = relatedNotes;
}
public int getId(){
return id;
}
public String getRelationship(){
return relationship;
}
public String getRelatedNotes() {
return relatedNotes;
}
public static void create(List<RelatedTag> rt){
((Model) rt).save();
}
public static boolean exists(String tagRelated) {
for(Tag tag : Tag.find.all()) {
if(tagRelated.equals(tag.getName()))
return true;
}
return false;
}
public static RelatedTag findByLabel(String tagRelated, String relation, String relatedNotes) {
RelatedTag relatedTag = null;
for(Tag tag : Tag.find.all()) {
if(tagRelated.equals(tag.getName())) {
relatedTag = new RelatedTag(tag.getId(), relation, relatedNotes);
}
}
return relatedTag;
}
public static Tag findTag(int id) {
for(Tag tag : Tag.find.all()) {
if(id == tag.getId())
return tag;
}
return null;
}
}
What have I been doing wrong? Please help me fix this. Thank you very much!

Dozer 5.4 setCustomConverter does not work between fields of the same name but different types

I want to do custom type conversion with Dozer between fields with the same name but different types in source and destination objects.
I prepared code snippet that explains my intention:
package com;
import org.dozer.CustomConverter;
import org.dozer.DozerBeanMapper;
import org.dozer.DozerConverter;
import java.util.Arrays;
public class DozerTest
{
public static void main(String[] args)
{
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.setCustomConverters(Arrays.<CustomConverter>asList(new DozerConverter<Version, String>(Version.class, String.class)
{
#Override public String convertTo(Version version, String versionOrig)
{
return version.getFullVersion();
}
#Override public Version convertFrom(String version, Version versionOrig)
{
return new Version(version);
}
}));
OldPackage oldPackage = new OldPackage();
oldPackage.setVersion("1.1");
NewPackage newPackage = mapper.map(oldPackage, NewPackage.class);
System.out.println(newPackage.getVersion().getFullVersion());
}
public static class NewPackage
{
private Version version;
public Version getVersion()
{
return version;
}
public void setVersion(Version version)
{
this.version = version;
}
}
public static class OldPackage
{
private String version;
public String getVersion()
{
return version;
}
public void setVersion(String version)
{
this.version = version;
}
}
private static class Version
{
private final String fullVersion;
private Version(String fullVersion)
{
this.fullVersion = fullVersion;
}
public String getFullVersion()
{
return fullVersion;
}
}
}
I receive this error message:
Exception in thread "main" org.dozer.MappingException: Illegal object type for the method 'setVersion'.
Expected types:
com.DozerTest$Version
Actual types:
java.lang.String
Anyone has an idea what I am doing wrong?
Ik think you forgot to add your mapping to the mapper:
BeanMappingBuilder foo = new BeanMappingBuilder() {
#Override
protected void configure() {
mapping(OldPackage.class, NewPackage.class).fields("version", "version", FieldsMappingOptions.customConverter(ConverterImpl.class));
}
};
mapper.addMapping(foo);
I created a static inner class to represent your DozerConverter implementation to refer it in your BeanMappingBuilder:
static class ConverterImpl extends DozerConverter<Version, String> {
ConverterImpl() {
super(Version.class, String.class);
}
#Override public String convertTo(Version version, String versionOrig)
{
return version.getFullVersion();
}
#Override public Version convertFrom(String version, Version versionOrig)
{
return new Version(version);
}
}
The full class:
import org.dozer.CustomConverter;
import org.dozer.DozerBeanMapper;
import org.dozer.DozerConverter;
import org.dozer.loader.api.BeanMappingBuilder;
import org.dozer.loader.api.FieldsMappingOptions;
import java.util.Collections;
public class DozerTest
{
public static void main(String[] args)
{
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.setCustomConverters(Collections.<CustomConverter>singletonList(new ConverterImpl()));
BeanMappingBuilder foo = new BeanMappingBuilder() {
#Override
protected void configure() {
mapping(OldPackage.class, NewPackage.class).fields("version", "version", FieldsMappingOptions.customConverter(ConverterImpl.class));
}
};
mapper.addMapping(foo);
OldPackage oldPackage = new OldPackage();
oldPackage.setVersion("1.1");
NewPackage newPackage = mapper.map(oldPackage, NewPackage.class);
System.out.println(newPackage.getVersion().getFullVersion());
}
static class ConverterImpl extends DozerConverter<Version, String> {
ConverterImpl() {
super(Version.class, String.class);
}
#Override public String convertTo(Version version, String versionOrig)
{
return version.getFullVersion();
}
#Override public Version convertFrom(String version, Version versionOrig)
{
return new Version(version);
}
}
public static class NewPackage
{
private Version version;
public Version getVersion()
{
return version;
}
public void setVersion(Version version)
{
this.version = version;
}
}
public static class OldPackage
{
private String version;
public String getVersion()
{
return version;
}
public void setVersion(String version)
{
this.version = version;
}
}
private static class Version
{
private final String fullVersion;
private Version(String fullVersion)
{
this.fullVersion = fullVersion;
}
public String getFullVersion()
{
return fullVersion;
}
}
}
When executing this test class, you get the desired output:
13:56:34.994 [main] DEBUG org.dozer.MappingProcessor - MAPPED: DozerTest$OldPackage.version --> DozerTest$NewPackage.version VALUES: 1.1 --> be.smals.safe.centralplatform.core.utils.DozerTest$Version#1490eb5 MAPID:
1.1

How to escape from ClassCastException

This is my collection:
db.power.find().pretty()
{
"_id" : ObjectId("513e4022cc6d8d7ff2c83239"),
"Indicator" : "One",
"sex" : "male"
}
How to escape from ClassCastException?
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
public class Test {
public static void main(String args[]) throws UnknownHostException {
Mongo mongo = new Mongo();
DB db = mongo.getDB("at");
DBCollection testdata = db.getCollection("power");
BasicDBObject query = new BasicDBObject();
query.put("Indicator", "One");
PowerData data = (PowerData) testdata.findOne(query);
System.out.println(data.getSize());
}
}
import com.mongodb.BasicDBObject;
public class PowerData extends BasicDBObject{
public String getSize() {
return (String) get("sex");
}
public void setSize(String sex) {
put("sex", sex);
}
public String getIndicator() {
return (String) get("Indicator");
}
public void setIndicator(String Indicator) {
put("Indicator", Indicator);
}
public String getId() {
return (String) get("_id");
}
public void setId(String _id) {
put("_id", _id);
}
}
Exception in thread "main" java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to PowerData
at Test.main(Test.java:19)
You could change your PowerData class like this:
public class PowerData extends BasicDBObject{
private BasicDBObject wrapped;
public PowerData(BasicDBObject o) {
this.wrapped = o;
}
public String getSize() {
return (String) o.get("sex");
}
public void setSize(String sex) {
o.put("sex", sex);
}
public String getIndicator() {
return (String) o.get("Indicator");
}
public void setIndicator(String Indicator) {
o.put("Indicator", Indicator);
}
public String getId() {
return (String) o.get("_id");
}
public void setId(String _id) {
o.put("_id", _id);
}
}
And in your main method, replace PowerData data = (PowerData) testdata.findOne(query); with following:
PowerData data = new PowerData(testdata.findOne(query));

Categories

Resources