json array writting to excel - java

I have a code like this,
examples of data:
{"reason":"TEST","viewDate":1674596700000,"userName":"ABC"}
{"reason":"TEST1","viewDate":1674596700000,"userName":"DEF"}
Key is a String array {reason, viewData, userName}
JSONArray data = null;
for(int i=0; i<data.length(); i++){
row = sheet.createRow(rownum);
rownum++;
System.out.println("... "+data.getJSONObject(i));
for(int cellnum = 0; cellnum < keys.length; cellnum++){
cell = row.createCell(cellnum);
//if(data.getJSONObject(i).has("viewDate") &&
!data.getJSONObject(i).isNull("viewDate"))
//cell.setCellValue(formatter.format(data.getJSONObject(i).get("viewDate")))
;
if(data.getJSONObject(i).has(keys[cellnum]) &&
!data.getJSONObject(i).isNull(keys[cellnum]))
cell.setCellValue(""+data.getJSONObject(i).get(keys[cellnum]));
else
cell.setCellValue("");
}
}
From above if the jsonObject matches with the key, i write data to cell. I
need to add one more condition
where if the data.getJSONObject(i) header is 'viewDate' then i need to
format the date to certain format. I added this condition but commented out
the code above.
If i uncomment and execute i get the below result
viewDate userName reason
2023 01 29 21:55 2023 01 29 21:55 2023 01 29 21:55
2023 01 24 16:45 2023 01 24 16:45 2023 01 24 16:45
What i am expecting is
viewDate userName reason
2023 01 29 21:55 ABC TEST
2023 01 24 16:45 DEF TEST1

Related

How should I manage fact insertion in drools to avoid a memory leak?

I am using Drools 7.8.0 to manage real time data ( 10000 facts every 5 seconds).
I am inserting them in the working memory using :
KieSession kieSession = kieContainer.newKieSession();
EntryPoint entryPoint = kieSession.getEntryPoint("myData");
new Thread( new Runnable() {
#Override
public void run() {
kieSession.fireUntilHalt();
}
} ).start();
while ( true )
{
Data data = recieveData();
factHandle=entryPoint.insert(data);
}
However, this is causing a memory leak :
64,994 instances of "org.drools.core.common.EventFactHandle", loaded by "jdk.internal.loader.ClassLoaders$AppClassLoader # 0x702500000" occupy 113,316,792 (71.06%) bytes. These instances are referenced from one instance of "java.lang.Thread", loaded by "<system class loader>"
so I tried keeping track of my facts and using update instead of insert but this affected the rule's behavior and some facts weren't matched.
Map<String,FactHandle> allfacts = new HashMap<String,FactHandle>();
if( !allfacts.containsKey(dataName) && data!=null)
{
factHandle=entryPoint.insert(data);
allfacts.put(dataName,factHandle);
}
else
{
entryPoint.update(allfacts.get(dataName), opcTagData);
}
}
catch(Exception ex)
{
//error
}
Here's an example of the rules I have:
declare Data
#role( event )
#timestamp( timestamp )
#expires( 20s )
end
rule "status not available for 10 seconds "
dialect "java"
when
d: Data(Name.contains("/Smart/Status")) from entry-point "myData"
eval(!d.getValue().equals("Available"))
not(
Data(
this.getName() == d.getName(),
this.getValue().equals("Available"),
this after[0s,10s] d) from entry-point "myData")
then
doSmthg();
end
I can't figure out what's the right way to to insert the facts and still get the expected result without facing a memory leak
PS:
I'm using fireUntilHalt because I used Temporal Operators when writing the rules and I noticed that using fireallrules does not give me the expected result.
I tested your rule and retraction works for me. Each event was retracted in 20s.
Can you confirm you use stream mode?
Set stream mode using system property
drools.eventProcessingMode=stream
Set stream mode using Java client API
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.KieServices.Factory;
KieBaseConfiguration config = KieServices.Factory.get().newKieBaseConfiguration();
config.setOption(EventProcessingOption.STREAM);
Set stream mode using project kmodule.xml file
<kmodule>
...
<kbase name="KBase2" default="false" eventProcessingMode="stream" packages="org.domain.pkg2, org.domain.pkg3" includes="KBase1">
...
</kbase>
...
</kmodule>
It happened in previous versions of drools that explicit event retraction worked better
rule "retract expired events"
salience 1
duration 20000
when
d: Data() from entry-point "myData"
then
retract(d);
end
This is how I tested your code
test.drl
package draft;
dialect "java"
declare Data
#role(event)
#timestamp(timestamp)
#expires(20s)
end
rule "retract expired events"
salience 1
duration 20000
when
d: Data() from entry-point "test it"
then
retract(d);
end
rule "status not available for 10 seconds"
when
d: Data(Name.contains("/Smart/Status")) from entry-point "myData"
eval(!d.getValue().equals("Available"))
not(
Data(
this.getName() == d.getName(),
this.getValue().equals("Available"),
this after[0s,10s] d) from entry-point "myData")
then
System.out.println("alert");
end
PlaygroundTest.java
#DroolsSession("test.drl")
public class PlaygroundTest {
#Rule
public DroolsAssert drools = new DroolsAssert();
#Test
public void testIt() {
for (int i = 0; i < 5; i++) {
drools.insertAndFireAt("myData", new Data(new Date(SECONDS.toMillis(i * 5)), "/Smart/Status", "Unavailable"));
drools.advanceTime(5, SECONDS);
drools.printFacts();
}
drools.assertFactsCount(3);
drools.advanceTime(5, SECONDS);
drools.printFacts();
drools.assertFactsCount(2);
drools.advanceTime(5, SECONDS);
drools.printFacts();
drools.assertFactsCount(1);
drools.advanceTime(5, SECONDS);
drools.printFacts();
drools.assertFactsCount(0);
}
}
Data.java
public class Data {
private Date timestamp;
private String name;
private String value;
public Data(Date timestamp, String name, String value) {
this.timestamp = timestamp;
this.name = name;
this.value = value;
}
public Date getTimestamp() {
return timestamp;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
stdout
00:00:00 --> inserted: Data[timestamp=Thu Jan 01 02:00:00 EET 1970,name=/Smart/Status,value=Unavailable]
00:00:00 --> fireAllRules
00:00:05 Facts (1):
Data[timestamp=Thu Jan 01 02:00:00 EET 1970,name=/Smart/Status,value=Unavailable]
00:00:05 --> inserted: Data[timestamp=Thu Jan 01 02:00:05 EET 1970,name=/Smart/Status,value=Unavailable]
00:00:05 --> fireAllRules
00:00:10 <-- 'status not available for 10 seconds' has been activated by the tuple [Data]
alert
00:00:10 Facts (2):
Data[timestamp=Thu Jan 01 02:00:00 EET 1970,name=/Smart/Status,value=Unavailable]
Data[timestamp=Thu Jan 01 02:00:05 EET 1970,name=/Smart/Status,value=Unavailable]
00:00:10 --> inserted: Data[timestamp=Thu Jan 01 02:00:10 EET 1970,name=/Smart/Status,value=Unavailable]
00:00:10 --> fireAllRules
00:00:15 <-- 'status not available for 10 seconds' has been activated by the tuple [Data]
alert
00:00:15 Facts (3):
Data[timestamp=Thu Jan 01 02:00:00 EET 1970,name=/Smart/Status,value=Unavailable]
Data[timestamp=Thu Jan 01 02:00:05 EET 1970,name=/Smart/Status,value=Unavailable]
Data[timestamp=Thu Jan 01 02:00:10 EET 1970,name=/Smart/Status,value=Unavailable]
00:00:15 --> inserted: Data[timestamp=Thu Jan 01 02:00:15 EET 1970,name=/Smart/Status,value=Unavailable]
00:00:15 --> fireAllRules
00:00:20 <-- 'status not available for 10 seconds' has been activated by the tuple [Data]
alert
00:00:20 Facts (3):
Data[timestamp=Thu Jan 01 02:00:05 EET 1970,name=/Smart/Status,value=Unavailable]
Data[timestamp=Thu Jan 01 02:00:10 EET 1970,name=/Smart/Status,value=Unavailable]
Data[timestamp=Thu Jan 01 02:00:15 EET 1970,name=/Smart/Status,value=Unavailable]
00:00:20 --> inserted: Data[timestamp=Thu Jan 01 02:00:20 EET 1970,name=/Smart/Status,value=Unavailable]
00:00:20 --> fireAllRules
00:00:25 <-- 'status not available for 10 seconds' has been activated by the tuple [Data]
alert
00:00:25 Facts (3):
Data[timestamp=Thu Jan 01 02:00:10 EET 1970,name=/Smart/Status,value=Unavailable]
Data[timestamp=Thu Jan 01 02:00:15 EET 1970,name=/Smart/Status,value=Unavailable]
Data[timestamp=Thu Jan 01 02:00:20 EET 1970,name=/Smart/Status,value=Unavailable]
00:00:30 <-- 'status not available for 10 seconds' has been activated by the tuple [Data]
alert
00:00:30 Facts (2):
Data[timestamp=Thu Jan 01 02:00:15 EET 1970,name=/Smart/Status,value=Unavailable]
Data[timestamp=Thu Jan 01 02:00:20 EET 1970,name=/Smart/Status,value=Unavailable]
00:00:35 Facts (1):
Data[timestamp=Thu Jan 01 02:00:20 EET 1970,name=/Smart/Status,value=Unavailable]
00:00:40 Facts (0):

How do i get a particular day from Jan to Dec

I am new to java and I am trying to get all the 7th day in the year 2009.
I am a bit confused about how to go about it. Below is my code
public class Main {
public static void main(String[] args) {
System.out.println("WELCOME TO MY CALENDER CLASS");
Calendar calendar = Calendar.getInstance();
calendar.set(DAY_OF_MONTH,7);
calendar.set(Calendar.YEAR,2009);
for(int i =1; i <= 12; i++){
calendar.set(DAY_OF_MONTH,i);
System.out.println(calendar.getTime());
}
}
}
Update: This below is my result
Sun Mar 01 23:41:14 GMT 2009
Mon Mar 02 23:41:14 GMT 2009
Tue Mar 03 23:41:14 GMT 2009
Wed Mar 04 23:41:14 GMT 2009
Thu Mar 05 23:41:14 GMT 2009
Fri Mar 06 23:41:14 GMT 2009
Sat Mar 07 23:41:14 GMT 2009
Sun Mar 08 23:41:14 GMT 2009
Mon Mar 09 23:41:14 GMT 2009
Tue Mar 10 23:41:14 GMT 2009
Wed Mar 11 23:41:14 GMT 2009
Thu Mar 12 23:41:14 GMT 2009
OK, assuming you are starting from 1st of January here is a simple example for your cause. I hope Java1.8 code is clear to you.
public static void main(String[] args) {
// create two localdate start of a year instances, one for current year and one for next year, 2009 and 2010 respectively
LocalDate thisYear = LocalDate.of(2009, Month.JANUARY, 1);
LocalDate nextYear = LocalDate.of(2010, Month.JANUARY, 1);
// used only for counting number of every seventh day in a year
int i=0;
// while we are not in the next year, 2010
while (thisYear.isBefore(nextYear)) {
i++;
// print current date
System.out.println(i+" " + thisYear.toString());
// add a week or seven days to our thisYear instance and loop thru again
thisYear = thisYear.plusWeeks(1);
}
}
The problem with your code is that in the for loop you set the day and not the month for the Calendar object.
So change to this:
for(int i = 0; i < 12; i++){
calendar.set(Calendar.MONTH, i);
System.out.println(calendar.getTime());
}
The loop starts from 0 and goes up to 11 because the months are 0 based.
If you can use LocalDate then your code would be much simpler and more efficient:
System.out.println("WELCOME TO MY CALENDER CLASS");
LocalDate date;
for(int i = 1; i <= 12; i++){
date = LocalDate.of(2009, Month.of(i), 7);
System.out.println(date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
}

Loop in csv file

I asked this question before however I did not get the answer that I expected. Therefore I opened this new question.
My try:
String fileName = "placements.csv";
try {
// Assume default encoding.
FileWriter fileWriter = new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
// First row, write the head of the csv file.
bufferedWriter.write(FILE_HEADER);
bufferedWriter.newLine();
// Increase the begin date 1 seconds until test end date.
int seconds = 0;
Calendar cal = Calendar.getInstance();
cal.setTime(beginDate);
for (int j = 0; j < convertedDifference; j++) {
for (Job currentJob : NEHCalculator.sequenceOrderListofJobs()) {
int times = (int) ((convertedDifference / currentJob.getInterval()) * testDevices());
for (int i = 0; i < currentJob.getNeededTestTime() * times; i++) {
cal.add(Calendar.SECOND, 1);
beginDate.getTime();
// write the test date
bufferedWriter.write(String.valueOf(cal.getTime()));
bufferedWriter.write(";");
bufferedWriter.write(String.valueOf(seconds));
bufferedWriter.write(";");
bufferedWriter.write(currentJob.getJobname());
bufferedWriter.write(";");
bufferedWriter.newLine();
}// end of currentjob loop
seconds++;
}// end first for loop
}
bufferedWriter.close();// Always close files.
} catch (IOException ex) {
System.out.println("Error writing to file '" + fileName);
}
}
First for loop for (int j = 0; j < convertedDifference; j++) : I restrict my program until test end date. If I enter 1 hour test time, i expected to see number 0 until 3599 seconds.
Second for loop for (Job currentJob : NEHCalculator.sequenceOrderListofJobs()): I want to test every devices in the list.
For third for loop for (int i = 0; i < currentJob.getNeededTestTime() * times; i++): I expected to test first job currentJob.getNeededTestTime() * times times.
For example I have 1 hour test time and interval of fist job is 15 min and it tests 2 devices and test needed time 2 seconds. So the output must be:
Mon Feb 22 12:59:59 CET 2016;0;WAF5-H;
Mon Feb 22 13:00:00 CET 2016;1;WAF5-H;
Mon Feb 22 13:00:01 CET 2016;2;WAF5-H;
Mon Feb 22 13:00:02 CET 2016;3;WAF5-H;
Mon Feb 22 13:00:03 CET 2016;4;WAF5-H;
Mon Feb 22 13:00:04 CET 2016;5;WAF5-H;
Mon Feb 22 13:00:05 CET 2016;6;WAF5-H;
Mon Feb 22 13:00:06 CET 2016;7;WAF5-H;
Mon Feb 22 13:00:07 CET 2016;8;WAF5-H;
Mon Feb 22 13:00:08 CET 2016;9;WAF5-H;
Mon Feb 22 13:00:09 CET 2016;10;WAF5-H;
Mon Feb 22 13:00:10 CET 2016;11;WAF5-H;
Mon Feb 22 13:00:11 CET 2016;12;WAF5-H;
Mon Feb 22 13:00:12 CET 2016;13;WAF5-H;
Mon Feb 22 13:00:13 CET 2016;14;WAF5-H;
Mon Feb 22 13:00:14 CET 2016;15;WAF5-H; then it will continue with second job until end of the job list.
However the output of my code is:
Mon Feb 22 12:59:59 CET 2016;0;WAF5-H;
Mon Feb 22 13:00:00 CET 2016;0;WAF5-H;
Mon Feb 22 13:00:01 CET 2016;0;WAF5-H;
Mon Feb 22 13:00:02 CET 2016;0;WAF5-H;
Mon Feb 22 13:00:03 CET 2016;0;WAF5-H;
Mon Feb 22 13:00:04 CET 2016;2;WAF5-H;
Mon Feb 22 13:00:05 CET 2016;2;WAF5-H;
Mon Feb 22 13:00:06 CET 2016;2;WAF5-H;
Mon Feb 22 13:00:07 CET 2016;2;WAF5-H;
Mon Feb 22 13:00:08 CET 2016;2;WAF5-H; until Mon Feb 22 17:55:08 CET 2016;7082;WAF5-H;
It is completely wrong and I spend really so soo much time but I failed with this task. Could someone please help me.
Best regards,
What about changing this code
bufferedWriter.write(String.valueOf(seconds));
for this one:
bufferedWriter.write(String.valueOf(cal.get(Calendar.SECOND)));
I think it might work

count number of certain value occurances in a string

I have a string which contains my mail details such as
GitHub Sat Jun 01 13:32:02 IST 2013
eBay Mon Jun 03 17:37:40 IST 2013
YouTube Tue Jun 04 00:18:50 IST 2013
YouTube Sat Jun 08 01:20:47 IST 2013
eBay Sat Jun 08 13:19:22 IST 2013
eBay Sat Jun 08 13:17:53 IST 2013
eBay Mon Jun 10 15:43:01 IST 2013
YouTube Mon Jun 10 15:47:02 IST 2013
eBay Wed Jun 12 11:10:15 IST 2013
eBay Wed Jun 12 19:25:50 IST 2013
eBay Thu Jun 13 17:22:14 IST 2013
eBay Thu Jun 13 18:09:18 IST 2013
Clark University Thu Jun 13 19:30:09 IST 2013
is there any way to get number of times eBay ,Youtube or anything has occured so that i can have a number of mails received from a particular person??
You can split the string using String tokenizer and match the value of first token.
If eBay is always going to be the first word then, you can use startsWith() method of String class.
try to use regular expressions with grouping of data.
This solution supposes two things:
names of days cannot appear in the first part;
each entry is separated by a newline:
[extra line to fix SO bug with list items and code extracts]
private static final Set<String> DAYS = new HashSet<String>(Arrays.asList(
"Mon ", "Tue ", "Wed ", "Thu ", "Fri ", "Sat ", "Sun "
));
public int nrMatches(final String mailList, final String sender)
{
int ret = 0;
int index;
for (final String line: mailList.split("\r?\n"))
for (final String day: DAYS) {
index = line.indexOf(day);
if (index == -1)
continue;
if (line.subString(0, index).trim().equals(sender))
ret++;
}
return ret;
}

Increment Time by one second in a loop

Here is a simple test: I am trying to increment current timestamp by 1 second in a loop. The output is not what I expect.
public class TimeTest {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
for (int i = 0; i < 10; i++) {
cal.add(Calendar.SECOND, i);
System.out.println("Updated = " + cal.getTime());
}
}
}
Instead of neat 1 second increments, I get increments from anywhere between 5 seconds to 1 second.
Updated = Mon May 13 15:12:45 PDT 2013
Updated = Mon May 13 15:12:46 PDT 2013
Updated = Mon May 13 15:12:48 PDT 2013
Updated = Mon May 13 15:12:51 PDT 2013
Updated = Mon May 13 15:12:55 PDT 2013
Updated = Mon May 13 15:13:00 PDT 2013
Updated = Mon May 13 15:13:06 PDT 2013
Updated = Mon May 13 15:13:13 PDT 2013
Updated = Mon May 13 15:13:21 PDT 2013
Updated = Mon May 13 15:13:30 PDT 2013
You want to add 1 instead of i on each for loop iteration.
cal.add(Calendar.SECOND, 1);
cal.add(Calendar.SECOND, 1);
Simply increment the calendar by 1 second instead of i seconds

Categories

Resources