JavaFX - Method for set LocalDateTime not working - java

I have a class called Sell which has a SimpleObjectProperty.
In the POJO, the getters and setters are the following:
private ObjectProperty<LocalDateTime> sellDate;
....
public LocalDateTime getSellDate() {
return sellDate.get();
}
public void setSellDate(LocalDateTime value) {
sellDate.set(value);
}
When creating a new instance of the Sell class, I use the method setSellDate():
....
Sell sell = new Sell();
//another gets and sets...
sell.setSellDate(LocalDateTime.now());
This line of code is giving me a NullPointerException.
What am I doing wrong?

Since sell clearly isn't null, sellDate must be the reference that is null. You show where you declare it with
private ObjectProperty<LocalDateTime> sellDate;
but you don't show any code that initializes it. You need something like
sellDate = new SimpleObjectProperty<>();
in the constructor.

Related

How to make code dynamic for similar kind of blocks

I am creating my web page with vaadin where I need to create same kind of blocks for different type for example need to show blocks having car details, so only car name would be different but the block design would be same with same label but different labels. I want to write generic code so that i can expand it for any car name, without adding it manually.
Attaching the code snippet which i am using where i am repeating my code for different type. Want to implement it dynamically.
private Grid<PresentableGenerateInputHeaders> winTSHeaderColumnsGrid;
private Grid<PresentableGenerateInputHeaders> fRHeaderColumnsGrid;
private ListDataProvider<PresentableGenerateInputHeaders> listDataProvider;
private List<PresentableGenerateInputHeaders> presentableGenerateInputHeaders = new ArrayList<>();
private void initWinTsGrid() {
listDataProvider = new ListDataProvider<>(presentableGenerateInputHeaders);
winTSHeaderColumnsGrid = new Grid<PresentableGenerateInputHeaders>(PresentableGenerateInputHeaders.class);
winTSHeaderColumnsGrid.setDataProvider(listDataProvider);
winTSHeaderColumnsGrid.setCaption(i18n.get("view.ruleDetails.general.csvHeaderColumns"));
winTSHeaderColumnsGrid.setStyleName("a-units");
winTSHeaderColumnsGrid.setWidth("450px");
winTSHeaderColumnsGrid.setItems(addGridValues(DataSource.WIN_TS, winTSHeaderColumnsGrid));
winTSHeaderColumnsGrid.getEditor().setEnabled(true);
winTSHeaderColumnsGrid.setColumnOrder("header", "count");
winTSHeaderColumnsGrid.sort("header");
winTSHeaderColumnsGrid.getEditor().addSaveListener((EditorSaveEvent<PresentableGenerateInputHeaders> event) -> {
event.getGrid().select(event.getBean());
selectedGapFillingCountWINTS.add(event.getBean());
});
}
private void initFRGrid() {
listDataProvider = new ListDataProvider<>(presentableGenerateInputHeaders);
fRHeaderColumnsGrid = new Grid<PresentableGenerateInputHeaders>(PresentableGenerateInputHeaders.class);
fRHeaderColumnsGrid.setDataProvider(listDataProvider);
fRHeaderColumnsGrid.setCaption(i18n.get("view.ruleDetails.general.csvHeaderColumns"));
fRHeaderColumnsGrid.setStyleName("a-units");
fRHeaderColumnsGrid.setWidth("450px");
fRHeaderColumnsGrid.setItems(addGridValues(DataSource.FR, fRHeaderColumnsGrid));
fRHeaderColumnsGrid.getEditor().setEnabled(true);
fRHeaderColumnsGrid.setColumnOrder("header", "count");
fRHeaderColumnsGrid.sort("header");
fRHeaderColumnsGrid.getEditor().addSaveListener((EditorSaveEvent<PresentableGenerateInputHeaders> event) -> {
event.getGrid().select(event.getBean());
selectedGapFillingCountFR.add(event.getBean());
});
}
You can change methods to be more generic by identifying all the parts you don't want to keep static, and moving those to be populated by method parameters instead. I.e. instead of
private void myMethod() {
grid.setCaption("myCaption");
}
you would write
private void myMethod(String caption) {
grid.setCaption(caption);
}
and then call it
myMethod("myCaption");
If you need to be outside of the whole class to be able to determine what the real values are, you can for example make the method public or pass on the necessary values in the class constructor.
public MyClass(String gridCaption) {
myMethod(gridCaption);
}
If there are a lot of values you need to set dynamically, you might consider using an object that contains all the necessary values instead.
public void myMethod(MyPojo pojo) {
grid.setCaption(pojo.getGridCaption());
}
In your example it looks like the generic values you want to pass are DataSource dataSource and whatever type of collection selectedGapFillingCountWINTS and selectedGapFillingCountFR happen to be, and the method should probably return the grid rather than set it directly to a class variable.

How to test private member objects without making a new object

I'm trying to write unit test against a class. I can't change the class, but I think it's possible to test using reflection. I just don't know how to do it. Here's the class:
public class MyClass extends AnotherClass implements TheInterface
{
private enum SomeTypes
{
SAMPLE01, SAMPLE02, SAMPLE03
}
private CircularList<SomeTypes> someTypesList;
Date date= new Date();
private SomeOtherClassProcessor01 someOtherClassProcessor01;
private SomeOtherClassProcessor02 someOtherClassProcessor02;
private SomeOtherClassProcessor03 someOtherClassProcessor03;
public Properties initialize (Properties properties) throws Exception
{
Properties propertiesToReturn = super.initialize(properties);
someTypesList = new CircularList<SomeTypes> (Arrays.asList(SomeTypes.values()));
someOtherClassProcessor01 = new SomeOtherClassProcessor01();
someOtherClassProcessor02 = new SomeOtherClassProcessor02();
someOtherClassProcessor03 = new SomeOtherClassProcessor03();
return propertiesToReturn;
}
#Override
public void get(ImportedClass someParams) throws Exception
{
SomeTypes types = someTypesList.getFirstAndRotate();
switch(types)
{
case SAMPLE01:
someOtherClassProcessor01.doSomething(someParams, date);
break;
case SAMPLE02:
someOtherClassProcessor02.doSomething(someParams, date);
break;
case SAMPLE03:
someOtherClassProcessor03.doSomething(someParams, date);
break;
default:
throw new IllegalArgumentException("This " + types + " was not implemented.");
}
}
}
For my test this is what I have so far... not sure how to actually do it.
#RunWith(PowerMockRunner.class)
#PrepareForTest(MyClass.class)
public class TestingMyClass
{
MyClass mockMyClass;
SomeOtherClassProcessor01 someOtherClassProcessor01;
SomeOtherClassProcessor02 someOtherClassProcessor02;
SomeOtherClassProcessor03 someOtherClassProcessor03;
Date date;
#Before
public void initialize () throws Exception
{
mockMyClass = spy(new MyClass());
mockSomeOtherClassProcessor01 = mock(SomeOtherClassProcessor01.class);
mockSomeOtherClassProcessor02 = mock(SomeOtherClassProcessor02.class);
mockSomeOtherClassProcessor03 = mock(SomeOtherClassProcessor03.class);
}
#Test
public void testingGet() throws Exception
{
date = new Date();
//this is where I'm stuck
Whitebox.setInternalState(mockMyClass, "someOtherClassProcessor01", mockSomeOtherClassProcessor01);
}
}
Would it be possible to use whitebox for this? I need to make sure that there's a call inside the getter for those objects. Should I try something like when(someOtherClassProcessor01.doSomething(any(), date)).thenReturn(true)? Please let me know if you need more details.
edit: is even possible to mock private enum SomeTypes?
One option is to substitute your own (mocked) implementations of SomeOtherClassProcessor into MyClass using reflection:
MyClass myClass = new MyClass();
SomeOtherProcessor01 mockProcessor01 = mock(SomeOtherProcessor01.class);
// reflection bit: find the field by its name
// handle NoSuchFieldException
Field someProcessorField = MyClass.getDeclaredField("someOtherProcessor01");
// the field is declared as private, so make it accessible in order to work with it
someProcessorField.setAccessible(true);
// now set your mocked processor into the field.
// First argument is the object to change; second argument - new value for the field
someProcessorField.set(myClass, mockProcessor01);
PS. Using PowerMock and/or reflection is surrender to bad design (as per Timothy :). You should not be depending on code you that isn't already well-tested, and if it is, you shouldn't try to test it again. Suppose your testing actually reveals a bug - how would you fix it if you don't control the code? Suppose Java 11 becomes a thing and prohibits your use of reflection. Suppose the code you're testing changes and the fields get renamed - with reflection, you don't have compile-time safety... List of potential issues goes on

Pass array with a string and int to another class

I am new to Java and I have failed to find anything about this case.
I am basically trying to pass this array called vakken to a new class called Vak,
Vak expects to receive a String and a int.
Vak[] vakken = new Vak[1];
vakken[0] = new Vak("Test",3);
Vak vak = new Vak(vakken[0]);
Whenever I try the code above I get this error.
Exception in thread "main" java.lang.UnsupportedOperationException: Not supported yet.
at ectsmonitor2.Vak.<init>(Vak.java:24)
at ectsmonitor2.ECTSmonitor2.main(ECTSmonitor2.java:27)
Java Result: 1
Vak.class
public class Vak {
public String naam;
public int teVerdienenEcts;
public Vak(String vakNaam, int vakTeVerdienenEcts){
naam = vakNaam;
teVerdienenEcts = vakTeVerdienenEcts;
}
}
You haven't actually coded your constructor that takes a Vak yet, you made it throw UnsupportedOperationException. Put some code in the constructor e.g.
public Vak(Vak v) {
this(v.naam, v.teVerdienenEcts);
}
This line wont work for sure
Vak vak = new Vak(vakken[0]);//IDE will display error message here
Because you have no such constructor for this.
Create a new constructor that takes an object of its own type.
Similar to this:
public Vak(Vak anObject){
//do stuffs here
}
These type of constructors are called copy constructors
And generally you won't want your attributes to be public. Make them private.

Java exception crshes play framework

I have following controller:
public static Result overview() {
class Earning {
public int ammount;
public String description;
}
Earning[] earnings = new Earning[5];
earnings[0].ammount = 5;
return ok(overview.render(earnings));
}
I didn't created corresponding object in array as a result in Java I should get: java.lang.NullPointerException
But instead of showing this error Play framework crashes.
Any ideas how not to crash the framework and see the error in first place?
Add:
earnings[0] = new Earning();
before:
earnings[0].ammount = 5;
This way, earnings[0] will hold an Earning object and you would be able to access its ammount field.
Don't declare the Earning class inside the overview method.
It's creating a visibility issue because this class should only be accessible in the method body, but your "leaking" it by passing it to a view.

Attribute modification within a class

I have the method getPlan and I try to modify an object (attribute in my class)
class XYZ
/**
* Plan.
*/
private Plan plan;
#Override
public final Plan getPlan() {
subjects.addAll(plan.getSubjects());
...
return new Plan("1", subjects.size(), subjects);
}
#Override
public final Graph createGraph() {
Plan fPlan = getPlan();
...
return graph;
}
In the second method createGraph, I try to get the modified object (fPlan), but it's in the initial state (Plan plan). I hope you understand the situation.
Thanks in advance!
Either your method should not return a Plan, because Plan plan is an instance variable already. Plus you don't instantiate Plan plan anyway, so I guess you have to pick one of below pieces of code:
First piece: we make Plan plan an instance variable, and edit, modify and use that and only that. That means in this class, we don't have to return an Plans, as we have access to Plan plan in this instance of xyz.
class XYZ
private Plan plan;
#Override
public final void instantiatePlan() {
subjects.addAll(plan.getSubjects());
...
plan = new Plan("1", subjects.size(), subjects);
}
#Override
public final Graph createGraph() {
plan = instantiatePlan();
...
return graph;
}
second option: we remove the instance variable Plan plan, and in createGraph(), we call getPlan() with returns a Plan which we can modify and edit there. According to what I guess your context is, I'd go for the first option though.
class XYZ
#Override
public final Plan getPlan() {
subjects.addAll(plan.getSubjects());
...
return new Plan("1", subjects.size(), subjects);
}
#Override
public final Graph createGraph() {
Plan fPlan = getPlan();
...
//edit fPlan here.
return graph;
}
EDIT: Seeing your comment, I understand even less of your problem. First of all, in getPlan() you call getSubjects() on Plan plan, but it's not even instantiated, so it'll throw an NPE immediately. Second: let a method do what the name tells you: thus, getPlan() should just be return plan;, no more, no less, no editing, modifying in that method. I'd suggest making a constructor of class XYZ with params Plan plan:
public XYZ(Plan mPlan) {
this.plan = mPlan;
}
Or initializing it in the constructor:
public XYZ(ArrayList<Subject> subjects) {
this.plan = new Plan("1", subjects.size(), subjects);
}
Please tell where you want plan to be what.

Categories