Connection management with ActiveJDBC - java

I am getting into ActiveJDBC at the moment, a very nice and useful framework, as far as I can tell. But I am having some problems with the JDBC-Connection management of it, as it attaches an opened connection to the current thread. That means, if I open the connection at the initialisation of my program, everything works fine; but if I instantiate a JFrame afterwards and try reading/wrtiting data from/to the database in an ActionListener for example, it will generate an error, since there is no connection attached to the dispatch thread.
How to solve this problem? I'd rather have just one connection, to which I can get access (via Base.connection()) all the time, instead of having one connection attached to each thread..
Thanks in advance

I would suggest that you implement action listener this way:
public class AJListenerAdapter implements ActionListener{
public void actionPerformed(ActionEvent e){
Base.open(...);
doPerform(ActionEvent e);
Base.close(...);
}
protected abstract doPerform(ActionEvent e);
}
then just subclass this adapter and implement the doPerform() method.
Additionally you might want to use connections from a pool. Here is an example
https://github.com/javalite/activejdbc/blob/master/activejdbc/src/test/java/org/javalite/activejdbc/C3P0PoolTest.java

Related

Java resource clean up before object destruction

I've the following problem and I know there are already a lot of questions but none of these give me really a satisfactorily answer! I wrote a lot of stuff in C++ and this language provide a destructor, Java doesn't because of the garbage collection.
A little introduction in my situation: I wrote a software which is accessing a local Sqlite3 database. I wrote a central singleton class for accessing this database. Multiple other classes access the DB through this wrapper class. Here is the pseudo-code of this wrapper class:
public class MyDbWrapper
{
private currentDbConnection;
public MyDbWrapper(dbPath)
{
// Open the database connection with given path
}
public readFromDb()
{
... // Uses the class member currentDbConnection
}
public writeToDb()
{
... // Uses the class member currentDbConnection
}
public closeDb()
{
...
}
}
Now my question is, how could I ensure that the database connection is closed before quitting the application? Yes I already implemented the AutoCloseable interface and yes I worked already a lot with try-with-resources, but because of the access by multiple classes this isn't really an option!
In C++ a destructor would solve this issue, but the possible "equivalent" in java the method finalize is deprecated!
So are there any other options or should I totally re-design my complete wrapper? If yes, how could I prevent performance issues because of a lot of read write access if I re-open the database every time?
Like Joker_vD already said, I solved this issue by using a try-with-resources statement in the main method of my program...
public static void main(String [] args)
{
try(MyDbWrapper wrapper = new MyDbWrapper())
{
// Execute other task with usage of the database wrapper
}
}
With this solution there is no need for a desturctor or the usage of the deprecated method finalize(), the database connection get closed if program ends...
Thanks again and credits to Joker_vD

Proper Vertx database etiquette

I'm fairly new to Vertx, And trying to find some realistic examples of database usage.
I have a Verticle that creates a shared database object (And a number of classes that handle routing, but I would like to use the shared database outside the main class, obviously I could pass the database object in other classes constructors, but I'm sure Vertx has some better way to do this.
public void start() {
...
this.postgreSQLClient = PostgreSQLClient.createShared(vertx, sqlClientConfig);
...
}
Does anyone have any Java Vertx examples with realistic implementations of a database?
Thank you in advance.
Use Dependency Injection. I have used Guice
Here's the example of it:
Main.java
//within main function where you have object of vertx
Guice.createInjector(new AppInjector(vertx));
AppInjector.java
//Create an Injector file and bind your injections
PostgreSQLClient postgreSQLClient = PostgreSQLClient.createShared(vertx, sqlClientConfig, "my-shared-client");
bind(PostgreSQLClient.class).annotatedWith(Names.named("DBClient")).toInstance(postgreSQLClient);
UserService.java
public class UserService {
#Inject
#Named("DBClient")
private PostgreSQLClient client;
}
You can find the source code here
Just specify a pool name:
if different clients are created using the same Vert.x instance and
specifying the same pool name, they will share the same data source.
So updating your example:
public void start() {
this.postgreSQLClient = PostgreSQLClient.createShared(vertx, sqlClientConfig, "my-shared-client");
}
Note that when doing this, the configuration provided in the first call will be used. Subsequent calls will simply return the existing client.

libgdx (Ashley Framework ECS) - What is the proper way of talking system to another system?

System to System
Currently I'm developing CharacterSystem, GunSystem, BulletSystem using ashley framework. My problem is I dont know if this is the proper way of talking system to other system.
My CharacterSystem method onProcessEntity when the character attack is triggered I used getEngine().getSystem(GunSystem.class).trigger(true) and inside the GunSystem I have a method the Generate entity of a Bullet. While the BulletSystem handles the freeing of bodies, when outside the camera.
sub-question What is the proper way of creating Bullet class with ECS framework?
I use the Ashley ECS quite a lot for games and in a recent project (https://github.com/basimkhajwal/LSD) I ran into a similar situation. My method probably isn't standard and it may have issues which would occur in a different project setup but using an event queue has been a good solution for me.
In essence, you have an enum (in my case GameEvent) which handles all the different events needing to be passed around like PLAYER_DIED, LAUNCH_PLAYER and so on. I used Ashley's signals interface to create a simple queued store of events that a system can poll on each tick. As follows:
public class EventQueue implements Listener<GameEvent> {
private PriorityQueue<GameEvent> eventQueue;
public EventQueue() {
eventQueue = new PriorityQueue<GameEvent>();
}
public GameEvent[] getEvents() {
GameEvent[] events = eventQueue.toArray(new GameEvent[0]);
eventQueue.clear();
return events;
}
public GameEvent poll() {
return eventQueue.poll();
}
#Override
public void receive(Signal<GameEvent> signal, GameEvent event) {
eventQueue.add(event);
}
}
Next, in my GameWorld class, the one which loads the Ashley Engine and populates it with systems, I have a single Signal<GameEvent> which is the main backbone for my event queue. Here, like Listener<T>, Signal<T> is already part of Ashley.
Some systems then need to be able to fire into this signal / receive events from it so they take this Signal class in the constructor. The EntitySystem can then bind a listener or fire events which would then be passed on to other listeners. E.g. my LaserSystem class (simplified):
public class LaserSystem extends IteratingSystem implements Disposable, ContactListener {
...
private Signal<GameEvent> gameEventSignal;
private EventQueue eventQueue;
public LaserSystem(Signal<GameEvent> gameEventSignal) {
super(Family.all(LaserComponent.class).get(), Constants.SYSTEM_PRIORITIES.LASER);
this.gameEventSignal = gameEventSignal;
eventQueue = new EventQueue();
gameEventSignal.add(eventQueue);
}
...
#Override
public void beginContact(Contact contact) {
....
LaserComponent laserComponent = laserMapper.get(laser);
laserComponent.updateLaser = true;
if (other.getComponent(PlayerComponent.class) != null) {
gameEventSignal.dispatch(GameEvent.LASER_COLLISION);
}
}
}
Hopefully this makes sense, also feel free to read my project code for more example usage.
I never used Ashley as ECS but usually Systems should not communicate with each other.
Reason: When Systems would communicate they would not be independent of each other. Independent Systems allow you to freely add and remove them without having to worry the code breaks. The game logic probably breaks of course when a important Systems are missing.
Have a Factory (class) which does create the bullet entity. Then use the Factory in each System which can built new bullet entity.

Open JFrame, only after successfull login verification with database. Using Eclipse?

what I'm trying to do is open up a main application from a login screen, only after the login information has been verified in the connected database.
Using Eclipse, what I have so far:
database.java: connection to MS Access Database using UCanAccess. (Success)
login.java: A login window that extends JFrame. When a username and password is entered, it is verified with the database. (Success)
Home.java: The main application window, that I want to only be accessible with a correct username and password. Does not extend JFrame, but has a JFrame within it.
Now, I have been able to set it up so that if the entered username and password are correct, a window pops up saying "Successful login". However, how do I approach setting it up so that after the successful login, it opens up Home.java?
I have looked at:
Open a new JFrame - I have tried the setVisible with my home but Eclipse returns an error saying to create a setVisible method in Home...I thought this is supposed to be an automatic control? After trying to create the method, more issues just arise.
JFrame Open Another JFrame - which suggests adding actionListener and then setting it visible..which I have done: public void actionPerformed(ActionEvent e) {this.setVisible(false); new Home().setVisible(true); but Eclipse just doesn't open up the login window at all. Initially, I thought it could be because my success message is in the actionListener, however even after removing that it still does not work.
Call Jframe from Java class and Open window after button click - My only conclusion is that this is not working since Home.java does not extend JFrame? However, I read through other sources that it is not good to use "extends JFrame"?
I guess I also don't have an understanding of the difference between "extends JFrame" vs a new JFrame within a class? I have been learning java on my own and I'm new to GUI creation. Maybe I am missing something very obvious, but I just can't find a solution.
Any ideas? Thanks
To give an idea, my Home.java starts like this:
public class Home {
private JFrame frame;
private JTable data;
private JTextField Column1;
private JTextField Column2;
private JTable table;
// Launch the application.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Areas window = new Areas();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
// Create the application.
public Home() {
initialize();
}
//Initialize the contents of the frame.
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 697, 518);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Start by defining a simple work flow which allows you to understand the logical path you want your code to take.
Break down the areas of responsibility so that your objects only do the work that they absolutely have to, for example, your login component should only collect the credentials from the user, it should not be responsible for validating them, that should be the responsibility of some kind of controller.
Equally, neither the login component or it's controller should be responsible for determine what happens after a successful login, that is the responsibility for another controller
This decouples the code and encourages reuse, so the next time you need to present some "login" view, you don't have to recode the whole thing, simply update the controller, model and/or view as required, or re-use it as it is
The concept of a controller in Swing is a little different then a normal MVC implementation, because Swing is already a form of MVC.
What I tend to do instead, is define a contract between the controller and the view which describes what events the view generates (and the events that the controller can expect), for example attemptLogin. This disconnects the controller from the view's implementation, so the view is free to form the view in what ever way it feels like, so long as when it wants to validate the actual credentials it calls attemptLogin
So, you would start with a "main controller" which is responsible for controlling the login and main application controllers. It defines the work flow between the login and the main application and monitors for appropriate events which the controllers may generate to make decisions about what it should do next
A basic flow of operation might look something like
This concept is demonstrated in Java and GUI - Where do ActionListeners belong according to MVC pattern?
Just create a method in your Home class that sets its JFrame to be visible:
public void setJFrameVisible(boolean visible)
{
frame.setVisible(visible);
}
Then, assuming your instance of your Home class is called "home", all you would have to do is:
home.setJFrameVisible(true);
Let me add a bit more context. When you're extending JFrame, the class inherits all the methods/properties of the JFrame class. That's why when you extend JFrame you can just call obj.setVisible(true), because your class inherited the setVisible method from the JFrame class. What you have is a class that contains a JFrame, so you have to call the setVisible method on the internal JFrame, not the class.

Which way of implementing thread is most beneficial?

I am working on a webserver written in Java. The web server is handling websocket communication with the clients and therefore we have a class called ClientHandler that has a socket and id as instance variables. The ClientHandler will need to have a function that will listen for messages from the clients. This function needs to work in paralell to the rest of the server, and since the "reading of messages" is a thread blocking function, we need a separate thread for this.
Here's the two alternative ways of implementing this:
public class ClientHandler implements Runnable{
//Instance variable
public Thread listener = new Thread(this);
.
.
.
public void run() {
while (!Thread.interrupted()){
//Listening code here
}
}
}
And then start the listener thread by writing
clientHandler.listener.start();
And stop it by writing
clientHandler.listener.interrupt();
Or this method:
public class ClientHandler {
//Instance variable
private Thread listenerTread;
private boolean alive; //set to true in constructor
.
.
.
public void listenToClient() {
listenerTread = new Thread(new Runnable() {
#Override
public void run(){
while (!alive){
//Listening code here
}
}
});
}
}
and then start the thread by calling the function listenToClient()
clientHandler.listenToClient();
and stop it by switching alive = false.
I have tried to find someone explaining the best solution, but most comparisons are between implementing Runnable or extending Thread. Is the any downsides to using either of the methods above? What method is best if I want to have multiple threads in one class?
I'm not sure you want to explicitly create a Thread instance. Why don't you try using a ThreadPoolExecutor to which you submit the tasks for execution. Read here more about thread pool. http://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html
Since you can have many clients, using a thread pool may improve the performance of your application.
You have two tasks. One is to listen for new connections and initiate serving of that connections. Second is to actually serve a connection. The decision to serve each connection within a separate thread is an implementation detail of the second task. In principle, it can be served in other ways, with a thread pool or with async IO. So this implementation detail should be hidden inside the code of the second task and must not be visible to the code of the first task. So use the second way.

Categories