Decision to make a class static - java

I have the server project that I have seperated into 6 different classes:
ServerConnectionManager - is class is ment to be the hub for all other classes
Connection - This object is the created whenever a client connects and also starts a Thread
ServerListner - This is the Thread class that listens to input from the user
ServerSender - This is the class that sends messages to one or more users
ServerInformation - this class contains two list one of chat persons and one of connections this class also allows you to search through the list to find a specefic person and or connection
ChatPerson - This object is to contain the username of each person who connects to the server
As you no-doubt have guessed by now this is a server for a chat program!
My question to you is:
I want to use the Design patteren (Mediator) on this project and therefore the ServerConnectionManager contains all the key methods that each of the classes use. for example adding a connection to the connection list in the ServerInformation class.
But since the ServerInformation class cannot be called an object seeing as it only have alot of methods (functions) and no real purpose other than storing and searching Data would it be a good idea to make it static? or should i stick to the plan and make everything go through the ServerConnectionManager?
Here is a sample of my code:
ServerConnectionManager
public class ServerConnectionManager {
private static ServerSocket server;
private static Socket connection;
private static ServerInformation ai = new ServerInformation();
private static boolean connected = false;
private static final int portNumber = 7070;
private static int backLog = 100;
/**
* This method launches the server (and the application)!
* #param args
*/
public static void main(String[] args){
startServer();
waitForConnection();
}
/**
*This method sets the serverSocket to portNumber and also adds the backLog.
*/
private static void startServer() {
try {
server = new ServerSocket(portNumber, backLog);
connected = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* This method waits for a connection aslong as the serverSocket is connected.
* When a new client connects it creates an Object of the connection and starts the individual procedure.
*/
private static void waitForConnection() {
while (connected) {
try {
connection = server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection c = new Connection(connection);
addConnection(c);
waitForConnection();
}
}
public static void closeMe(Socket con) {
for (Connection conn : ai.getConnectionList()) {
if (conn.getConnection() == con) {
ai.getList().remove(ai.getList().indexOf(ai.getChatPersonByConnection(con)));
ai.getConnectionList().remove(conn);
System.out.println(ai.getList());
System.out.println(ai.getConnectionList());
conn.close();
break;
}
}
}
public static void addConnection(Connection con){
ai.addToConnectionList(con);
}
public static void addChatPerson(ChatPerson p){
ai.add(p);
System.out.println(ai.getList());
}
}
Connection
public class Connection{
private Socket connection;
public Connection(Socket connection){
this.connection = connection;
ServerListner cl = new ServerListner(Connection.this);
cl.start();
}
public Socket getConnection(){
return this.connection;
}
public void close() {
try {
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ServerListner
public class ServerListner extends Thread {
private Socket connection;
private BufferedReader br;
private ChatPerson person;
private Connection con;
private ServerInformation ai = new ServerInformation();
private ServerSender sender = new ServerSender();
public ServerListner(Connection con){
this.con = con;
connection = con.getConnection();
try {
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Socket getConnection(){
return this.connection;
}
public void run(){
System.out.println(con.getConnection().isConnected());
try {
String inString;
while ((inString = br.readLine()) != null) {
if (inString.equalsIgnoreCase("Disconnect")) {
System.out.println(inString);
break;
}else {
processInput(inString);
}
}
ServerConnectionManager.closeMe(connection);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void processInput(String input){
if (input.equalsIgnoreCase("Connect")) {
sender.sendMessageToConnection(this.connection, "Accepted");
}
if (input.equalsIgnoreCase("UserInformation")) {
try {
String username = br.readLine();
person = new ChatPerson(username, connection);
ServerConnectionManager.addChatPerson(person);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (input.equalsIgnoreCase("SearchByCon")) {
String name = ai.searchByConnection(connection);
System.out.println(name);
}
}
}
ServerSender
public class ServerSender {
private PrintWriter pw;
private ServerInformation ai = new ServerInformation();
public void addToList(){
}
public void sendToAll(String message){
for (Connection c : ai.getConnectionList()) {
try {
pw = new PrintWriter(c.getConnection().getOutputStream());
pw.print(message);
pw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
*
* #param con
* #param message
*/
/*
* Note - Denne metode gør også at jeg kan hviske til folk!:)
*/
public void sendMessageToConnection(Socket con, String message){
try {
PrintWriter print = new PrintWriter(con.getOutputStream());
print.println(message);
print.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ServerInformation
public class ServerInformation{
private ArrayList<Connection> connectedClients = new ArrayList<Connection>();
private ArrayList<ChatPerson> list = new ArrayList<ChatPerson>();
public ArrayList<Connection> getConnectionList(){
return connectedClients;
}
public void addToConnectionList(Connection con){
connectedClients.add(con);
}
public String searchByConnection(Socket myConnection){
for (ChatPerson p : list) {
if (p.getConnection() == myConnection) {
return p.getName();
}
}
/*
* If none found!
*/
return null;
}
public ChatPerson getChatPersonByConnection(Socket myConnection){
for (ChatPerson p : list) {
if (p.getConnection() == myConnection) {
return p;
}
}
return null;
}
public void add(ChatPerson p){
list.add(p);
}
public void removeByName(String name){
for (ChatPerson p : list) {
if (p.getName().equalsIgnoreCase(name)) {
list.remove(p);
}
}
}
public String searchList(String name){
for (ChatPerson p : list) {
if (p.getName().equalsIgnoreCase(name)) {
return p.getName();
}
}
return null;
}
public ArrayList<ChatPerson>getList(){
return list;
}
}
ChatPerson
public class ChatPerson {
private String chatName;
private Socket connection;
/*
* This is for furture development
* private Integer adminLevel;
*/
public ChatPerson(String name, Socket connection){
this.chatName = name;
this.connection = connection;
}
public void setName(String name){
this.chatName = name;
}
public String getName(){
return chatName;
}
public String toString(){
return "Username: "+chatName;
}
public Socket getConnection(){
return connection;
}
}
Thank you in advance, by the way since i am a student it would be nice if you had time to rate my code aswell and come with suggestions on how i can improve (if there are any :))

You probably meant class with only static methods, not static class. Static inner classes are something different (you can google it).
Advantages of having non-static methods in your manager:
You can easily mock them with frameworks like Mockito during testing.
You can pull them up to some interface during refactoring of your code.
Using static methods is not object-oriented-programming as such method invocations are not associated with any instance (object) of your class.

Related

Observer with RxJava/Quarkus

I started a Quarkus project, which (in part) shall watch for file changes on a text-file, read the added line(s) and then sends the added line(s) through a websocket connection to a client.
For watching the file changes and reading those I created the following class:
public class McServerService {
private String directory;
private List<String> currentLog;
private Observable<List<String>> observableLog;
private Thread logObserverThread;
public McServerService (String directory) {
this.currentLog = new ArrayList<String>();
this.observableLog = Observable.fromCallable(() -> this.currentLog);
this.directory = directory;
}
public void startWatching () {
this.logObserverThread = new Thread(new LogObserverThreadImpl(this.directory));
this.logObserverThread.start();
}
public void subscribeToLog (Observer<? super List<String>> observer) {
this.observableLog.subscribe(observer);
}
private class LogObserverThreadImpl implements Runnable {
BufferedReader br;
WatchService watchService;
private LogObserverThreadImpl (String directory) {
try {
this.br = new BufferedReader(new java.io.FileReader(directory + "\\" + "latest.log"));
String nextLine;
while ((nextLine = this.br.readLine()) != null) {
McServerService.this.currentLog.add(nextLine);
System.out.println(nextLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
Path path = Paths.get(directory);
try {
System.out.println("entered try");
this.watchService = FileSystems.getDefault().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = this.watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
if (event.context().toString().equals("latest.log")) {
String line = this.br.readLine();
McServerService.this.currentLog.add(line);
System.out.println(line);
}
}
key.reset();
}
System.out.println("after while");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Now the websocket would be handled by this class:
#ServerEndpoint("/test")
#ApplicationScoped
public class McServerWebSocket {
Map<String, Session> sessions = new ConcurrentHashMap<>();
McServerService mss = new McServerService("D:\\Spiele\\Minecraft");
#OnOpen
public void onOpen(Session session, #PathParam("name") String name) {
sessions.put(name, session);
}
#OnClose
public void onClose(Session session, #PathParam("name") String name) {
sessions.remove(name);
}
#OnError
public void onError(Session session, #PathParam("name") String name, Throwable throwable) {
sessions.remove(name);
}
#OnMessage
public void onMessage(String message, #PathParam("name") String name) {
Session c_session = sessions.get(name);
c_session.getAsyncRemote().sendObject("insert");
}
private class ConsoleLogObserverImpl implements Observer<List<String>>{
private ConsoleLogObserverImpl () {
}
#Override
public void onSubscribe(#NonNull Disposable d) {
// TODO Auto-generated method stub
System.out.println("subscribed");
}
#Override
public void onNext(#NonNull List<String> t) {
System.out.println(t.toString());
}
#Override
public void onError(#NonNull Throwable e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete() {
// TODO Auto-generated method stub
System.out.println("finished");
}
}
}
I didnt implement the websocket yet, because my problem lies with observing the changes of
private List<String> currentLog; in the McServerServive class.
Unfortunately I deleted the main method in McServerWebSocket, that I used to test this, but that main method would essentially just create an instance of McServerWebSocket and then call the startWatching() method of its McServerService mss = new McServerService("D:\\Spiele\\Minecraft"); and its
public void subscribeToLog (Observer<? super List<String>> observer) {
this.observableLog.subscribe(observer);
}
method with the inner class:
private class ConsoleLogObserverImpl implements Observer<List<String>>
But the behaviour was not as I would have exspected. The output was:
subscribed
[]
finished
The observable was imediately terminating. Did I do something wrong when creating the Observable or did I completly misunderstand the usage RxJava?
How can I create an Observable class field and an Observer that triggers an action when the Observable is changed with RxJava/some Quarkus extension?

TCP Multiple Clients Room

I'm making code for a Server that has multiple clients that joins in it. Here's what the server's looks like.
public class Server {
private final ServerSocket serverSocket;
private static final int PORT = 9000;
private WaitingRoom wroom = new WaitingRoom();
public Server(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
public void startServer() throws InterruptedException,Exception{
try {
int count = 0;
while (!serverSocket.isClosed()) {
Socket socket = serverSocket.accept();
System.out.println("A new client has connected!");
ClientHandler clientHandler = new ClientHandler(new Player(count),socket);
Thread thread = new Thread(clientHandler);
thread.start();
count++;
System.out.println(clientHandler.getPlayer().getNickname());
wroom.join(clientHandler.getPlayer());
}
} catch (IOException e) {
closeServerSocket();
}
}
public void closeServerSocket() {
try {
if(serverSocket != null)
serverSocket.close();
}catch (IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException,InterruptedException,Exception{
ServerSocket serverSocket = new ServerSocket(PORT);
Server server = new Server(serverSocket);
server.startServer();
}
}
I've a class named ClientHandler that manages these clients in a thread for each, and i pass it also in the Player class because i will use it for things like: Send msg, Receive msg. That's the ClientHandler class:
public class ClientHandler implements Runnable {
public static ArrayList<ClientHandler> clientHandlers = new ArrayList<>();
private Player player;
private String nickname;
private Socket socket;
private BufferedReader bufferedReader;
private BufferedWriter bufferedWriter;
public ClientHandler(Player player,Socket socket) throws InterruptedException,Exception{
try {
this.socket = socket;
this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.bufferedWriter= new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
nickname = this.bufferedReader.readLine();
player.init(nickname, this);
clientHandlers.add(this);
broadcastMessage("SERVER: " + nickname + " è entrato");
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
}
}
public Player getPlayer(){
return player;
}
public BufferedWriter getBufferedWriter(){
return bufferedWriter;
}
public BufferedReader getBufferedReader(){
return bufferedReader;
}
#Override
public void run() {
String messageFromClient;
while (socket.isConnected()) {
/* try {
// messageFromClient = bufferedReader.readLine();
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
break;
} */
}
}
public void broadcastMessage(String messageToSend) {
for (ClientHandler clientHandler : clientHandlers) {
try {
if (!clientHandler.nickname.equals(nickname)) {
clientHandler.bufferedWriter.write(messageToSend);
clientHandler.bufferedWriter.newLine();
clientHandler.bufferedWriter.flush();
}
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
}
}
}
private void writeToClient(String text) throws IOException{
bufferedWriter.write(text);
bufferedWriter.newLine();
bufferedWriter.flush();
}
public void removeClientHandler() {
clientHandlers.remove(this);
broadcastMessage("SERVER: " + nickname + " è uscito");
}
public void closeEverything(Socket socket, BufferedReader bufferedReader, BufferedWriter bufferedWriter) {
removeClientHandler();
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now, the problem is: if I want to create a class named "WaitingRoom" for let players to waint until the wait's done. Where and how could I instantiate it? Before the linked code, i was instantiating it in the ClientHandler, but it worked only for a client a time. Here's what i wrote for the WaitingRoom class:
public class WaitingRoom {
private final int MAXPLAYERS = 2;
private ArrayList<Player> players = new ArrayList<Player>();
public ArrayList<Player> getPlayers(){
return players;
}
public void join(Player player) throws IOException,InterruptedException,Exception{
while(!addPlayer(player)){
player.sendMsg("waiting for join");
TimeUnit.SECONDS.sleep(1);
}
waitStart(player);
}
public boolean addPlayer(Player player){
if (players.size() >= MAXPLAYERS) return false;
players.add(player);
return true;
}
public boolean removePlayer(int idPlayer){
for(Player player : players){
if(player.getId() == idPlayer){
players.remove(player);
return true;
}
}
return false;
}
public void waitStart(Player player) throws IOException,InterruptedException,Exception{
if(players.size() < MAXPLAYERS)
player.sendMsg("sei entrato nella stanza d'attesa");
while(players.size() < MAXPLAYERS){
player.sendMsg("(" + players.size() + "/2) in attesa di giocatori...");
TimeUnit.SECONDS.sleep(1);
}
player.sendMsg("Inizio Gioco");
Player[] players2 = new Player[MAXPLAYERS];
for(int i=0;i<MAXPLAYERS;i++){
players2[0] = new Player(players.get(i).getId()).init(players.get(i).getNickname(),players.get(i).getClientHandler());
}
new Gioco(players2);
cleanRoom();
}
public void cleanRoom(){
players.clear();
}}
it's a really basic concept for waiting room and I only need a place where user must to wait before a gameloop. For example i don't really need multiple wainting rooms, one is ok for me, maybe.

JAVA RMI get pass ArrayList element

I have a server that contains an ArrayList in " ServerInfo " and when I try to take from ClientRMI an element of the ArrayList(in ServerInfo) for example adf.getSGM ( 0 ).incrementCount( ) ;
"count" does not increase it's as if every time I call it instantiates a new class SGM
in a few words I want to interact from ClientRMI with ArrayList that is on ServerInfo (SORRY FOR ENGLISH)
Hear are the classes :
SERVER
public class ServerRMI {
public static void main(String[] args) {
Registry registry = null;
String name = "ServerInfo";
try {
System.out.println("Init RMI");
ServerInfoInterface sir = ServerInfo.getInstance();
ServerInfoInterface stub = (ServerInfoInterface) UnicastRemoteObject.exportObject(sir, 0);
registry = LocateRegistry.createRegistry(9000);
registry.bind(name, stub);
System.out.println("RMI OK");
System.out.println("Init SGM...");
for(int i=0;i<3;i++){
ServerInfo.getInstance().addSGM(new SGM());
}
System.out.println("Init SGM OK");
} catch (Exception e) {
System.out.println("RMI Error"+e.toString());
registry = null;
}
}
}
public class ServerInfo implements ServerInfoInterface{
private ArrayList<SGM> sgmHandler = new ArrayList<SGM>();
// Singleton pattern
private static ServerInfo instance;
// Singleton pattern
public static ServerInfo getInstance() {
if (instance == null){
System.out.println("ServerInfo new instance");
instance = new ServerInfo();
}
return instance;
}
#Override
public synchronized void addSGM(SGM sgm) throws RemoteException {
sgmHandler.add(sgm);
}
#Override
public synchronized SGM getSGM(int i) throws RemoteException {
return sgmHandler.get(i);
}
}
public interface ServerInfoInterface extends Remote{
public void addSGM(SGM sgm) throws RemoteException;
public SGM getSGM(int i) throws RemoteException;
}
public class SGM implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4756606091542270097L;
private int count=0;
public void incrementCount(){
count++;
}
public void decrementCount(){
count--;
}
public int getCount(){
return count;
}
}
CLIENT
public class ClientRMI {
private ServerInfoInterface sgmInterface;
public void startServer() {
String name = "ServerInfo";
Registry registry;
try {
registry = LocateRegistry.getRegistry(9000);
try {
sgmInterface = (ServerInfoInterface) registry.lookup(name);
sgmInterface.getSGM(0).incrementCount();
System.out.println(sgmInterface.getSGM(0).getCount()); // always 0
} catch (AccessException e) {
System.out.println("RIM AccessException"+ e.toString());
} catch (RemoteException e) {
System.out.println("RIM RemoteException"+ e.toString());
} catch (NotBoundException e) {
System.out.println("RIM NotBoundException"+ e.toString());
}
} catch (RemoteException e) {
System.out.println("RIM RemoteException registry"+ e.toString());
}
}
}
You're creating an SGM at the server, passing it via Serialization to the client, incrementing its count at the client, and then expecting that count to be magically increased at the server.
It can't work.
You will have to make SGM a remote object, with its own remote interface, or else provide a remote method in the original remote interface to increment the count of a GSM, specified by index.

objects don't deserializing when i use socket in Java

I have two classes , utilisateur ( means user in french ) and Envellope ( wich means envelope ), so i have many classes to organize sending and receiving objects to/from two classes in localhost !
I want to print the result in the screen after sending and receiving.
I conclude that it's not deserializing and the output of toString is a kind of hashcode like this #14ae5a5
Envellope class:
public class Envellope<T> implements Serializable{
private static final long serialVersionUID = -5653473013975445298L;
public String todo;
public T thing;
public Envellope() {
}
public Envellope(String todo, T thing) {
this.todo = todo;
this.thing = thing;
}
}
Utilisateur class:
public class utilisateur implements Serializable{
private static final long serialVersionUID = -5429001491604482315L;
public String login;
public String mdp;
public utilisateur(String l,String m){
login=l;
mdp=m;
}
public utilisateur(){}
}
and there is the main (Client):
public static void main(String[] args) {
try {
Socket socket=new Socket("localhost",4444);
StreamObject so=new StreamObject(socket);
Envellope<utilisateur> toSend=new Envellope<utilisateur>("Authenticate",new utilisateur("addou","ismail"));
so.send(toSend);//sending to ServerSocket
Envellope<utilisateur> env=(Envellope<utilisateur>) so.receive();//receiving from server
System.out.println(env.todo+" Object: "+env.thing);
} catch (IOException ex) {
Logger.getLogger(Aaa.class.getName()).log(Level.SEVERE, null, ex);
}
}
I didn't write here the other classes, because i think it works , but if you need it just tell me !
StreamObject class:
public class StreamObject extends IOS{
private ObjectOutputStream oos;
private ObjectInputStream ois;
public StreamObject(Socket s) throws IOException{
super();
super.os=s.getOutputStream();
super.is=s.getInputStream();
oos=new ObjectOutputStream(os);
ois=new ObjectInputStream(is);
}
And IOS class is just inputStream and OutputStream !
public void send(Object object) {
try {
oos.writeObject(object);
} catch (IOException e) {
System.out.print("Erreur receive socket: ");
System.err.print("IOException ");
System.out.println(e.getMessage());
}
}
public Object receive() {
try {
return ois.readObject();
} catch (ClassNotFoundException e) {
System.out.print("Erreur receive socket: ");
System.err.print("ClassNotFoundException ");
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.print("Erreur receive socket: ");
System.err.print("IOException ");
System.out.println(e.getMessage());
}
return null;
}
}
Your utilisateur class does not override toString, so it uses the default implementation, which returns the class name and hash code.
Add something like this to utilisateur:
#Override
public String toString() {
return "login="+login+" & mdp="+mdp;
}

How to initialise,load properties and dispose my own connection pool using spring?

I have own connection pool:
public final class ConnectionPool {
private static final Logger log = Logger.getLogger(ConnectionPool.class);
private static final int DEFAULT_POOL_SIZE = 10;
//single instance
private static ConnectionPool instance;
//queue of free connections
private BlockingQueue<Connection> connectionQueue;
public ConnectionPool(String driver, String url, String user,
String password, int poolSize)
throws ClassNotFoundException, DAOException{
try{
Class.forName(driver);
connectionQueue = new ArrayBlockingQueue<Connection>(poolSize);
for(int i = 0; i < poolSize ;i++){
Connection connection = DriverManager.getConnection(url, user, password);
connectionQueue.offer(connection);
}
}
catch (SQLException e) {
log.error(e);
throw new DAOException(e.getMessage());
}
}
public static void init() throws DAOException{
try {
if(instance == null){
String driver = ConfigurationManager.
getInstance().getProperty(ConfigurationManager.DATABASE_DRIVER_NAME);
String url = ConfigurationManager.
getInstance().getProperty(ConfigurationManager.DATABASE_URL);
String user = ConfigurationManager.
getInstance().getProperty(ConfigurationManager.DATABASE_USER);
String password = ConfigurationManager.
getInstance().getProperty(ConfigurationManager.DATABASE_PASSWORD);
String poolSizeStr = ConfigurationManager.
getInstance().getProperty(ConfigurationManager.DATABASE_POOLSIZE);
int poolSize = (poolSizeStr != null) ?
Integer.parseInt(poolSizeStr) : DEFAULT_POOL_SIZE;
log.info("Trying to create pool of connections...");
instance = new ConnectionPool(driver,url,user,password,poolSize);
log.info("Connection pool initialized");
}
}catch (ClassNotFoundException e) {
log.error(e);
} catch (SQLException e) {
log.error(e);
throw new DAOException(e.getMessage());
}
}
public static void dispose() throws DAOException {
try {
if(instance != null){
instance.clearConnectionQueue();
instance = null;
log.info("Connection queue is disposed");
}
} catch (DAOException e) {
log.info(e.getMessage());
throw new DAOException(e.getMessage());
}
}
public static ConnectionPool getInstance(){
return instance;
}
public Connection takeConnection() {
Connection connection = null;
try{
connection = connectionQueue.take();
}catch (InterruptedException e) {
log.info("Free connection waiting interrupted.Returned null connection");
log.error(e);
}
return connection;
}
public static void releaseConnection(Connection connection) throws DAOException {
try {
if(!connection.isClosed()){
if(!getInstance().connectionQueue.offer(connection)){
log.info("Connections is not added.");
}
}
else{
log.info("Trying to release closed connection.");
}
} catch (SQLException e) {
log.info("SQLException at connection isClosed(). Connection is not added");
throw new DAOException(e.getMessage());
}
}
private void clearConnectionQueue() throws DAOException{
try {
Connection connection;
while((connection = connectionQueue.poll()) != null){
if(!connection.getAutoCommit()){
connection.commit();
connection.close();
}
}
} catch (SQLException e) {
log.info(e.getMessage());
throw new DAOException(e.getMessage());
}
}
}
And I now I'm initialise and destroy it with listener and load properties using my own class ConfigurationManager,connected with ResourceBundle:
public final class ConfigurationManager {
private static ConfigurationManager instance;
private ResourceBundle resourceBundle;
//getting info from config.properties
private static final String BUNDLE_NAME = "config";
public static final String DATABASE_DRIVER_NAME =
"DATABASE_DRIVER_NAME";
public static final String DATABASE_URL =
"DATABASE_URL";
public static final String DATABASE_USER =
"DATABASE_USER";
public static final String DATABASE_PASSWORD =
"DATABASE_PASSWORD";
public static final String ERROR_PAGE_PATH =
"ERROR_PAGE_PATH";
public static final String BEAN_PATH =
"BEAN_PATH";
public static final String DATABASE_POOLSIZE =
"DATABASE_POOLSIZE";
public synchronized static ConfigurationManager getInstance() {
if (instance == null) {
instance = new ConfigurationManager();
instance.resourceBundle =
ResourceBundle.getBundle(BUNDLE_NAME);
}
return instance;
}
public String getProperty(String key) {
return (String)resourceBundle.getObject(key);
}
}
But I want to do it(init,destroy,properties), using Spring. So how could I do it?
Use Spring's init and destroy methods, of course:
http://www.mkyong.com/spring/spring-init-method-and-destroy-method-example/
Personally, I think this is ill-advised. You aren't likely to improve on the pools already available to you (e.g. C3P0). You may do worse. But that's your choice.

Categories