Right now I write the function to get the number of working days myself. Instead of course it is much better to make use of Spring data and let the database make the calculation.
So how could I write the second function in Spring data.
It should be something like. Count by Date Distinct group by date from WorkingDay . A workingDayObject can occur more than once per day if somebody worked on different projects . That's way I use a hashset in my function to get just the days.
private double calculateOvertimeHours(WorkingMonth month)
{
double workedHours = Util.convertTimeToDoubleDecimal(month.getWorkedHours());
//Here I use a Spring data method as you can see
List<WorkingDay> lstWorkingDays = workingDayDao.findByWorkingMonthOrderByDateAsc(month);
return workedHours - calcNumberWorkDays(lstWorkingDays) * 8;
}
private int calcNumberWorkDays(List<WorkingDay> lstWorkingDays)
{
Set<Integer> hashSetDays = new HashSet<Integer>();
Calendar cal = Calendar.getInstance();
for(WorkingDay workingDay : lstWorkingDays)
{
cal.setTime(workingDay.getDate());
hashSetDays.add(cal.get(Calendar.DAY_OF_MONTH));
}
return hashSetDays.size();
}
Related
I want to insert Print code after every java code.
For example:
public void myMethod() {
Integer i = 0;
Long l = 0L;
Date date = new Date();
}
to:
public void myMethod() {
Integer i = 0;
System.out.println("test");
Long l = 0L;
System.out.println("test");
Date date = new Date();
System.out.println("test");
}
how should I do?Can you help me?
One way to a solution in the compiler
1 parse your code:
Best way to parse Java in Java
2 insert automatically code:
use JET for example
https://eclipse.org/articles/Article-JET2/jet_tutorial2.html
SECOND SOLUTION
create and put some annotation (by hand)
RUNTIME SOLUTION
you have to investigate bytecode.
Some links:
http://web.cs.ucla.edu/~msb/cs239-tutorial/
see the chapter: Generating Call Traces
And posts around this tag:
https://stackoverflow.com/questions/tagged/java-bytecode-asm
I have a JobClass wherein I am calling another class named as MainClass. The quartz trigger schedule to run the Main class via JobClass every 5 minutes. Now in the main class I have to collect the current date time something like below:-
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd/hh/mm/ss");
Calendar calendar = Calendar.getInstance();
String CurrentDateTime = dateFormat.format(calendar.getTime());
public String[] splitMe = CurrentDateTime.split("/");
public String year = splitMe[0];
public String month = splitMe[1];
public String day = splitMe[2];
public String hour = splitMe[3];
public String minute = splitMe[4];
public String second = splitMe[5];
String FilePrefix = year.concat(month).concat(day).concat("_").concat(hour).concat(minute).concat(second);
String FilePrefix4ControlFile = year.concat(month).concat(day).concat(" ").concat(hour).concat(minute).concat(second);
String EarliestTime = year.concat("-").concat(month).concat("-").concat(String.valueOf(Integer.parseInt(day) - 1));
String LatestTime = year.concat("-").concat(month).concat("-").concat(day);
This way I can get all my date time individual variable to create some strings with different combinations. Every single job runs I need to have a unique set of values however whatever number of times these variables are called within one job run then the values should be same.
Now I tried doing it using Static variables which kind of solved one problem of having same values during 1 run. However as the static variables are created on class initialisation ( main class) then they will always have same value unless the class is reloaded which I don't want to do , indeed not that easily possible in java.
I am sure I am doing some silly mistake, any pointers on this will be helpful.
PS: I just started Java by my own recently.
Thanks guys!
RJay
Is this correct?
ArrayList<Timestamp> timeStampList = new ArrayList<Timestamp>();
timeStampList.add(0, new Timestamp(System.currentTimeMillis()));
Thread.sleep(600);
timeStampList.add(1, new Timestamp(System.currentTimeMillis()));
Collections.sort(timeStampList);
Timestamp tempStamp = timeStampList.get(0);
for (Timestamp startstamp : timeStampList)
{
if (tempStamp != startstamp)
{
long diffTime = startstamp.getTime() - tempStamp.getTime();
diffDays = diffTime / (1000 * 60 * 60);
if(diffDays > 24)
{
System.out.println(diffDays / 24 +"Day" + " "+diffDays % 24 + "hours");
}
tempStamp = startstamp;
}
}
I am NOT sure how I can find the oldest timestamp in the array list. Any advice or direct answer is appreciated. Thanks a lot. This current code I think only compares.
EDIT: So assume I do not use Collection.sort in this context, I know I did apply that when I posted, but lets assume I want to know how to compare and find the oldest timestamp of all in the arrayList via a for-loop.
If, based on your post, you didn't want to sort your data, but instead wanted to just iterate through your entire collection of Timestamp objects and compare that way, you could use the Timestamp's after() method, which establishes whether a Timestamp occurs after the Timestamp provided as the argument of the function.
public Timestamp getOldestTimeStamp(ArrayList<Timestamp> timeStampList)
{
if (timeStampList != null || timeStampList.length() == 0)
{
return null;
}
Timestamp oldestTimestamp = timeStampList.get(0);
for (int i = 1; i < timeStampList.length(); i++)
{
if (oldestTimeStamp.after(timeStampList.get(i))
{
oldestTimeStamp = timeStampList.get(i);
}
}
// oldestTimeStamp is now the oldest Timestamp in the ArrayList
return oldestTimeStamp;
}
I could've sworn I included this in my first edit, but it looks like it didn't take. Everyone in the comments is correct in their wish for you to use the built-in features of the language instead of rolling your own. In this case, you would be far better suited learning to use simple language features like Collections.sort() and Collections.min(), which will invariably be as efficient and typically more so than the kind of code you or I will write, and significantly more succinct than a 12-line method like the one above.
I have this method to test :
public static Date getDateSinceUTC(CstOrderBean orderBean) {
int year = orderBean.getDeadLineYear();
int month = orderBean.getDeadLineMonth();
int day = orderBean.getDeadLineDay();
int hour = orderBean.getDeadLineHour();
int minute = orderBean.getDeadLineMinute();
String ap = orderBean.getDeadLineAmPm() == 1 ? "PM" : "AM";
//TODO AM=0, PM=1 comes from html form
SimpleDateFormat df = new SimpleDateFormat("yyyy:MM:dd:hh:mm:aa");
String stringDate = stringifyIntegers(":", year, month, day, hour, minute);
stringDate = stringDate.concat(ap);
Date date;
try {
date = df.parse(stringDate);
} catch (ParseException e) {
throw new Error("Parsing date from html form failed", e);
}
return date;
}
Where CstOrderBean needs to be mocked by Mockito because it is not a POJO (some static initializations etc. - from source code generator). But I need to run the method xxx times, hence set the mocks with many data combinations
I could use TestNG's #DataProvider to do that. But I'm not sure how to do that, I guess that :
when(ob.getDeadLineYear()).thenReturn(1, 2, 3);
....
in loop is a bad idea, isn't it ? Is the correct way of doing this to create xx mocks and initialize them like that ?
Each test should get their own mock that preferably does not have variable data. If you use several different return values from the same mock object then the testing has to be white-box testing as the test is coupled with the number of calls to a mocked method instead of the result of the method under test.
That said, you are able to define a set of return values with calling thenReturn repeatedly or by defining the return values as varargs
when(ob.getDeadLineYear()).thenReturn(someValue, anotherValue, ..., ultimateValue);
This might be cleaner as you should probably control the values that the mock returns anyway.
How you mock depends on what you would like to test. Looping on the deadline year might not do the job you want it to.
One test for seeing if a leap year works might be something like:
when(ob.getDeadLineYear()).thenReturn(2000);
when(ob.getDeadLineMonth()).thenReturn(2);
when(ob.getDeadLineDay()).thenReturn(29);
when(ob.getDeadLineHour()).thenReturn(12);
when(ob.getDeadLineMinute()).thenReturn(0);
when(ob.getDeadDeadLineAmPm()).thenReturn(1);
assertTrue("Got unexpected date", getDateSinceUTC(ob).toString().startsWith("2000-02-29 12:00:00"));
(Warning: above codes was typed in by hand). Mix, match, and repeat for other dates that you need to test to verify that getDateSinceUTC is working. You might want a separate test method to check invalid dates, like 2/30/2012 (and expect a throw). You might want to check invalid times like 23:61. You might want to check valid dates, like your birthdate.
Instead of a loop on the year, please look at "normal" cases, borderline cases, and error cases. This is the better practice for unit testing.
I'm glancing through parts of the official db4o tutorial, and I'm trying to make a modification to the code they give you for running native queries:
//the original
List<Pilot> pilots = db.query(new Predicate<Pilot>() {
public boolean match(Pilot pilot) {
return pilot.getPoints() == 100;
}
});
//modified
List<Pilot> pilots = db.query(new Predicate<Pilot>() {
public boolean match(Pilot pilot) {
return pilot.getGames() >= 100;
}
});
I've added this to their Pilot class:
//in declarations
private ArrayList<String> games;
//modified constructors
public Pilot() {
this.name=null;
this.points=0;
}
public Pilot(String name,int points) {
this.name=name;
this.points=points;
this.games = new ArrayList<String>();
int numGames = (int) (Math.random() * 1000 + 1);
for(int i=0;i<numGames;i++) {
this.games.add(name=" vs Computer");
}
}
//new method
public int getGames() {
return games.size();
}
I've already populated a database with 500 objects using the second constructor, and all the data in the db looks correct with the OME eclipse addon. I've tested getGames() and it works as expected.
My problem is that when I run the modified query, it returns all the objects in the db and I don't understand why. I've tried changing the query to include a more standard if true, else false structure and changing the query to include requiring a certain amount of points to no avail. Whatever I do, it seems it always evaluates (pilot.getGames() >= 100) to be true.
Can anyone help me as to understand why?
I think you've found a bug. db4o tries to translate the native-queries into a soda-query. This avoid instantiating to objects to perform queries. Now here this translation somehow does not work!
When you turn the optimization off it works. You can do this via configuration:
EmbeddedConfiguration cfg = Db4oEmbedded.newConfiguration();
cfg.common().optimizeNativeQueries(false);
ObjectContainer db = Db4oEmbedded.openFile(cfg,DB_FILE)
However I don't recommend this because then all queries will run slowly. I've found an easy workaround. Change the declaration of the games-field to List<String>. (And other, future List-fields). Like this:
class Pilot {
private List<String> games;
// rest
}
This will 'deoptimize' a native query as soon as you access the size() or other methods, hence avoids this bug.
Now a 'deoptimized' query can run quite slow. So if you have lots of objects and the performance is unacceptable I would do this for this query: Create an addional field which stores the current size of the list. Then you use this additional size-field for this kind of query. Additionally you can then index the size-field.
I've reported this as a bug: