Drools decision table excel rules not working [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 days ago.
Improve this question
(https://i.stack.imgur.com/ASl5i.png)
Is there any wrong in this drools decision table excel?
this is the DroolCOnfig code.
public class DroolConfig {
private KieServices kieServices = KieServices.Factory.get();
private KieFileSystem getKieFileSystem() throws IOException {
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newClassPathResource("offers.xlsx",getClass()));
return kieFileSystem;
}
#Bean
public KieContainer getKieContainer() throws IOException {
System.out.println("Container created...");
getKieRepository();
KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem());
kb.buildAll();
KieModule kieModule = kb.getKieModule();
KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId());
return kContainer;
}
private void getKieRepository() {
final KieRepository kieRepository = kieServices.getRepository();
kieRepository.addKieModule(new KieModule() {
public ReleaseId getReleaseId() {
return kieRepository.getDefaultReleaseId();
}
});
}
#Bean
public KieSession getKieSession() throws IOException {
System.out.println("session created...");
return getKieContainer().newKieSession();
}
}
DataModel.
package com.javatechie.spring.drools.api;
public class Order {
private String name;
private String cardType;
private int discount;
private int price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCardType() {
return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
public int getDiscount() {
return discount;
}
public void setDiscount(int discount) {
this.discount = discount;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
i tried this below drl rule in excel.
package KieRule;
import com.javatechie.spring.drools.api.Order;
rule "HDFC"
when
orderObject : Order(cardType=="HDFC" && price>10000);
then
orderObject.setDiscount(10);
end;
rule "ICICI"
when
orderObject : Order(cardType=="ICICI" && price>15000);
then
orderObject.setDiscount(8);
end;
rule "DBS"
when
orderObject : Order(cardType=="DBS" && price>15000);
then
orderObject.setDiscount(15);
end;

Related

Stream filter returns NullPointerException in condition [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I have a condition that does not work due to NullPointerException. This is my code:
public class RightDrawerItem {
User user;
String sectionName, title, subitle, subtitle2;
int amount, icon;
boolean expanded;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void setSectionName(String sectionName) {
this.sectionName = sectionName;
}
public boolean isExpanded() {
return expanded;
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
public String getSubitle() {
return subitle;
}
public void setSubitle(String subitle) {
this.subitle = subitle;
}
public String getSubtitle2() {
return subtitle2;
}
public void setSubtitle2(String subtitle2) {
this.subtitle2 = subtitle2;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getSectionName() {
return sectionName;
}
public String getTitle() {
return title;
}
public int getIcon() {
return icon;
}
public int getAmount() {
return amount;
}
public static class Builder {
private String sectionName, title;
private final int amount;
boolean expanded;
private int icon;
private User user;
public Builder(int amount) {
this.expanded = false;
this.amount = amount;
}
public Builder title(String title) {
this.title = title;
return this;
}
public Builder icon(int icon) {
this.icon = icon;
return this;
}
public Builder sectionName(String sectionName) {
this.sectionName = sectionName;
return this;
}
public Builder user(User user) {
this.user = user;
return this;
}
public RightDrawerItem build() {
return new RightDrawerItem(this);
}
}
public RightDrawerItem(Builder builder) {
this.title = builder.title;
this.icon = builder.icon;
this.amount = builder.amount;
this.sectionName = builder.sectionName;
this.user = builder.user;
}
}
Here is my User class:
public class User {
String name;
int level, exp, gold;
Timestamp regDate;
public Timestamp getRegDate() {
return regDate;
}
public void setRegDate(Timestamp regDate) {
this.regDate = regDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public int getGold() {
return gold;
}
public void setGold(int gold) {
this.gold = gold;
}
public User(String name, int level, int exp, int gold, Timestamp regDate) {
this.name = name;
this.level = level;
this.exp = exp;
this.gold = gold;
this.regDate = regDate;
}
}
And here is my condition code in SearchAdapter:
List<RightDrawerItem> rightDrawerItems;
List<User> users;
...
if (!Stream.of(rightDrawerItems).filter(o -> o.getTitle() != null).anyMatch(o -> o.getTitle().equals(users.get(pos).getName())))
The problem is that this .filter seems not to work because .anyMatch finds sometimes such elements which getTitle() returns null. How to solve it?
The Exception states that o itself is null, so you can't call null.getTitle(). You can add .filter(Objects::nonNull) to 'skip' those in your check:
if (Stream.of(rightDrawerItems) //note the removed
.filter(Objects::nonNull) // <- avoid Exceptions due to o==null
.filter(o -> o.getTitle() != null)
.anyMatch(o -> o.getTitle().equals(users.get(pos).getName()))
)
But it may be advisable to figure out why some of your rightDrawerItems could be null in the first place.
A neater way of writing the above could also be:
if (Stream.of(rightDrawerItems) //note the removed negation (noneMatch below)
.filter(Objects::nonNull) // <- avoid Exceptions due to o==null
.map(RightDrawerItem::getTitle) //we're interested in the title
.noneMatch(users.get(pos).getName()::equals) //use noneMatch
)
if (!Stream.of(rightDrawerItems).filter(o -> o != null).filter(o -> o.getTitle() != null).anyMatch(o -> o.getTitle().equals(users.get(pos).getName())))
solves my problem.

Records missing due to Chunk count in SpringBatc

We have a batch job to load millions of Employee data with multiple address, It is failing to load few rows when I use chunk.
For example if I use chunk 5 and we loose 6th record which is associate to 5th row employee(refer image)
Please suggest a solution. Here is the Spring Batch code
#Configuration
public class EmployeeJobMyBatis {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Autowired
private EmployeeDataSourceConfig datasourceConfig;
EmployeeRowMapper rowMapper = null;
private static final Logger LOG = LogManager.getLogger(EmployeeJobMyBatis.class);
#Bean
#Qualifier("MyBatisJob")
public Job mybatisJob() throws Exception {
return this.jobBuilderFactory.get("MyBatisJob").incrementer(new RunIdIncrementer())
.start(step()).build();
}
#Bean
public Step step() throws SQLException, Exception {
return this.stepBuilderFactory.get("EmployeeDataReadStep").<Employee, String>chunk(5)
.reader(reader()).processor(processor()).writer(writer())
.build();
}
#Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
SqlSessionFactoryBean ss = new SqlSessionFactoryBean();
ss.setDataSource(datasourceConfig.getDataSource());
ss.setMapperLocations(resourcePatternResolver.getResources("employee.xml"));
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setDefaultExecutorType(ExecutorType.BATCH);
ss.setConfiguration(configuration);
return ss.getObject();
}
#Bean
public MyBatisCursorItemReader<Employee> reader() throws Exception {
MyBatisCursorItemReader<Employee> reader = new MyBatisCursorItemReader<Employee>();
reader.setSqlSessionFactory(sqlSessionFactory());
reader.setQueryId("EmployeeData");
return reader;
}
#Bean
public processor processor() {
return new DataProcessor();
}
#Bean
public MultiResourceItemWriter<String> writer() {
MultiResourceItemWriter<String> writer = new MultiResourceItemWriter<String>();
writer.setResource(new FileSystemResource("C:/data/Employee.json"));
writer.setItemCountLimitPerResource(2500000);
FlatFileItemWriter<String> fileWriter = new FlatFileItemWriter<String>();
fileWriter.setLineAggregator(new MyDelimitedLineAggregator());
writer.setDelegate(fileWriter);
return writer;
}
}
public class DataProcessor implements ItemProcessor<Employee, String> {
private static final Gson gson = new GsonBuilder().create();
#Override
public String process(Employee employee) throws Exception {
if (employee != null && employee.getId() == null)
return null;
else
return (String) (gson.toJson(employee));
}
}
public class MyDelimitedLineAggregator extends DelimitedLineAggregator<String> {
String returnString = "";
#Override
public String aggregate(String jsonstr) {
if(jsonstr != null)
returnString = jsonstr;
return returnString;
}
}
public class Employee{
String emplId;
Addresses addressList;
public String getEmplId() {
return emplId;
}
public void setEmplId(Addresses value) {
this.emplId = value;
}
public Addresses getAddressList() {
return addressList;
}
public void setAddressList(Addresses value) {
this.addressList = value;
}
}
public class Addresses{
List<Address> addresses;
public List<Address> getAddresses() {
if (addresses == null) {
addresses = new ArrayList<Address>();
}
return this.addresses;
}
}
public class Address{
String addressLineOne;
String city;
String country;
public String getAddressLineOne(){
return addressLineOne;
}
public void setAddressLineOne(String value) {
this.addressLineOne = value;
}
public String getCity(){
return city;
}
public void setCity(String value) {
this.city = value;
}
public String getCountry(){
return country;
}
public void setCountry(String value) {
this.country = value;
}
}
Here is the MyBatis Mapper xml
Employee.xml
<resultMap id="EmployeeMap" type="Employee">
<id column="emplId" property="emplId"/>
<collection property="addressList.addresses"
javaType="list" ofType="Address">
<result column="addressLineOne" property="addressLineOne"/>
<result column="city" property="city"/>
<result column="country" property="country"/>
</collection>
</resultMap>
<select id="employeeData" resultMap="EmployeeMap">select * from employee e left join address a on a.emplId = e.emplId</select>
A chunk oriented step reads rows one by one and map each one to a domain object (basically one to one mapping). In your case, you have a one to many relation. So your step configuration won't work as it is now. What you need to do is implement the driving query pattern as follows:
Make the reader reads employee details except addresses
Use an item processor that fetches addresses for the current employee
Edit: Add an example
import javax.sql.DataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.batch.item.database.builder.JdbcCursorItemReaderBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
#Configuration
#EnableBatchProcessing
public class MyJob {
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("/org/springframework/batch/core/schema-drop-h2.sql")
.addScript("/org/springframework/batch/core/schema-h2.sql")
.build();
}
#Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
#Bean
public JdbcCursorItemReader<Person> itemReader() {
return new JdbcCursorItemReaderBuilder<Person>()
.name("personItemReader")
.dataSource(dataSource())
.sql("select id, name from person")
.beanRowMapper(Person.class)
.build();
}
#Bean
public ItemProcessor<Person, Person> itemProcessor() {
return new ItemProcessor<Person, Person>() {
#Autowired
private JdbcTemplate jdbcTemplate;
#Override
public Person process(Person person) {
Address address = jdbcTemplate.queryForObject("select * from address where personId = ?", new Object[]{person.getId()}, new BeanPropertyRowMapper<>(Address.class));
person.setAddress(address);
return person;
}
};
}
#Bean
public ItemWriter<Person> itemWriter() {
return items -> {
for (Person item : items) {
System.out.println("item = " + item);
}
};
}
#Bean
public Job job(JobBuilderFactory jobs, StepBuilderFactory steps) {
return jobs.get("job")
.start(steps.get("step")
.<Person, Person>chunk(2)
.reader(itemReader())
.processor(itemProcessor())
.writer(itemWriter())
.build())
.build();
}
public static void main(String[] args) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(MyJob.class);
JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);
jdbcTemplate.update("CREATE TABLE address (id INT IDENTITY NOT NULL PRIMARY KEY, personId INT, street VARCHAR(20));");
jdbcTemplate.update("CREATE TABLE person (id INT IDENTITY NOT NULL PRIMARY KEY, name VARCHAR(20));");
jdbcTemplate.update("INSERT INTO address (id, personId, street) VALUES (1,1, 'oxford street');");
jdbcTemplate.update("INSERT INTO address (id, personId, street) VALUES (2,2, 'howard street');");
jdbcTemplate.update("INSERT INTO person (id, name) VALUES (1, 'foo');");
jdbcTemplate.update("INSERT INTO person (id, name) VALUES (2, 'bar');");
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
Job job = context.getBean(Job.class);
jobLauncher.run(job, new JobParameters());
}
public static class Person {
private long id;
private String name;
private Address address;
public Person() {
}
public Person(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", address=" + address +
'}';
}
}
public static class Address {
private int id;
private int personId;
private String street;
public Address() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public int getPersonId() {
return personId;
}
public void setPersonId(int personId) {
this.personId = personId;
}
#Override
public String toString() {
return "Address{" +
"id=" + id +
", street='" + street + '\'' +
'}';
}
}
}
This example reads person/address data. The reader reads only the person's id and name, and a processor fetches the address for the current item.

How to get response from Array in retrofit? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Here is my response. I don't know how to create Response Model for this type of response model
[{"id":"4","templateName":"FUP 100","dataUsage":"100 GB","price":236,"groupName":"","bandwidthName":""},{"id":"19","templateName":"FUP200","dataUsage":"200 GB","price":299.72,"groupName":"","bandwidthName":""}]
your retrofit call must be a list of your object not just the object
your object is like that
public class MyClass
{
private String id;
private String groupName;
private String price;
private String dataUsage;
private String bandwidthName;
private String templateName;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getGroupName ()
{
return groupName;
}
public void setGroupName (String groupName)
{
this.groupName = groupName;
}
public String getPrice ()
{
return price;
}
public void setPrice (String price)
{
this.price = price;
}
public String getDataUsage ()
{
return dataUsage;
}
public void setDataUsage (String dataUsage)
{
this.dataUsage = dataUsage;
}
public String getBandwidthName ()
{
return bandwidthName;
}
public void setBandwidthName (String bandwidthName)
{
this.bandwidthName = bandwidthName;
}
public String getTemplateName ()
{
return templateName;
}
public void setTemplateName (String templateName)
{
this.templateName = templateName;
}
#Override
public String toString()
{
return "MyClass [id = "+id+", groupName = "+groupName+", price = "+price+", dataUsage = "+dataUsage+", bandwidthName = "+bandwidthName+", templateName = "+templateName+"]";
}
}
kotlin :
class MyClass {
var id:String
var groupName:String
var price:String
var dataUsage:String
var bandwidthName:String
var templateName:String
public override fun toString():String {
return "MyClass [id = " + id + ", groupName = " + groupName + ", price = " + price + ", dataUsage = " + dataUsage + ", bandwidthName = " + bandwidthName + ", templateName = " + templateName + "]"
}
}
there are online tools to help you http://pojo.sodhanalibrary.com/
public class Response {
#SerializedName("id")
#Expose
private String id;
#SerializedName("templateName")
#Expose
private String templateName;
#SerializedName("dataUsage")
#Expose
private String dataUsage;
#SerializedName("price")
#Expose
private Double price;
#SerializedName("groupName")
#Expose
private String groupName;
#SerializedName("bandwidthName")
#Expose
private String bandwidthName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTemplateName() {
return templateName;
}
public void setTemplateName(String templateName) {
this.templateName = templateName;
}
public String getDataUsage() {
return dataUsage;
}
public void setDataUsage(String dataUsage) {
this.dataUsage = dataUsage;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getBandwidthName() {
return bandwidthName;
}
public void setBandwidthName(String bandwidthName) {
this.bandwidthName = bandwidthName;
}
}
Then Create ArrayList because your response start with array :
#Headers("Content-Type:application/json")
#GET("your_api")
Call<ArrayList<Response>> api();

FlatFileItemReader cannot be cast when being accessed from custom ItemReader

I currently have an application that I'm attempting to diagnose what in the setup I've done incorrectly, and am not having any luck in determining why it's not working outside of very specific situations.
First the code that I'm using.
Configuration.java
#EnableBatchProcessing
#SpringBootApplication(scanBasePackages="com.lcbo")
#EnableIntegration
public class COnfig {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Autowired
private LCBOInventoryTrackerProperties inventoryTrackerProperties;
#Bean
public Job processLCBOInventory(#Qualifier("getLCBOStoreDataStep") final Step getLCBOStoreDataStep) {
return jobBuilderFactory
.get("processLCBOInventory")
.incrementer(new RunIdIncrementer())
.start(getLCBOStoreDataStep)
.build();
}
/**
* This tasklet downloads the .zip file, unzips, and saves it in the appropriate folder under resources.
* Execute at 6am daily
*
// * #param AcquireDataFileTasklet acquireDataFiles
* #return Step - returns Step status; either SUCCESS or FAILURE
*/
#Bean
public Step getCurrentLCBODataStep(final AcquireDataFileTasklet acquireDataFiles,
final ExecutionContextPromotionListener listener) {
return stepBuilderFactory
.get("getCurrentLCBODataStep")
.tasklet(acquireDataFiles)
.allowStartIfComplete(true)
.listener(listener)
.build();
}
#Bean
public Step getLCBOStoreDataStep(final LCBOStoreReader lcboStoreReader,
final LCBOStoreWriter lcboStoreWriter) {
return stepBuilderFactory
.get("getLCBOStoreDataStep")
.<LCBOStore, LCBOStore>chunk(inventoryTrackerProperties.getDefaults().getChunkSize())
.reader(lcboStoreReader)
.writer(lcboStoreWriter)
.build();
}
}
The reader class
#Component
public class LCBOStoreReader extends AbstractLCBOReader implements ItemReader, InterstepDataRetriever {
private static final Logger log = LoggerFactory.getLogger(LCBOStoreReader.class);
#Override
public ItemReader<LCBOStore> read() throws UnexpectedInputException, ParseException, NonTransientResourceException {
Class<LCBOStore> classType = LCBOStore.class;
return createCSVReader(classType, currentCSVFilePath, inventoryTrackerProperties.getLCBOFilPropertiess().getStores());
}
/*
#Override
public void beforeStep(final StepExecution stepExecution) {
JobExecution jobExecution = stepExecution.getJobExecution();
ExecutionContext jobContext = jobExecution.getExecutionContext();
this.currentWorkingDate = (String) jobContext.get("currentWorkingDateKey");
}
*/
#Override
public void retrieveInterstepDataFromJobContext(final ExecutionContext jobContext) {
this.currentCSVFilePath = (String) jobContext.get("currentCSVFilePathKey");
}
}
and the class it extends (because the FlatFileItemReader setup is used by multiple readers)
public abstract class AbstractLCBOReader {
#Autowired
protected LCBOInventoryTrackerProperties inventoryTrackerProperties;
protected String currentCSVFilePathKey;
protected String currentCSVFilePath;
private static final Logger log = LoggerFactory.getLogger(AbstractLCBOReader.class);
protected <T> ItemReader<T> createCSVReader(final Class<T> classType,
final String currentCSVFilePath,
final LCBOFileDetailsProperties properties) {
FlatFileItemReader<T> reader = new FlatFileItemReader<>();
// Skip a line to ignore the header information in these files
reader.setLinesToSkip(properties.getNumberOfLinesToSkipInFile());
reader.setResource(new FileSystemResource(currentCSVFilePath + File.separator + properties.getFileName()));
reader.setLineMapper(createLineMapper(classType, properties));
reader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy());
reader.setEncoding("utf8");
return reader;
}
private <T> LineMapper<T> createLineMapper(final Class<T> classType, final LCBOFileProperties.LCBOFileDetailsProperties properties) {
DefaultLineMapper<T> lineMapper = new DefaultLineMapper<>();
lineMapper.setLineTokenizer(createLineTokenizer(properties));
lineMapper.setFieldSetMapper(createFieldSetMapper(classType));
return lineMapper;
}
private <T> FieldSetMapper<T> createFieldSetMapper(final Class<T> classType) {
BeanWrapperFieldSetMapper<T> fieldSetMapper = new BeanWrapperFieldSetMapper<>();
fieldSetMapper.setTargetType(classType);
return fieldSetMapper;
}
private LineTokenizer createLineTokenizer(final LCBOFileProperties.LCBOFileDetailsProperties properties) {
LCBOFileProperties.Column[] columns = properties.getColumns();
int[] columnIndexes = new int[columns.length];
String[] columnNames = new String[columns.length];
// populating the columnIndexes
for (int i = 0; i < columns.length; i++) {
columnIndexes[i] = columns[i].getColumnIndex();
columnNames[i] = columns[i].getColumnName();
}
DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer();
lineTokenizer.setIncludedFields(columnIndexes);
lineTokenizer.setNames(columnNames);
lineTokenizer.setDelimiter(",");
lineTokenizer.setQuoteCharacter('"');
return lineTokenizer;
}
}
The error when executing this will be that the object cannot be cast from FlatFileItemreader to the object passed as the first parameter in createCSVReader. Here's an example.
public class LCBOStore {
private Long id;
private String addressLineOne;
private String addressLineTwo;
private String city;
private String postalCode;
private String latitude;
private String longitude;
private String updatedAt; //Convert to Date
public LCBOStore(final Long id, final String addressLineOne, final String addressLineTwo, final String city,
final String postalCode, final String latitude, final String longitude, final String updatedAt) {
this.id = id;
this.addressLineOne = addressLineOne;
this.addressLineTwo = addressLineTwo;
this.city = city;
this.postalCode = postalCode;
this.latitude = latitude;
this.longitude = longitude;
this.updatedAt = updatedAt;
}
public Long getId() {
return id;
}
public String getAddressLineOne() {
return addressLineOne;
}
public String getAddressLineTwo() {
return addressLineTwo;
}
public String getCity() {
return city;
}
public String getPostalCode() {
return postalCode;
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setId(final Long id) {
this.id = id;
}
public void setAddressLineOne(final String addressLineOne) {
this.addressLineOne = addressLineOne;
}
public void setAddressLineTwo(final String addressLineTwo) {
this.addressLineTwo = addressLineTwo;
}
public void setCity(final String city) {
this.city = city;
}
public void setPostalCode(final String postalCode) {
this.postalCode = postalCode;
}
public void setLatitude(final String latitude) {
this.latitude = latitude;
}
public void setLongitude(final String longitude) {
this.longitude = longitude;
}
public void setUpdatedAt(final String updatedAt) {
this.updatedAt = updatedAt;
}
#Override
public String toString() {
return "StoreDBModel [id=" + id + ", addressLineOne=" + addressLineOne + ", city=" + city
+ ", postalCode=" + postalCode + ", latitude=" + latitude + ", longitude="
+ longitude + ", updatedAt=" + updatedAt + "]";
}
}
Now if I move the FlatFileItemReader mode that exists in createCSVReader into the constructor of the custom Reader class, or have it so it's in the configuration file, it works fine. However, I couldn't figure out how to work with job and step context in those configurations (the constructor executes before you can access step and jobContext it seems from my testing, and I could never figure how to access when put in the Config class.). Plus to me at least, it looks cleaner to have the Reader code in it's own file not being stuffed in the constructor.
So in a nutshell, is there a way to fix this os that having it in it's own reader class would work? Am I doing this incorrectly and using bad practices? Maybe a mix of the two? If there's anything missing please ask away and I'll attempt to clarify.
So I found the answer to be very simple with some help from those in the comments. Here's my solution.
First, add the bolded code to the abstract class createCSVWriter method
**protected <T> T** createCSVReader(final Class<T> classType,
final String currentCSVFilePath,
final LCBOFileDetailsProperties properties) throws Exception {
FlatFileItemReader<T> reader = new FlatFileItemReader<>();
// Skip a line to ignore the header information in these files
reader.setLinesToSkip(properties.getNumberOfLinesToSkipInFile());
reader.setResource(new FileSystemResource(currentCSVFilePath + File.separator + properties.getFileName()));
reader.setLineMapper(createLineMapper(classType, properties));
reader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy());
reader.setEncoding("utf8");
**return reader.read();**
}
Doing the read call manually will prevent it returning more then needed for your reader class. Then in the reader class edit the following
#Override
public **LCBOStore** read() throws **Exception**, UnexpectedInputException, ParseException, NonTransientResourceException {
Class<LCBOStore> classType = LCBOStore.class;
return createCSVReader(classType, currentCSVFilePath, inventoryTrackerProperties.getLCBOFilPropertiess().getStores());
}
This just returns the object you've created and hence issue resolved.

Class Return type when creating a method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
[UML Diagram][1]
I'm studying for the midterm exam next week and I'm practicing some given examples from my professor; however, I am having some trouble with class return type methods.
I attached UML diagram just in case.
What i'm trying to understand is getPerson method in Job class. I don't think i need a array list in Job class to store all the employee. Because I have an array list already in Company class. Also return type is Employee class that I'm not sure how to get person's info using this class return type.
My problems
public Employee getPerson() {} in Job class
public boolean isVacant() {} in Job class
Also would you mind checking getVacantJobs, getFilledJobs, and getAllJobs methods if those are correctly built?
I used iterator to display all the stored jobs.
---------------------------Employee Class -----------------------------
public class Employee {
private String name;
private int id;
public Employee(int id, String name) {
this.name = name;
this.id =id;
}
public final String getName() {
return name;
}
public final void setName(String name) {
this.name = name;
}
public final int getId() {
return id;
}
public final void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "Employee [name=" + name + ", id=" + id + "]";
}
}
----------------------------Job Class--------------------------------------
public class Job {
private String description;
private int id;
private double maxSalary;
public Job(int id, double maxSalary, String description) {
this.description = description;
this.id = id;
this.maxSalary = maxSalary;
}
public Job(int id, double maxSalary, String description, Employee e1) {
this.description = description;
this.id = id;
this.maxSalary = maxSalary;
}
#Override
public String toString() {
return "Job [description=" + description + ", id=" + id
+ ", maxSalary=" + maxSalary + "]";
}
public final String getDescription() {
return description;
}
public final void setDescription(String description) {
this.description = description;
}
public final double getMaxSalary() {
return maxSalary;
}
public final void setMaxSalary(double maxSalary) {
this.maxSalary = maxSalary;
}
public final int getId() {
return id;
}
public Employee getPerson() {
retrun
}
public final void setPerson(Employee person) {
this.id = person.getId();
}
}
--------------------------Company Class ---------------------------
import java.util.ArrayList;
import java.util.Iterator;
public class Company {
static ArrayList list = new ArrayList();
Iterator itr = list.iterator();
private String name;
public Company(String name) {
this.name = name;
}
public Company() {
// TODO Auto-generated constructor stub
}
public static void addJob(Job j1) {
list.add(j1);
}
public void removeJob(int id) {
list.remove(id);
}
public ArrayList<Job> getVacantJobs() {
while (itr.hasNext()) {
if ((itr == null)) {
System.out.println(itr);
}
}
return null;
}
public ArrayList<Job> getFilledJobs() {
while (itr.hasNext()) {
if (!(itr == null)) {
System.out.println(itr);
}
}
return null;
}
public ArrayList<Job> getAllJobs() {
while (itr.hasNext()) {
System.out.println(itr.next());
}
return null;
}
}
Add field person to Job class.
public class Job {
// .....
private Employee person;
public Employee getPerson() {
return person;
}
public final void setPerson(Employee person) {
this.person = person;
}
public boolean isVacant() {
return person == null;
}
}
And add jobs field to Company class.
public class Company {
// static ArrayList list = new ArrayList(); // You don't need this
// Iterator itr = list.iterator(); // You don't need this.
// .....
private ArrayList<Job> jobs = new ArrayList<>();
public ArrayList<Job> getVacantJobs() {
ArrayList<Job> result = new ArrayList<>();
for (Job job : jobs)
if (job.isVacant())
result.add(job);
return result;
}
public ArrayList<Job> getFilledJobs() {
ArrayList<Job> result = new ArrayList<>();
for (Job job : jobs)
if (!job.isVacant())
result.add(job);
return result;
}
public ArrayList<Job> getAllJobs() {
ArrayList<Job> result = new ArrayList<>();
for (Job job : jobs)
result.add(job);
return result;
}
}

Categories

Resources