I have combed through SO, and have found many questions on the topic of my problem but do not answer it.
I am setting up an MVC, I have set up things correctly to best of my knowledge but I cannot get the Controller to show in my view. I am working on an assignment that essentially is a program for a Video Rental Store.
First, In a class called RentalStoreGUI, I set up my panels and everything looks good when I run.
RentalStoreEngine model = new RentalStoreEngine();
JList<DVD> list = new JList<DVD>();
list.setModel(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setVisible(true);
list.setSelectedIndex(0);
jScrollPane = new JScrollPane(list);
add(jScrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
As you can see I set my model for the list based on another class called RentalStoreEngine() and it implements AbstractListModel. The Abstract List model is functioning when I do class specific testing and all of the necessary methods are implemented. Here is an example of my add method from that class:
public void add(DVD d){
if (d != null){
rentals.add(d);//rentals is an arrayList<DVD> instantiated earlier
fireIntervalAdded(this, rentals.size() - 1, rentals.size() - 1);
}
}
Here is the actionPerformed method, it runs DVD_Dialog which simply gets some input from the user and creates a new DVD object from that.
public void actionPerformed(ActionEvent event) {
if(event.getSource() == rentDVD){
DVD_Dialog = new RentDVDDialog(this, null);
DVD_Dialog.clear();
DVD_Dialog.setVisible(true);
dvd = new DVD(DVD_Dialog.getTitleText(),DVD_Dialog.getRenterText(),
DVD_Dialog.getRentedOnText(), DVD_Dialog.getDueBackText());
if(DVD_Dialog.closeStatus() == true){
model.add(dvd);
}
}
Eclipse gives me no errors, until I run it. I then receive a nullPointerException at the line model.add(dvd); Based on all my research the list.setModel(model) and the fireIntervalAdded method line should update the Jlist on its own. But it does not. And as I said, class specific testing for both the GUI and the Model are producing the desired results, but when it comes to integrating them I am at a loss.
Related
I've created a test plugin as a science project to try and determine if 2 of the same event are called at the same time, which will be executed first.
public class TestPlugin extends JavaPlugin implements Listener {
public void onEnable() {
Bukkit.getPluginManager().registerEvents(this, this);
}
#EventHandler(priority = EventPriority.HIGHEST)
public void event1(PlayerInteractEvent e) {
System.out.println("event 1");
}
#EventHandler(priority = EventPriority.HIGHEST)
public void event2(PlayerInteractEvent e) {
System.out.println("event 2");
}
}
the output that the plugin produced are
[17:01:51 INFO]: event 2
[17:01:51 INFO]: event 1
if event1 is listed first in the class file, why is it that event2 is fired first?
This is very hard to determine. Since registerEvents leads to the function createRegisteredListeners of https://github.com/Bukkit/Bukkit/blob/master/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java
In there they use a HashSet to store the Methods of your Listener-class. So it is the pseudo random hash they give each method to store it that determines which event gets registered first.
I'm not sure but I guess that each and every time you register the events it's kind of random which gets registered first. This is why you should use different eventPriorities in order to determine which is called first.
If you really want to get deeper you have to tear apart the function createRegisteredListeners of the github-link I posted earlier in this reply. But I guess it woll never be totally certain because of the HashSet used in line 235 of the JavaPluginLoader.java:
methods = new HashSet<Method>(publicMethods.length, Float.MAX_VALUE);
As Methods are added to the set it never is certain in which position in the RAM they end up.
I hope I could help you with this post even though it doesn't really answer your original question.
After reading about the remote shell in the Spring Boot documentation I started playing around with it. I implemented a new Command that produces a Stream of one of my database entities called company.
This works fine. So I want to output my stream of companies in the console. This is done by calling toString() by default. While this seams reasonable there is also a way to get nicer results by using a Renderer.
Implementing one should be straight forward as I can delegate most of the work to one of the already existing ones. I use MapRenderer.
class CompanyRenderer extends Renderer<Company> {
private final mapRenderer = new MapRenderer()
#Override Class<Company> getType() { Company }
#Override LineRenderer renderer(Iterator<Company> stream) {
def list = []
stream.forEachRemaining({
list.add([id: it.id, name: it.name])
})
return mapRenderer.renderer(list.iterator())
}
}
As you can see I just take some fields from my entity put them into a Mapand then delegate to a instance of MapRenderer to do the real work.
TL;DR
Only problem is: How do I register my Renderer with CRaSH?
Links
Spring Boot documentation http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-remote-shell.html
CRaSH documentation (not helping) http://www.crashub.org/1.3/reference.html#_renderers
I get this error when opening one specific form. The rest is working fine and I have no clue why this one isn't.
Error: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.
I get the error at _oDBConnection when I try to save. When I watch _oDBConnection while running through the code, it does not exist. Even when I open the main-window it does not exist. So this form is where the DataContext is built for the very first time.
Every class inherits from clsBase where the DataContext is built.
My collegue is the professional one who built it all. I am just expanding and using it (learned it by doing it). But now I'm stuck and he is on holiday. So keep it simple :-)
What can it be?
clsPermanency
namespace Reservation
{
class clsPermanency : clsBase
{
private tblPermanency _oPermanency;
public tblPermanency PermanencyData
{
get { return _oPermanency; }
set { _oPermanency = value; }
}
public clsPermanency()
: base()
{
_oPermanency = new tblPermanency();
}
public clsPermanency(int iID)
: this()
{
_oPermanency = (from oPermanencyData in _oDBConnection.tblPermanencies
where oPermanencyData.ID == iID
select oPermanencyData).First();
if (_oPermanency == null)
throw new Exception("Permanentie niet gevonden");
}
public void save()
{
if (_oPermanency.ID == 0)
{
_oDBConnection.tblPermanencies.InsertOnSubmit(_oPermanency);
}
_oDBConnection.SubmitChanges();
}
}
}
clsBase
public class clsBase
{
protected DBReservationDataContext _oDBConnection;
protected int _iID;
public int ID
{
get { return _iID; }
}
public DBReservationDataContext DBConnection
{
get { return _oDBConnection; }
}
public clsBase()
{
_oDBConnection = new DBReservationDataContext();
}
}
Not a direct answer, but this is really bad design, sorry.
Issues:
One context instance per class instance. Pretty incredible. How are you going to manage units of work and transactions? And what about memory consumption and performance?
Indirection: every entity instance (prefixed o) is wrapped in a cls class. What a hassle to make classes cooperate, if necessary, or to access their properties.
DRY: far from it. Does each clsBase derivative have the same methods as clsPermanency?
Constructors: you always have to call the base constructor. The constructor with int iID always causes a redundant new object to be created, which will certainly be a noticeable performance hit when dealing with larger numbers. A minor change in constructor logic may cause the sequence of constructor invocations to change. (Nested and inherited constructors are always tricky).
Exception handling: you need a try-catch everywhere where classes are created. (BTW: First() will throw its own exception if the record is not there).
Finally, not a real issue, but class and variable name prefixes are sooo 19xx.
What to do?
I don't think you can change your colleague's design in his absence. But I'd really talk to him about it in due time. Just study some linq-to-sql examples out there to pick up some regular patterns.
The exception indicates that somewhere between fetching the _oPermanency instance (in the Id-d constructor) and saving it a new _oDBConnection is created. The code as shown does not reveal how this could happen, but I assume there is more code than this. When you debug and check GetHashCode() of _oDBConnection instances you should be able to find where it happens.
I am trying to serialize my game data. In case the user presses the Windows button, everything should be saved. I know that we should override the OnExiting event in the game class. but am using the Game State Management , I want to serialize game data in my GamePlayScreen class. I did override the Serialize and DeSerialize methods, but they didnt work.
hers my code:
public override void Serialize(Stream stream)
{
gameState.HumanPlayer = HumanPlayer;
gameState.Player1 = AIPlayer1;
gameState.Player2 = AIPlayer2;
gameState.Player3 = AIPlayer3;
XmlSerializer serializer = new XmlSerializer(typeof(GameState));
serializer.Serialize(stream, gameState);
base.Serialize(stream);
}
public override void Deserialize(Stream stream)
{
XmlSerializer serializer = new XmlSerializer(typeof(GameState));
gameState = (GameState)serializer.Deserialize(stream);
if (gameState.HumanPlayer != null)
HumanPlayer = gameState.HumanPlayer;
if (gameState.Player1 != null)
AIPlayer1 = gameState.Player1;
if (gameState.Player2 != null)
AIPlayer2 = gameState.Player2;
if (gameState.Player3 != null)
AIPlayer3 = gameState.Player3;
base.Deserialize(stream);
}
I tried to create my own IsolatedStorageFile instead of the provided stream object, but it didnt work.
I tried to write the same code in the Load and Unload event. it works fine there, but in case of pressing the back button. i need to serialize if the user pressed the windows button or the search button.
It looks like you need to handle the OnDeactivated and OnActivated events. Just do the same thing as is done in the OnExiting event and the Constructor. I would have thought the sample would do this as proper handling of tombstone/rehydrate is such a big thing for WP7, however it seems it has been neglected. Note that OnActivated is NOT called when the app is launched and OnDeactivated is NOT called when the app is closed manually or exited using the Back button.
Note that Activated and Deactivated area also available as events on PhonApplicationServices.Current, along with Launching and Closing, which are ONLY called on actual open and exit situations.
EDIT
Ok, I take it back. OnDeactivated and OnActivated are not required. It seems that OnExiting is fired for both Deactivate and Exit scenarios. I downloaded the sample you linked (XNA4 WP7, not Mango version) and put this code into the GameplayScreen:
public override void Serialize(System.IO.Stream stream)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(string));
serializer.Serialize(stream, "Blah de blah blah");
base.Serialize(stream);
}
public override void Deserialize(System.IO.Stream stream)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(string));
string testStr = (string)serializer.Deserialize(stream);
base.Deserialize(stream);
}
A break point shows that the Deserialize method is being hit functioning correctly, so your problem must be in how you apply your loaded data, or perhaps you've edited other code that has broken it.
I've read a lot about mocking/stubbing/faking - and still hit my mental roadblocks.
I'm trying to adapt MVP (Model View Presenter) with a "fun" weight loss tracking system I'm building for my own Fatty McFatter-self. I'm trying to TDD & 'by the book' this but hit many mental blocks and stall out.
I am building my Presenter and mocking my Service & View at the moment. Here's my test: again note: service and view are mocked with Moq
[Test]
public void GetLog_WithExistingDate_ViewSetWithExistingLog()
{
WeightLogModel model = new WeightLogModel
{
EntryDate = DateTime.Now,
Waist = 42,
Weight = 242
};
service.Setup(x => x.GetLog(It.IsAny<DateTime>())).Returns(model);
presenter.Display(DateTime.Now);
IWeightLogView myView = view.Object;
Assert.AreEqual(model.Weight, myView.Weight);
}
and in my Presenter - this is my Display method:
public void Display(DateTime date)
{
var weightLog = service.GetLog(date);
if(weightLog == null) return;
View.EntryDate = weightLog.EntryDate;
View.Waist = weightLog.Waist;
View.Weight = weightLog.Weight;
}
Now - if I debug as Display is being called - I see the weightLog is filled with the correct info I've setup in the mock. But as it's suppose to set View.EntryDate, View.Waist, etc - the View values never change. They stay zero or 0001/1/1
Is there some way to make it work? Or is this just a bad test and I'm floundering in confusion?
Thanks to Phil for starting me in motion. Although I didn't want to explicitly set what I was going to return - I wanted the mock view to behave like my view. You can have the mocked setter behave as normal by calling SetupProperty --> view.SetupProperty(x => x.Weight) //in my case... here's the test that will now pass asserting the weight was set
[Test]
public void GetLog_WithExistingDate_ViewSetWithExistingLog()
{
WeightLogModel model = new WeightLogModel
{
EntryDate = DateTime.Now,
Waist = 42,
Weight = 242
};
service.Setup(x => x.GetLog(It.IsAny<DateTime>())).Returns(model);
// I ADDED THIS ONE LINE
view.SetupProperty(x => x.Weight);
presenter.Display(DateTime.Now);
IWeightLogView myView = view.Object;
Assert.AreEqual(model.Weight, myView.Weight);
}
You are not showing all your setup code here, nor the dependencies between classes.
However if you are indeed mocking the view called "myView", it's going to return what you have the mock set up to return, or defaults for each type if you haven't specified anything for it to return (which sounds like what is happening).
From your comment:
I am trying to setup the
service.GetLog(date) to return the
WeightLogModel I have in the test. My
thinking is that doing so - would make
that WeightLogModel available in my
presenter
So far that seems like it is working from your original question.
to assign to my mocked view - where
View.EntryDate = weightLog.EntryDate
.... in this case weightLog is what is
setup in the test.... I hope I'm clear
as to where my head is... I'm not
saying I'm right - this is what my
thinking is though.
Where are you going wrong is where you say "to assign to my mocked view". It's not clear from your code whether or not the View property is in fact your mocked view (because your code is incomplete).
Although, in this case, it actually doesn't matter. If the View property is in fact a mock, it will only return what you tell it to return--its properties are not going to behave like "normal" properties.
So the following will fail without explicit setup:
mockView.MyProperty = "hello";
Assert.AreEqual("hello", mock.MyProperty);