Read Anylogic schedule exceptions from database table - java

How can I read a list of exception dates for a schedule from an Excel file without having to adopt each date from the file separately? I am trying to set up a shift-plan which takes into account holidays, etc. over the next 5 years. For this I have created an Excel table containing a list of holiday dates, which I would now like to use in my AnyLogic simulation. I tried the exceptions section of my schedule object, but didn't find a way to connect this section to my excel file. The only option I am getting here is to manually enter each date... Since this would be extremely tedious, I am looking for a workaround (Java Code?). Can someone help?

Suppose you have a scheduled object of type integer and a database table full of exception dates that you want the integer value of the schedule to be 0 for the entire day.
You can then programmatically add exceptions to your scheduling with the following code
List<Tuple> rows = selectFrom(db_table).list();
for (Tuple row : rows) {
Date exceptionDate = row.get( db_table.db_column );
schedule.addException(exceptionDate.getYear(), exceptionDate.getMonth(), exceptionDate.getDay(), exceptionDate.getHours(), exceptionDate.getMinutes(), exceptionDate.getSeconds(),
exceptionDate.getYear(), exceptionDate.getMonth(), exceptionDate.getDay()+1, exceptionDate.getHours(), exceptionDate.getMinutes(), exceptionDate.getSeconds(),
0, false);
}
The format for adding exceptions is a bit cumbersome but it is:
schedule.addException(startYear, startMonth, startDay, startHour, startMinute, startSecond, endYear, endMonth, endDay, endHour, endMinute, endSecond, value, annually);
The value object is the value of your schedule type

True, there is no build-in way for this. You need to code your schedule. This allows adding exceptions programmatically, see https://anylogic.help/anylogic/data/schedule.html#creating-and-initializing-schedule-from-code-on-model-startup
Specifically:

Related

How to delete from database with LIKE operator and context variable MySQL in Talend

I have a database that has the date as String and I have to delete the rows that have the same data in the csv file as in the database. More exactly, my dates look like this 2018-03-31T23:30:24+00:00. I want that when it gets a date like this, to delete from database where data LIKE %2018-03-31%, so it will delete all the records from that day, even if the time is not the same.
I have a job where tFileInputDelimited is connected with a tSortRow and then to tFlowToIterate. After that, I have a tJava where I extract the date and then a tMysqlInput where the query has the where clause like this: WHERE purchase_date LIKE '%"+context.date+"%' . Then, with a run if connection, I have tMysqlRow in which I have the delete statement with the same where clause. After that, of course, I have the tMysqlCommit.
The context.date is made like this:
context.dataaa=(String)globalMap.get("row6.purchase_date");
context.month=context.dataaa.substring(5,7);
context.year=context.dataaa.substring(0,4);
context.day=context.dataaa.substring(8,10);
context.date=context.year+"-"+context.month+"-"+context.day;
The problem is that, it doesn't delete from database. I want it to go row by row and delete all my records that have the same day in the csv and database.
The problem was from an if statement that compared the full date separately, so I had to compare only the day not day,year and month.
In Talend, you can define the pattern of a Date column to some usage.
Here, I have a tFileInputDelimited with a column date :
Column: date
Type : Date
pattern : "yyyy-MM-dd'T'hh:mm:ss"
That let me read a file with a value like 2018-03-31T23:30:24 because here, the pattern is used to "parse" the String from the file into a Date. Now if we add a LogRow and update the schema of this component, we can define a different pattern to format the Date
Column: date
Type : Date
pattern : "yyyy-MM-dd"
Input : 2018-03-31T23:30:24
Output : 2018-03-31
Know, if you don't want to play with the Schema, you can convert/format a date into a String with TalendDate.formatDate("yyyy-MM-dd", row1.date)

Calculate difference between 2 times in MongoDB

I have a field called Last Modified At with value like '2016/04/12 20:24:18'. It is not an ISO Date but a normal String value stored via a java process in MongoDb.
I am trying to write a shell script to calculate the difference between '2016/04/12 20:24:18' and say '2016/04/12 16:24:18'. The difference could be either in days or hours or mins or secs. I tried couple of things including converting to ISO dates but it doesnt work out. Is there an easy way to find out like Oracle.
Any help would be appreciated?
Thanks,
Ram
I'm not exactly sure how you plan on running the shell script, but it is possible in the mongo shell to parse dates (using Javascript) and calculate time between two dates as you have asked. Assume we have a document in the things database as follows:
{
"_id" : ObjectId("570f1e528163383227ace761"),
"lastModifiedAt" : "2016/04/12 20:24:18"
}
We can run the following script to get the difference between the lastModifiedDate of a document and a hard-coded date, such as 2016/04/12 16:24:18:
db.things.find({}).forEach(function(thing) {
var date1 = new Date(thing.lastModifiedAt);
var date2 = new Date('2016/04/12 16:24:18');
var dateDiff = date1.getTime() - date2.getTime();
printjson({_id:thing._id,lastModifiedAt:thing.lastModifiedAt,dateDiff:dateDiff});
});
This results in:
{
"_id" : ObjectId("570f1e528163383227ace761"),
"lastModifiedAt" : "2016/04/12 20:24:18",
"dateDiff" : 14400000
}
where dateDiff is milliseconds and 14400000 milliseconds = 4 hours.
If you provide more information on how you plan on making this call, and where the second date is coming from I would be happy to expand upon this answer.

Elasticsearch aggregation query not giving expected output

I am trying to do aggregation on documents which contains datetime and CPU time and server name. I want to find the avg CPU time on latest date. I have the following query which partially works it gives me the avg CPU time but not on latest date it just randomly chooses date.
client.prepareSearch("myindex").
setTypes("mytype").
setQuery(
QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
FilterBuilders.andFilter(FilterBuilders.termFilter("server","x")))).
addAggregation(AggregationBuilders.avg("cpu_agg")
.field("dt_time").field("cpu_time"))
.get()
Please guide. I want avg cpu time on latest date say today's date. I am new to ElasticSearch. Thanks in advance.
client.prepareSearch("myindex").
setTypes("mytype").
setQuery(
QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
FilterBuilders.andFilter(FilterBuilders.termFilter("server","x")))).
addAggregation(AggregationBuilders.avg("cpu_agg")
.field("dt_time").field("cpu_time"))
.get()
look at the portion (where field is set to dt_time at first and replaced to cpu_time), which means aggregation is build for cpu_time,
If you want to get cpu time in today's date then one way is use date filter ,
FilterBuilders.andFilter(FilterBuilders.termFilter("server","x"),FilterBuilders.rangeFilter("dt_time").to(to).from(from))))
For your problem, from = to = today_date (or last date)
so finally,
client.prepareSearch("myindex").
setTypes("mytype").
setQuery(
QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
FilterBuilders.andFilter(FilterBuilders.termFilter("server", "x"), FilterBuilders.rangeFilter("dt_time").to("to").from("from")))).
addAggregation(AggregationBuilders.avg("cpu_agg")
.field("cpu_time"))
.get();

HIBERNATE : Don't want to save milliseconds

I got a little problem and I didn't find a suitable solution on the net because my question is a bit tricky for search engine.
There's a lot of topics about hibernate saving milliseconds. But my problem is something else.
In fact, I got a database, which save my date like this :
2014-03-20 10:58:09
I used Hibernate to get back my date, and display it on a web page. But Hibernate retrieve more than that : it also retrieve a 0 milliseconds, like this :
2014-03-20 10:58:09.0
Many people seems to have problem with this, but in my case, I DON'T WANT this information, I want Hibernate to retrieve the date without this .0 !
Thanks for your help !
EDIT AND SOLUTION :
Ok so I made it by using a little hack.
In my specific object using by Hibernate, I had this method :
public Date getModificationDate() {
return modificationDate;
}
I just simply create an other method :
private static final SimpleDateFormat FMT = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public String getModificationDateLabel() {
if (modificationDate != null) {
return FMT.format(modificationDate);
}
return null;
}
So, when I display in my webpage (I use Velocity Template), I just run through my list of object an display the label :
#foreach( $object in $objects)
$!{object.modificationDateLabel}
#end
The SimpleDateFormat allow me to remove the .0, and by creating a new method, I don't disturb the behavior of getting a Date with Hibernate.
Thanks for your time !
I don't see a problem with the date returned as "2014-03-20 10:58:09.0" is equal to "2014-03-20 10:58:09". Can you provide specific scenario where this can result in issue?
Or use SimpleDateFormat("yyyy-MM-dd HH:mm:ss") then parse your date in this format before using the date.

Database timestamps not matching

I have an action in struts2 that will query the database for an object and then copy it with a few changes. Then, it needs to retrieve the new objectID from the copy and create a file called objectID.txt.
Here is relevant the code:
Action Class:
ObjectVO objectVOcopy = objectService.searchObjects(objectId);
//Set the ID to 0 so a new row is added, instead of the current one being updated
objectVOcopy.setObjectId(0);
Date today = new Date();
Timestamp currentTime = new Timestamp(today.getTime());
objectVOcopy.setTimeStamp(currentTime);
//Add copy to database
objectService.addObject(objectVOcopy);
//Get the copy object's ID from the database
int newObjectId = objectService.findObjectId(currentTime);
File inboxFile = new File(parentDirectory.getParent()+"\\folder1\\folder2\\"+newObjectId+".txt");
ObjectDAO
//Retrieve identifying ID of copy object from database
List<ObjectVO> object = getHibernateTemplate().find("from ObjectVO where timeStamp = ?", currentTime);
return object.get(0).getObjectId();
The problem is that more often than not, the ObjectDAO search method will not return anything. When debugging I've noticed that the Timestamp currentTime passed to it is usually about 1-2ms off the value in the database. I have worked around this bug changing the hibernate query to search for objects with a timestamp within 3ms of the one passed, but I'm not sure where this discrepancy is coming from. I'm not recalculating the currentTime; I'm using the same one to retrieve from the database as I am to write to the database. I'm also worried that when I deploy this to another server the discrepancy might be greater. Other than the objectID, this is the only unique identifier so I need to use it to get the copy object.
Does anyone know why this is occuring and is there a better work around than just searching through a range? I'm using Microsoft SQL Server 2008 R2 btw.
Thanks.
Precision in SQL Server's DATETIME data type does not precisely match what you can generate in other languages. SQL Server rounds to the nearest 0.003 - this is why you can say:
DECLARE #d DATETIME = '20120821 23:59:59.997';
SELECT #d;
Result:
2012-08-21 23:59:59.997
Then try:
DECLARE #d DATETIME = '20120821 23:59:59.999';
SELECT #d;
Result:
2012-08-22 00:00:00.000
Since you are using SQL Server 2008 R2, you should make sure to use the DATETIME2 data type instead of DATETIME.
That said, #RedFilter makes a good point - why are you relying on the time stamp when you can use the generated ID instead?
This feels wrong.
Other than the objectID, this is the only unique identifier
Databases have the concept of a unique identifier for a reason. You should really use that to retrieve an instance of your object.
You can use the get method on the Hibernate session and take advantage of the session and second level caches as well.
With your approach you execute a query everytime you retrieve your object.

Categories

Resources