OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 153 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
43 ilm 1
package org.openconcerto.modules.badge;
2
 
3
import java.awt.AWTException;
4
import java.awt.Image;
5
import java.awt.MenuItem;
6
import java.awt.PopupMenu;
7
import java.awt.SystemTray;
8
import java.awt.TrayIcon;
9
import java.awt.event.ActionEvent;
10
import java.awt.event.ActionListener;
11
import java.io.File;
12
import java.io.FileInputStream;
13
import java.io.FileNotFoundException;
14
import java.io.IOException;
15
import java.net.DatagramPacket;
16
import java.net.DatagramSocket;
17
import java.sql.SQLException;
18
import java.sql.Time;
19
import java.text.SimpleDateFormat;
167 ilm 20
import java.time.LocalDateTime;
21
import java.time.format.DateTimeFormatter;
22
import java.time.format.FormatStyle;
43 ilm 23
import java.util.Calendar;
24
import java.util.Date;
25
import java.util.List;
26
import java.util.Properties;
167 ilm 27
import java.util.prefs.BackingStoreException;
28
import java.util.prefs.Preferences;
43 ilm 29
 
30
import javax.swing.ImageIcon;
31
import javax.swing.JFrame;
32
import javax.swing.JOptionPane;
33
import javax.swing.SwingUtilities;
34
 
35
import org.openconcerto.erp.config.ComptaPropsConfiguration;
167 ilm 36
import org.openconcerto.erp.core.customerrelationship.customer.element.CustomerSQLElement;
85 ilm 37
import org.openconcerto.erp.modules.ModuleVersion;
167 ilm 38
import org.openconcerto.erp.utils.HeadlessGestion;
43 ilm 39
import org.openconcerto.sql.model.SQLRow;
40
import org.openconcerto.sql.model.SQLRowValues;
167 ilm 41
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
43 ilm 42
import org.openconcerto.sql.model.SQLSelect;
43
import org.openconcerto.sql.model.SQLTable;
44
import org.openconcerto.sql.model.Where;
167 ilm 45
import org.openconcerto.utils.cc.ITransformer;
43 ilm 46
 
47
public class BadgeListener implements Runnable {
48
    private static final int UDP_PORT = 1470;
167 ilm 49
 
118 ilm 50
    private String doorIp;
43 ilm 51
    private int relai;
167 ilm 52
    private ComptaPropsConfiguration conf;
53
    private Preferences modulePrefs;
43 ilm 54
 
55
    protected TrayIcon trayIcon;
56
 
57
    public BadgeListener() {
118 ilm 58
 
59
    }
60
 
167 ilm 61
    public void init(String id) throws Exception {
62
        final HeadlessGestion headlessGestion = new HeadlessGestion();
63
        headlessGestion.setupGlobalState(2, Integer.valueOf(id));
64
        this.conf = headlessGestion.getComptaPropsConfiguration();
43 ilm 65
 
167 ilm 66
        final String moduleID = "org.openconcerto.modules.badge";
67
        final ModuleVersion vers = this.conf.getModuleManager().getDBInstalledModuleVersion(moduleID);
68
        this.modulePrefs = this.conf.getModuleManager().getFactories().get(moduleID).get(vers).getSQLPreferences(this.conf.getModuleManager().getRoot());
43 ilm 69
    }
70
 
71
    private PopupMenu createTrayMenu() {
72
        ActionListener exitListener = new ActionListener() {
73
            public void actionPerformed(ActionEvent e) {
74
                System.out.println("Bye from the tray");
75
                System.exit(0);
76
            }
77
        };
78
 
79
        ActionListener executeListener = new ActionListener() {
80
            public void actionPerformed(ActionEvent e) {
118 ilm 81
                openDoor(4);
43 ilm 82
            }
83
        };
84
 
85
        PopupMenu menu = new PopupMenu();
86
        MenuItem execItem = new MenuItem("Ouvrir la porte");
87
        execItem.addActionListener(executeListener);
88
        menu.add(execItem);
89
 
90
        MenuItem exitItem = new MenuItem("Quitter");
91
        exitItem.addActionListener(exitListener);
92
        menu.add(exitItem);
93
        return menu;
94
    }
95
 
96
    private TrayIcon createTrayIcon() {
97
        Image image = new ImageIcon(this.getClass().getResource("badge.png")).getImage();
98
        PopupMenu popup = createTrayMenu();
99
        TrayIcon ti = new TrayIcon(image, "Service de badge", popup);
100
        ti.setImageAutoSize(true);
101
        return ti;
102
    }
103
 
167 ilm 104
    public static void main(String[] args) throws Exception {
43 ilm 105
        BadgeListener bl = new BadgeListener();
106
        bl.readConfiguration();
107
        bl.initUI();
108
        bl.startDaemon();
109
    }
110
 
111
    public void startDaemon() {
112
        Thread t = new Thread(this);
113
        t.setName("UDP Listener");
114
        t.start();
115
    }
116
 
117
    public void initUI() {
118
        SwingUtilities.invokeLater(new Runnable() {
119
 
120
            @Override
121
            public void run() {
122
                if (!SystemTray.isSupported()) {
118 ilm 123
                    try {
124
                        JOptionPane.showMessageDialog(new JFrame(), "System tray not supported on this platform");
125
                    } catch (Exception e) {
126
                        System.out.println("System tray not supported on this platform");
127
                    }
128
                } else {
129
                    try {
130
                        final SystemTray sysTray = SystemTray.getSystemTray();
131
                        trayIcon = createTrayIcon();
132
                        sysTray.add(trayIcon);
133
                        displayMessage("Service de badge", "Ecoute sur port " + UDP_PORT);
134
                    } catch (AWTException e) {
135
                        System.out.println("Unable to add icon to the system tray");
136
                    }
43 ilm 137
                }
138
 
139
            }
140
        });
141
 
142
    }
143
 
167 ilm 144
    public void readConfiguration() throws Exception {
43 ilm 145
        final Properties props = new Properties();
146
        final File file = new File("badge.properties");
147
        System.out.println("Reading from: " + file.getAbsolutePath());
148
        try {
149
            final FileInputStream inStream = new FileInputStream(file);
150
            props.load(inStream);
118 ilm 151
            this.doorIp = props.getProperty("ip").trim();
43 ilm 152
            this.relai = Integer.parseInt(props.getProperty("relai", "1"));
153
            inStream.close();
154
        } catch (FileNotFoundException e) {
155
            JOptionPane.showMessageDialog(new JFrame(), "Fichier manquant\n" + file.getAbsolutePath());
156
        } catch (IOException e) {
157
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage());
158
        }
118 ilm 159
        System.err.println("BadgeListener.readConfiguration() door ip : " + doorIp + ", index :" + relai);
43 ilm 160
 
118 ilm 161
        init(props.getProperty("idSociete"));
43 ilm 162
    }
163
 
164
    @Override
165
    public void run() {
166
        while (true) {
167
            DatagramSocket serverSocket = null;
168
 
169
            try {
170
                final byte[] receiveData = new byte[1024];
171
                serverSocket = new DatagramSocket(UDP_PORT);
172
 
173
                while (true) {
174
                    final DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
175
                    serverSocket.receive(receivePacket);
176
                    final String sentence = new String(receivePacket.getData()).trim();
118 ilm 177
                    cardIdReceived(sentence);
43 ilm 178
                }
179
            } catch (Throwable e) {
180
                e.printStackTrace();
118 ilm 181
                displayError("Erreur", (e == null) ? "" : e.getMessage());
43 ilm 182
            } finally {
183
                if (serverSocket != null) {
184
                    serverSocket.close();
185
                }
186
            }
187
            try {
188
                System.out.println("Waiting 10s");
189
                Thread.sleep(10 * 1000);
190
            } catch (InterruptedException e) {
191
                System.err.println(e.getMessage());
192
            }
193
        }
194
    }
195
 
118 ilm 196
    public void cardIdReceived(final String sentence) {
197
        if (isBadgeAllowed(sentence)) {
198
            boolean b = openDoor(4);
199
            if (b) {
200
                displayMessage("Ouverture", "Ouverture de la porte OK");
201
            } else {
202
                displayError("Erreur", "Impossible d'ouvrir la porte");
203
            }
204
 
205
        } else {
206
            displayMessage("Carte refusée", "Carte " + sentence + " non acceptée");
207
        }
208
    }
209
 
167 ilm 210
    private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
211
 
118 ilm 212
    public void displayMessage(String title, String txt) {
167 ilm 213
        displayMessage(title, txt, TrayIcon.MessageType.INFO);
214
    }
215
 
216
    private void displayMessage(String title, String txt, final TrayIcon.MessageType msgType) {
217
        if (this.trayIcon != null) {
218
            this.trayIcon.displayMessage(title, txt, msgType);
118 ilm 219
        } else {
167 ilm 220
            System.out.println("[" + msgType.name() + "] " + DATE_FMT.format(LocalDateTime.now()) + " " + title + " : " + txt);
118 ilm 221
        }
222
    }
223
 
224
    public void displayError(String title, String txt) {
167 ilm 225
        displayMessage(title, txt, TrayIcon.MessageType.ERROR);
118 ilm 226
    }
227
 
167 ilm 228
    public boolean isBadgeAllowed(final String cardNumber) {
229
        final CustomerSQLElement clientElem = this.conf.getDirectory().getElement(CustomerSQLElement.class);
230
        final String clientAdhFieldName = "ID_ADHERENT";
231
        final SQLTable tableAdh = clientElem.getForeignElement(clientAdhFieldName).getTable();
232
        // TODO use createFetcher()
233
        final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(clientElem.createGraph());
234
        fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
235
            @Override
236
            public SQLSelect transformChecked(SQLSelect sel) {
237
                sel.andWhere(new Where(sel.getAlias(tableAdh).getField("NUMERO_CARTE"), "=", cardNumber));
238
                return sel;
239
            }
240
        });
241
        final List<SQLRowValues> list = fetcher.fetch();
43 ilm 242
 
243
        String motif = "";
167 ilm 244
 
43 ilm 245
        boolean allow = false;
167 ilm 246
        SQLRowValues adh = null;
247
        String name = null;
43 ilm 248
        // Aucun adhérent assigné à cette carte
249
        if (list == null || list.isEmpty()) {
250
            motif = "Aucun adhérent associé à la carte " + cardNumber;
167 ilm 251
            displayError("Erreur", motif);
43 ilm 252
 
253
        } else if (list.size() > 1) {
254
            motif = list.size() + " adhérents sont liés à la même carte " + cardNumber;
167 ilm 255
            displayError("Erreur", motif);
43 ilm 256
            Thread.dumpStack();
257
        } else {
258
 
167 ilm 259
            for (SQLRowValues clientR : list) {
260
                name = clientR.getString("NOM");
261
                adh = (SQLRowValues) clientR.getForeign(clientAdhFieldName);
43 ilm 262
 
263
                // Admin toujours autorisé
167 ilm 264
                if (adh.getBoolean("ADMIN")) {
43 ilm 265
                    allow = true;
266
                    motif = "Administrateur toujours autorisé";
65 ilm 267
                    break;
43 ilm 268
                }
269
 
167 ilm 270
                // get up to date values
271
                try {
272
                    this.modulePrefs.sync();
273
                } catch (BackingStoreException e) {
274
                    e.printStackTrace();
275
                }
276
                final boolean onlyAdmin = this.modulePrefs.getBoolean(Module.ENTREE_PREF, false);
79 ilm 277
                if (onlyAdmin) {
278
                    motif = "Seul les membres administrateurs sont autorisés!";
279
                    break;
280
                }
281
 
167 ilm 282
                if (!adh.getBoolean("ACTIF")) {
43 ilm 283
                    motif = "La carte de l'adhérent n'est pas active dans sa fiche";
65 ilm 284
                    break;
43 ilm 285
                }
286
 
287
                Calendar cal = Calendar.getInstance();
65 ilm 288
                final Date d = cal.getTime();
167 ilm 289
                final Calendar dateValidite = adh.getDate("DATE_VALIDITE_INSCRIPTION");
43 ilm 290
 
65 ilm 291
                if (dateValidite != null && dateValidite.before(cal)) {
43 ilm 292
                    motif = "La date d'autorisation est expirée";
65 ilm 293
                    break;
43 ilm 294
                }
295
 
167 ilm 296
                SQLRow rowPlage = adh.asRow().getForeignRow("ID_PLAGE_HORAIRE");
43 ilm 297
 
298
                if (rowPlage != null) {
299
                    Time time = new Time(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
300
                    SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE");
301
                    String day = dateFormat.format(d).toUpperCase();
302
                    {
303
                        Time d1 = (Time) rowPlage.getObject("DEBUT_1_" + day);
304
                        Time f1 = (Time) rowPlage.getObject("FIN_1_" + day);
305
                        if (d1 != null && f1 != null) {
306
                            if (time.after(d1) && time.before(f1)) {
307
                                allow = true;
308
                                motif = "Autorisé sur la plage " + rowPlage.getString("NOM") + " 1";
309
                                break;
310
                            }
311
                        }
312
                    }
313
                    {
314
                        Time d1 = (Time) rowPlage.getObject("DEBUT_2_" + day);
315
                        Time f1 = (Time) rowPlage.getObject("FIN_2_" + day);
316
 
317
                        if (d1 != null && f1 != null) {
318
                            if (time.after(d1) && time.before(f1)) {
319
                                allow = true;
320
                                motif = "Autorisé sur la plage " + rowPlage.getString("NOM") + " 2";
321
                                break;
322
                            }
323
                        }
324
                    }
325
 
326
                    {
327
                        Time d1 = (Time) rowPlage.getObject("DEBUT_3_" + day);
328
                        Time f1 = (Time) rowPlage.getObject("FIN_3_" + day);
329
 
330
                        if (d1 != null && f1 != null) {
331
                            if (time.after(d1) && time.before(f1)) {
332
                                allow = true;
333
                                motif = "Autorisé sur la plage " + rowPlage.getString("NOM") + " 3";
334
                                break;
335
                            }
336
                        }
337
                    }
338
                    motif = "Non autorisé sur la plage horaire " + rowPlage.getString("NOM");
339
                } else {
340
                    motif = "Aucune plage horaire associée";
341
                }
342
            }
343
        }
344
 
345
        // Création de l'entrée dans la table
167 ilm 346
        SQLTable tableEntree = this.conf.getDirectory().getElement("ENTREE").getTable();
43 ilm 347
        SQLRowValues rowVals = new SQLRowValues(tableEntree);
348
        rowVals.put("DATE", new Date());
349
        rowVals.put("NUMERO_CARTE", cardNumber);
350
        rowVals.put("ACCEPTE", allow);
351
        rowVals.put("MOTIF", motif);
352
 
167 ilm 353
        if (name != null) {
354
            rowVals.put("ADHERENT", name);
43 ilm 355
        }
356
        try {
357
            rowVals.commit();
358
        } catch (SQLException exn) {
359
            exn.printStackTrace();
360
        }
361
        return allow;
362
    }
363
 
118 ilm 364
    public boolean openDoor(int seconds) {
365
        final Relai r = new Relai(doorIp, relai);
366
        try {
367
            r.pulse(seconds);
368
            return true;
369
        } catch (Throwable ex) {
370
            return false;
371
        }
372
    }
373
 
374
    public String getDoorIp() {
375
        return doorIp;
376
    }
43 ilm 377
}