001/**
002 * Copyright (C) 2014  Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/
003 *
004 * This file is part of Dicoogle/dicoogle.
005 *
006 * Dicoogle/dicoogle is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * Dicoogle/dicoogle is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with Dicoogle.  If not, see <http://www.gnu.org/licenses/>.
018 */
019package pt.ua.dicoogle.rGUI.client;
020
021import java.net.InetAddress;
022import java.net.UnknownHostException;
023import java.rmi.RemoteException;
024import java.util.Timer;
025import java.util.TimerTask;
026import java.util.concurrent.Semaphore;
027import org.slf4j.Logger;
028import org.slf4j.LoggerFactory;
029import org.slf4j.Logger;
030import org.slf4j.LoggerFactory;
031import javax.swing.JOptionPane;
032import pt.ua.dicoogle.Main;
033import pt.ua.dicoogle.rGUI.client.UIHelper.ServerMessagesManager;
034import pt.ua.dicoogle.rGUI.client.windows.MainWindow;
035import pt.ua.dicoogle.rGUI.interfaces.IAdmin;
036import pt.ua.dicoogle.rGUI.interfaces.IUser;
037
038/**
039 *
040 * @author Samuel Campos <samuelcampos@ua.pt>
041 */
042@Deprecated
043
044public class ClientCore {
045
046    private IUser user = null;
047    private IAdmin admin = null;
048
049    private InetAddress serverAddr;
050    private boolean localServer = false;
051
052    private static int timeoutTime = 8000;  //5 seconds (needs to be minor than 15 seconds)
053    private static int startTime = 1000;    //starts the keepAlive only 1 second after start
054    
055    private AdminKeepAliveThread adminKeep;
056    private UserKeepAliveThread userKeep;
057    
058    private static ClientCore instance;
059    private static Semaphore sem = new Semaphore(1, true);
060
061    public static synchronized ClientCore getInstance() {
062        try {
063            sem.acquire();
064            if (instance == null) {
065                instance = new ClientCore();
066            }
067            sem.release();
068        } catch (InterruptedException ex) {
069            LoggerFactory.getLogger(ClientCore.class).error(ex.getMessage(), ex);
070        }
071        return instance;
072    }
073
074    private ClientCore() {
075      
076    }
077
078    public void setUser(IUser user) {
079        try {
080            this.user = user;
081
082            if(Main.isFixedClient())
083                user.shtudownTimeout(Main.randomInteger);
084            if (!(Main.isFixedClient() && user.shtudownTimeout(Main.randomInteger))) {
085                userKeep = new UserKeepAliveThread(user);
086                userKeep.start();
087            }
088
089    
090            
091                //userKeep = new UserKeepAliveThread(user);
092                //userKeep.start();
093
094            
095            UserRefs.getUserRefs(user);
096        } catch (RemoteException ex) {
097            LoggerFactory.getLogger(ClientCore.class).error(ex.getMessage(), ex);
098        }
099    }
100
101    public boolean isUser() {
102        return user != null;
103    }
104
105    public IUser getUser() {
106        return user;
107    }
108
109    public void setAdmin(IAdmin admin) {
110        try {
111            this.admin = admin;
112            
113            if(Main.isFixedClient())
114                admin.shtudownTimeout(Main.randomInteger);
115            if (!(Main.isFixedClient() && admin.shtudownTimeout(Main.randomInteger))) {
116                adminKeep = new AdminKeepAliveThread(admin);
117                adminKeep.start();
118            }
119
120            AdminRefs.getAdminRefs(admin);          
121            ServerMessagesManager.getInstance();
122        } catch (RemoteException ex) {
123            LoggerFactory.getLogger(ClientCore.class).error(ex.getMessage(), ex);
124        }
125    }
126
127    public boolean isAdmin() {
128        return AdminRefs.getInstance() != null;
129    }
130
131    public void setServerAddress(InetAddress serverAddr){
132        this.serverAddr = serverAddr;
133
134        try {
135            //Verify if the remote server is in the local pc
136            if (serverAddr.equals(InetAddress.getByName("localhost"))){
137                System.out.println(" localServer True");
138                localServer = true;
139                return;
140            }
141            
142            InetAddress in = InetAddress.getLocalHost();
143            InetAddress[] all = InetAddress.getAllByName(in.getHostName());
144            
145            for (int i = 0; i < all.length; i++)
146                if (serverAddr.equals(all[i])){
147                    localServer = true;
148                    return;
149                }
150            System.out.println(" localServer False");
151            localServer = false;
152        } catch (UnknownHostException ex) {
153            //LoggerFactory.getLogger(ClientCore.class).error(ex.getMessage(), ex);
154        }
155    }
156
157    public InetAddress getServerAddress(){
158        return serverAddr;
159    }
160    
161    public boolean isLocalServer(){        
162        return localServer;
163    }
164
165    public void stopKeepAlives(){
166        //DebugManager.getInstance().log("Stopping KeepAlive messages between server and client");
167        if(isAdmin() && adminKeep != null){
168            adminKeep.timer.cancel();
169            adminKeep = null;
170        }
171
172        if(userKeep != null){
173            userKeep.timer.cancel();
174            userKeep = null;
175        }
176    }
177
178    private void closeDicoogle(int source) {
179        String message = "The connection with the GUI server is lost!\n";
180        
181        if(source == 1)
182            message += "User KeepAlive failed.\n";
183        else
184            message += "Admin KeepAlive failed.\n";
185
186        message += "Dicoolge client is closing.";
187        
188        JOptionPane.showMessageDialog(MainWindow.getInstance(), message,
189                "Connection Lost", JOptionPane.ERROR_MESSAGE);
190
191        System.exit(2);
192    }
193
194    /**
195     * Private classes, they are used only within this parent class
196     */
197   
198
199    private class UserKeepAliveThread extends Thread{
200        private Timer timer;
201        private TimerTask userTask;
202        private IUser userRef;
203
204        public UserKeepAliveThread(IUser user){
205            timer = new Timer();
206            userRef = user;
207        }
208
209        @Override
210        public void run(){
211            userTask = new UserKeepAlive();
212            timer.schedule(userTask, startTime, timeoutTime);
213        }
214
215        private class UserKeepAlive extends TimerTask {
216
217            @Override
218            public void run() {
219                try {
220                    userRef.KeepAlive();
221                } catch (Exception ex) {
222                    closeDicoogle(1);
223                }
224            }
225        }
226    }
227
228    private class AdminKeepAliveThread extends Thread{
229        private Timer timer;
230        private TimerTask adminTask;
231        private IAdmin adminRef;
232
233        public AdminKeepAliveThread(IAdmin admin){
234            timer = new Timer();
235            adminRef = admin;
236        }
237
238
239        @Override
240        public void run(){
241            adminTask = new AdminKeepAlive();
242            timer.schedule(adminTask, startTime, timeoutTime);
243        }
244
245        private class AdminKeepAlive extends TimerTask {
246
247            @Override
248            public void run() {
249                try {
250                    adminRef.KeepAlive();
251                } catch (Exception ex) {
252                    closeDicoogle(2);
253                }
254            }
255        }
256    }
257}