OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
17 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
182 ilm 4
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
17 ilm 5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.sql.users.rights;
15
 
73 ilm 16
import org.openconcerto.sql.Configuration;
17
import org.openconcerto.sql.TM;
18
import org.openconcerto.sql.element.SQLElement;
19
import org.openconcerto.sql.element.SQLElementDirectory;
182 ilm 20
import org.openconcerto.sql.model.SQLInsert;
21
import org.openconcerto.sql.model.SQLRow;
22
import org.openconcerto.sql.model.SQLRowValues;
17 ilm 23
import org.openconcerto.sql.model.SQLTable;
182 ilm 24
import org.openconcerto.sql.model.SQLTableEvent;
25
import org.openconcerto.sql.model.SQLTableEvent.Mode;
17 ilm 26
import org.openconcerto.sql.model.Where;
27
import org.openconcerto.sql.request.ListSQLRequest;
28
import org.openconcerto.sql.sqlobject.IComboSelectionItem;
29
import org.openconcerto.sql.users.UserManager;
30
import org.openconcerto.sql.view.ListeModifyPanel;
182 ilm 31
import org.openconcerto.sql.view.list.RowAction;
17 ilm 32
import org.openconcerto.ui.DefaultGridBagConstraints;
182 ilm 33
import org.openconcerto.utils.ExceptionHandler;
34
import org.openconcerto.utils.Tuple2;
17 ilm 35
import org.openconcerto.utils.cc.IClosure;
36
 
37
import java.awt.GridBagConstraints;
38
import java.awt.GridBagLayout;
182 ilm 39
import java.awt.Toolkit;
40
import java.awt.datatransfer.Clipboard;
41
import java.awt.datatransfer.Transferable;
42
import java.awt.datatransfer.UnsupportedFlavorException;
93 ilm 43
import java.awt.event.ActionEvent;
182 ilm 44
import java.io.IOException;
45
import java.math.BigDecimal;
46
import java.sql.SQLException;
47
import java.util.ArrayList;
48
import java.util.HashMap;
49
import java.util.List;
50
import java.util.Map;
17 ilm 51
 
182 ilm 52
import javax.swing.AbstractAction;
93 ilm 53
import javax.swing.JButton;
17 ilm 54
import javax.swing.JLabel;
55
import javax.swing.JPanel;
56
import javax.swing.JScrollPane;
57
import javax.swing.JSplitPane;
58
import javax.swing.event.ListSelectionEvent;
59
import javax.swing.event.ListSelectionListener;
60
 
182 ilm 61
import net.minidev.json.JSONArray;
62
import net.minidev.json.JSONObject;
63
 
17 ilm 64
public class UserRightsPanel extends JPanel {
65
 
66
    // Liste des utilisateurs
67
    private final JListSQLTablePanel list;
68
    private final ListeModifyPanel modifPanel;
69
 
70
    public UserRightsPanel() {
73 ilm 71
        this(Configuration.getInstance().getDirectory());
72
    }
73
 
74
    public UserRightsPanel(final SQLElementDirectory dir) {
17 ilm 75
        super(new GridBagLayout());
76
 
77
        // init the list before adding it, otherwise we see the first refresh from all lines to just
78
        // these of undef
93 ilm 79
        this.modifPanel = new ListeModifyPanel(dir.getElement(UserRightSQLElement.class)) {
80
            @Override
81
            protected void handleAction(JButton source, ActionEvent evt) {
82
                super.handleAction(source, evt);
83
                // if the user click add and the create frame is then hidden (not closed) and he
84
                // later click add again the create frame will be brought to the front, its content
85
                // unmodified even if he has selected another principal. So call reset() so that the
86
                // principal in the create frame match the selected principal.
87
                if (source == this.buttonAjouter) {
88
                    this.getAddComp().resetValue();
89
                }
90
            }
91
        };
92
        // don't listen to the list, as the behaviour differs if there's some rights for a principal
93
        // or not. I.e. if the user clicks add the current principal is selected :
94
        // - if the user select another principal with rights, the principal is updated
95
        // - if the user select another principal without rights, no lines are available and the
96
        // principal is not updated
97
        this.modifPanel.setDeaf(true);
17 ilm 98
        this.modifPanel.setSearchFullMode(false);
80 ilm 99
        // order is important for rights
100
        this.modifPanel.getListe().setSortingEnabled(false);
17 ilm 101
        final SQLTable table = this.getTable().getForeignTable("ID_USER_COMMON");
65 ilm 102
 
73 ilm 103
        final SQLElement usersElem = dir.getElement(table);
104
        this.list = new JListSQLTablePanel(JListSQLTablePanel.createComboRequest(usersElem, true), TM.tr("rightsPanel.defaultRights"));
17 ilm 105
        // only superusers can see superusers (that's how we prevent the setting of superuser
106
        // rights)
107
        if (!UserRightsManager.getCurrentUserRights().isSuperUser())
108
            this.list.getModel().setWhere(new Where(table.getField("SUPERUSER"), "=", false));
109
        this.list.getModel().setItemCustomizer(new IClosure<IComboSelectionItem>() {
110
            @Override
111
            public void executeChecked(IComboSelectionItem input) {
112
                if (input.getId() == UserManager.getUserID())
113
                    input.setFlag(IComboSelectionItem.IMPORTANT_FLAG);
114
            }
115
        });
116
        this.list.addListSelectionListener(new ListSelectionListener() {
117
            @Override
118
            public void valueChanged(ListSelectionEvent e) {
119
                updateListFromSelection();
120
            }
121
        });
122
        this.updateListFromSelection();
123
 
124
        // Liste des utilisateurs
125
        JPanel listePanel = new JPanel(new GridBagLayout());
126
        GridBagConstraints c = new DefaultGridBagConstraints();
127
        c.weightx = 1;
128
        c.gridwidth = GridBagConstraints.REMAINDER;
73 ilm 129
        listePanel.add(new JLabel(TM.getInstance().trM("element.list", "element", usersElem.getName())), c);
17 ilm 130
 
131
        c.weightx = 1;
132
        c.weighty = 1;
133
        c.gridy++;
134
        c.fill = GridBagConstraints.BOTH;
135
        listePanel.add(this.list, c);
136
 
137
        // Droits
138
        JPanel panelDroits = new JPanel(new GridBagLayout());
139
        GridBagConstraints c2 = new DefaultGridBagConstraints();
140
        c2.gridwidth = GridBagConstraints.REMAINDER;
73 ilm 141
        panelDroits.add(new JLabel(TM.tr("rights")), c2);
17 ilm 142
        c2.gridy++;
143
        c2.weightx = 1;
144
        c2.weighty = 0.7;
145
        c2.fill = GridBagConstraints.BOTH;
146
 
147
        panelDroits.add(new JScrollPane(this.modifPanel), c2);
148
 
149
        // SplitPane
150
        JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listePanel, panelDroits);
151
        GridBagConstraints c3 = new GridBagConstraints();
152
        c3.weightx = 1;
153
        c3.weighty = 1;
154
        c3.fill = GridBagConstraints.BOTH;
155
        this.add(pane, c3);
182 ilm 156
 
157
        RowAction actionPaste = new RowAction(new AbstractAction("Coller") {
158
 
159
            @Override
160
            public void actionPerformed(ActionEvent e) {
161
                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
162
                Transferable clipboardContent = clipboard.getContents(this);
163
 
164
                if (clipboardContent.isDataFlavorSupported(UserRightCopySelection.rightsFlavor)) {
165
                    JSONObject rights;
166
                    try {
167
                        rights = (JSONObject) clipboardContent.getTransferData(UserRightCopySelection.rightsFlavor);
168
 
169
                        addRights(rights);
170
 
171
                    } catch (UnsupportedFlavorException | IOException e1) {
172
 
173
                        e1.printStackTrace();
174
                    }
175
                }
176
            }
177
 
178
        }, true) {
179
            @Override
180
            public boolean enabledFor(List<SQLRowValues> selection) {
181
                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
182
                Transferable clipboardContent = clipboard.getContents(this);
183
 
184
                return clipboardContent.isDataFlavorSupported(UserRightCopySelection.rightsFlavor);
185
            }
186
        };
187
        this.modifPanel.getListe().addIListeAction(actionPaste);
17 ilm 188
    }
189
 
190
    private void updateListFromSelection() {
191
        final int selectedIndex = this.list.getSelectedIndex();
192
 
193
        final boolean b = selectedIndex >= 0;
194
 
195
        final ListSQLRequest req = this.modifPanel.getListe().getRequest();
196
        final int userID;
197
        if (b) {
198
            userID = this.list.getModel().getRowAt(selectedIndex).getID();
199
        } else {
200
            // since we don't display user in the list (to avoid undef)
201
            // we need to always display at most one user
202
            userID = this.list.getModel().getTable().getUndefinedID();
203
        }
204
        req.setWhere(new Where(req.getPrimaryTable().getField("ID_USER_COMMON"), "=", userID));
205
 
206
        // enforce the limitation
93 ilm 207
        ((UserRightSQLComponent) this.modifPanel.getModifComp()).setUserID(userID);
208
        ((UserRightSQLComponent) this.modifPanel.getAddComp()).setUserID(userID);
17 ilm 209
    }
210
 
182 ilm 211
    private void addRights(JSONObject rights) {
212
        // Récupération des droits courants
213
        final ListSQLRequest req = this.modifPanel.getListe().getRequest();
214
        List<SQLRowValues> vals = req.getValues();
215
        Map<Tuple2<Number, String>, SQLRowValues> currentUserRight = new HashMap<>();
216
        for (SQLRowValues sqlRowValues : vals) {
217
            currentUserRight.put(Tuple2.create(sqlRowValues.getForeignIDNumber("ID_RIGHT"), sqlRowValues.getString("OBJECT")), sqlRowValues);
218
        }
219
 
220
        try {
221
            List<SQLInsert> inserts = new ArrayList<SQLInsert>();
222
 
223
            final int selectedIndex = this.list.getSelectedIndex();
224
            final boolean b = selectedIndex >= 0;
225
 
226
            final int userID;
227
            if (b) {
228
                userID = this.list.getModel().getRowAt(selectedIndex).getID();
229
            } else {
230
                // since we don't display user in the list (to avoid undef)
231
                // we need to always display at most one user
232
                userID = this.list.getModel().getTable().getUndefinedID();
233
            }
234
 
235
            BigDecimal order = getTable().getMaxOrder().add(BigDecimal.ONE);
236
            for (Object a : rights.values()) {
237
                JSONArray array = (JSONArray) a;
238
                Number right = (Number) array.get(0);
239
                String obj = (String) array.get(1);
240
                Boolean hasRight = (Boolean) array.get(2);
241
 
242
                final Tuple2<Number, String> key = Tuple2.create(right, obj);
243
                if (currentUserRight.containsKey(key)) {
244
                    SQLRowValues rowVals = currentUserRight.get(key);
245
                    if (!rowVals.getBoolean("HAVE_RIGHT").equals(hasRight)) {
246
                        rowVals.createEmptyUpdateRow().put("HAVE_RIGHT", hasRight).commit();
247
                    }
248
                } else {
249
                    SQLInsert insert = new SQLInsert();
250
                    insert.add(getTable().getField("ID_RIGHT"), right);
251
                    insert.add(getTable().getField("HAVE_RIGHT"), hasRight);
252
                    insert.add(getTable().getField("OBJECT"), obj);
253
                    insert.add(getTable().getField("ID_USER_COMMON"), userID);
254
                    insert.add(getTable().getOrderField(), order);
255
 
256
                    inserts.add(insert);
257
                    order = order.add(BigDecimal.ONE);
258
                }
259
            }
260
            if (!inserts.isEmpty()) {
261
                SQLInsert.executeMultiple(getTable().getDBSystemRoot(), inserts);
262
                getTable().fire(new SQLTableEvent(getTable(), SQLRow.NONEXISTANT_ID, Mode.ROW_ADDED));
263
            }
264
        } catch (SQLException e1) {
265
            ExceptionHandler.handle("Erreur lors de la duplication des droits", e1);
266
        }
267
    }
268
 
17 ilm 269
    public final SQLTable getTable() {
270
        return this.modifPanel.getElement().getTable();
271
    }
272
}