re base code
[sdc.git] / common / onap-common-configuration-management / onap-configuration-management-cli / src / main / java / org / onap / config / gui / app / Configuration.java
1 package org.onap.config.gui.app;
2
3
4 import com.sun.tools.attach.VirtualMachine;
5 import com.sun.tools.attach.VirtualMachineDescriptor;
6 import org.onap.config.api.ConfigurationManager;
7
8 import javax.management.JMX;
9 import javax.management.MBeanServerConnection;
10 import javax.management.ObjectName;
11 import javax.management.remote.JMXConnector;
12 import javax.management.remote.JMXConnectorFactory;
13 import javax.management.remote.JMXServiceURL;
14 import java.awt.event.ItemEvent;
15 import java.awt.event.WindowAdapter;
16 import java.awt.event.WindowEvent;
17 import java.util.Collection;
18 import java.util.HashMap;
19 import java.util.Map;
20 import java.util.Set;
21 import java.util.concurrent.Executors;
22 import java.util.concurrent.TimeUnit;
23
24
25 /**
26  * The type Configuration.
27  */
28 public class Configuration extends Frame {
29
30   /**
31    * The Vm.
32    */
33   VirtualMachine vm = null;
34   private TextField host;
35   private TextField port;
36   private TextField user;
37   private Choice pid;
38   private TextField password;
39   private CheckboxGroup getUpdateList;
40   private CheckboxGroup localRemote;
41   private Choice tenantChoice;
42   private Choice namespaceChoice;
43   private Choice keyChoice;
44   private Checkbox latest;
45   private Checkbox lookup;
46   private Checkbox fallback;
47   private Checkbox nodeSpecific;
48   private Checkbox nodeSpecificForList;
49   private Checkbox latestForList;
50   private Checkbox lookupForList;
51   private Checkbox fallbackForList;
52   private Checkbox nodeOverride;
53   private TextArea getValue = new TextArea(1, 50);
54   private TextArea updateValue = new TextArea(1, 50);
55   private Panel table;
56   private CardLayout cards;
57   private Panel cardPanel;
58   private JMXConnector connector;
59   private ConfigurationManager manager;
60   private Frame container;
61   private Button getKeysButton;
62
63   /**
64    * Instantiates a new Configuration.
65    *
66    * @param title the title
67    */
68   public Configuration(String title) {
69     super(title);
70     setSize(300, 300);
71     setLayout(new GridLayout(2, 1));
72     Panel firstRowPanel = new Panel();
73     firstRowPanel.setLayout(new GridLayout(0, 1));
74     firstRowPanel.add(
75         buildHostPortPanel(host = new TextField("127.0.0.1"), port = new TextField("9999"),
76             pid = new Choice(), localRemote = new CheckboxGroup()));
77     firstRowPanel
78         .add(buildUserPasswordPanel(user = new TextField(""), password = new TextField("")));
79     firstRowPanel.add(buildGetUpdatelistPanel(getUpdateList = new CheckboxGroup()));
80     firstRowPanel.add(
81         buildTenantNamespacePanel(tenantChoice = new Choice(), namespaceChoice = new Choice()));
82     firstRowPanel.add(buildKeyPanel(keyChoice = new Choice()));
83     add(firstRowPanel);
84     add(cardPanel = buildCards(cards = new CardLayout()));
85     addWindowListener(new WindowAdapter() {
86       public void windowClosing(WindowEvent windowEvent) {
87         close();
88         System.exit(0);
89       }
90     });
91     pack();
92     setVisible(true);
93     container = this;
94     centreWindow(this);
95     Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(() -> {
96       this.populateAvailablePids();
97       validate();
98     }, 30, 30, TimeUnit.SECONDS);
99   }
100
101   /**
102    * The entry point of application.
103    *
104    * @param args the input arguments
105    */
106   public static void main(String[] args) {
107     Configuration configuration = new Configuration("Configuration Management App");
108
109   }
110
111   private void toggleLocalRemote(ItemEvent ie) {
112     if (ie.getStateChange() == ItemEvent.SELECTED) {
113       String usecase = (ie.getSource() instanceof Checkbox) ? ((Checkbox) ie.getSource()).getLabel()
114           : ((Checkbox) ie.getItem()).getLabel();
115       pid.setEnabled(usecase.equals("Local"));
116       host.setEnabled(!usecase.equals("Local"));
117       port.setEnabled(!usecase.equals("Local"));
118     }
119   }
120
121   private Panel buildHostPortPanel(TextField host, TextField port, Choice pid,
122                                    CheckboxGroup group) {
123     populateAvailablePids();
124     Panel panel = new Panel();
125     panel.setLayout(new GridBagLayout());
126     GridBagConstraints gbc = new GridBagConstraints();
127     gbc.fill = gbc.HORIZONTAL;
128     gbc.weightx = 0;
129     Checkbox checkbox = null;
130     panel.add(checkbox = new Checkbox("Local", group, pid.getItemCount() > 0), gbc);
131     checkbox.addItemListener(this::toggleLocalRemote);
132     gbc.weightx = 0;
133     panel.add(checkbox = new Checkbox("Remote", group, pid.getItemCount() == 0), gbc);
134     checkbox.addItemListener(this::toggleLocalRemote);
135     gbc.weightx = 0;
136     panel.add(new Label("PID:"), gbc);
137     gbc.weightx = 1;
138     panel.add(pid, gbc);
139     gbc.weightx = 0;
140     panel.add(new Label("Host:"), gbc);
141     gbc.weightx = 1;
142     panel.add(host, gbc);
143     gbc.weightx = 0;
144     panel.add(new Label("Port:"), gbc);
145     gbc.weightx = 1;
146     panel.add(port, gbc);
147     host.setEnabled(pid.getItemCount() == 0);
148     port.setEnabled(pid.getItemCount() == 0);
149     pid.setEnabled(pid.getItemCount() > 0);
150     return panel;
151   }
152
153   private Panel buildUserPasswordPanel(TextField user, TextField password) {
154     Panel panel = new Panel();
155     password.setEchoChar('*');
156     panel.setLayout(new GridBagLayout());
157     GridBagConstraints gbc = new GridBagConstraints();
158     gbc.fill = gbc.HORIZONTAL;
159     gbc.weightx = 0;
160     panel.add(new Label("User : "), gbc);
161     gbc.weightx = 1;
162     panel.add(user, gbc);
163     gbc.weightx = 0;
164     panel.add(new Label("Password : "), gbc);
165     gbc.weightx = 1;
166     panel.add(password, gbc);
167     gbc.weightx = 0;
168     Button button = null;
169     panel.add(button = new Button("Connect"), gbc);
170     button.addActionListener((actionListener) -> connect());
171     return panel;
172   }
173
174   /**
175    * Build get updatelist panel panel.
176    *
177    * @param getUpdtaeList the get updtae list
178    * @return the panel
179    */
180   public Panel buildGetUpdatelistPanel(CheckboxGroup getUpdtaeList) {
181     Panel panel = new Panel();
182     Checkbox checkbox = null;
183     panel.setLayout(new GridLayout(1, 3));
184     panel.add(checkbox = new Checkbox("Get", getUpdtaeList, true));
185     checkbox.addItemListener(this::showCard);
186     panel.add(checkbox = new Checkbox("List", getUpdtaeList, false));
187     checkbox.addItemListener(this::showCard);
188     panel.add(checkbox = new Checkbox("Update", getUpdtaeList, false));
189     checkbox.addItemListener(this::showCard);
190     return panel;
191   }
192
193   /**
194    * Build tenant namespace panel panel.
195    *
196    * @param tenant    the tenant
197    * @param namespace the namespace
198    * @return the panel
199    */
200   public Panel buildTenantNamespacePanel(Choice tenant, Choice namespace) {
201     Panel panel = new Panel();
202     panel.setLayout(new GridBagLayout());
203     GridBagConstraints gbc = new GridBagConstraints();
204     gbc.fill = gbc.HORIZONTAL;
205     gbc.weightx = 0;
206     panel.add(new Label("Tenant"), gbc);
207     gbc.weightx = 1;
208     panel.add(tenant, gbc);
209     gbc.weightx = 0;
210     panel.add(new Label("Namespace"), gbc);
211     gbc.weightx = 1;
212     panel.add(namespace, gbc);
213     gbc.weightx = 0;
214     panel.add(getKeysButton = new Button("Get Keys"), gbc);
215     getKeysButton.addActionListener((actionListener) -> populateKeys(
216         manager.getKeys(tenantChoice.getSelectedItem(), namespaceChoice.getSelectedItem())));
217     tenantChoice.addItemListener((itemListener) -> keyChoice.removeAll());
218     namespaceChoice.addItemListener((itemListener) -> keyChoice.removeAll());
219     return panel;
220   }
221
222   private Panel buildConnectPanel() {
223     Button button = null;
224     Panel panel = new Panel();
225     panel.setLayout(new GridLayout(1, 3));
226     panel.add(new Label());
227     panel.add(button = new Button("Connect"));
228     panel.add(new Label());
229     button.addActionListener((actionListener) -> connect());
230     return panel;
231   }
232
233   /**
234    * Build key panel panel.
235    *
236    * @param keyChoice the key choice
237    * @return the panel
238    */
239   public Panel buildKeyPanel(Choice keyChoice) {
240     Panel panel = new Panel();
241     panel.setLayout(new GridBagLayout());
242     GridBagConstraints gbc = new GridBagConstraints();
243     gbc.fill = gbc.HORIZONTAL;
244     gbc.weightx = 0;
245     panel.add(new Label("Keys : "), gbc);
246     gbc.weightx = 1;
247     panel.add(keyChoice, gbc);
248     return panel;
249   }
250
251   /**
252    * Build cards panel.
253    *
254    * @param cards the cards
255    * @return the panel
256    */
257   public Panel buildCards(CardLayout cards) {
258     Panel panel = new Panel();
259     panel.setLayout(cards);
260     panel.add(buildCardGetPanel(latest = new Checkbox("Latest"),
261         fallback = new Checkbox("Fallback"),
262         lookup = new Checkbox("External Lookup"), nodeSpecific = new Checkbox("Node Specific"),
263         getValue), "Get");
264     panel.add(buildCardUpdatePanel(nodeOverride = new Checkbox("NodeOverride"),
265         updateValue), "Update");
266     panel.add(buildCardListPanel(table = new Panel(), latestForList = new Checkbox("Latest"),
267         fallbackForList = new Checkbox("Fallback"), lookupForList = new Checkbox("External Lookup"),
268         nodeSpecificForList = new Checkbox("Node Specific")), "List");
269     return panel;
270   }
271
272   /**
273    * Build card get panel panel.
274    *
275    * @param latest       the latest
276    * @param fallback     the fallback
277    * @param lookup       the lookup
278    * @param nodeSpecific the node specific
279    * @param value        the value
280    * @return the panel
281    */
282   public Panel buildCardGetPanel(Checkbox latest, Checkbox fallback, Checkbox lookup,
283                                  Checkbox nodeSpecific, TextArea value) {
284     Panel panel = new Panel();
285
286     panel.setLayout(new BorderLayout());
287     Panel p1 = new Panel();
288     p1.setLayout(new GridLayout(1, 4));
289     p1.add(latest);
290     p1.add(fallback);
291     p1.add(nodeSpecific);
292     p1.add(lookup);
293     panel.add(p1, BorderLayout.NORTH);
294     panel.add(value, BorderLayout.CENTER);
295     Panel bottom = new Panel();
296     bottom.setLayout(new GridLayout(1, 5));
297     bottom.add(new Label());
298     Button button = null;
299     bottom.add(button = new Button("GET"));
300     button.addActionListener((actionListener) -> value.setText(manager
301         .getConfigurationValue(buildMap("org.onap.config.type.ConfigurationQuery", value))));
302     bottom.add(new Label());
303     bottom.add(button = new Button("CLOSE"));
304     bottom.add(new Label());
305     panel.add(bottom, BorderLayout.SOUTH);
306     button.addActionListener((actionListener) -> {
307       close();
308       System.exit(0);
309     });
310     return panel;
311   }
312
313   private Map<String, Object> buildMap(String implClass, TextArea value) {
314     Map<String, Object> input = new HashMap<>();
315     input.put("ImplClass", implClass);//:);
316     input.put("externalLookup", value != null ? lookup.getState() : lookupForList.getState());
317     input.put("nodeOverride", nodeOverride.getState());
318     input.put("latest", value != null ? latest.getState() : latestForList.getState());
319     input.put("fallback", value != null ? fallback.getState() : fallbackForList.getState());
320     input.put("nodeSpecific",
321         value != null ? nodeSpecific.getState() : nodeSpecificForList.getState());
322     input.put("tenant", tenantChoice.getSelectedItem());
323     input.put("namespace", namespaceChoice.getSelectedItem());
324     if (keyChoice.getItemCount() == 0) {
325       message("Error", "Key is missing.");
326       throw new RuntimeException("Error");
327     }
328     input.put("key", keyChoice.getSelectedItem());
329     input.put("value", value == null ? "" : value.getText());
330     return input;
331   }
332
333   /**
334    * Build card update panel panel.
335    *
336    * @param nodeOverride the node override
337    * @param value        the value
338    * @return the panel
339    */
340   public Panel buildCardUpdatePanel(Checkbox nodeOverride, TextArea value) {
341     Panel panel = new Panel();
342     panel.setLayout(new BorderLayout());
343     Panel p1 = new Panel();
344     p1.setLayout(new GridLayout(1, 1));
345     p1.add(nodeOverride);
346     panel.add(p1, BorderLayout.NORTH);
347     panel.add(value, BorderLayout.CENTER);
348     Panel bottom = new Panel();
349     bottom.setLayout(new GridLayout(1, 5));
350     bottom.add(new Label());
351     Button button = null;
352     bottom.add(button = new Button("UPDATE"));
353     button.addActionListener((actionListener) -> {
354       manager
355           .updateConfigurationValue(buildMap("org.onap.config.type.ConfigurationUpdate", value));
356       message("Info", "Success");
357     });
358     bottom.add(new Label());
359     bottom.add(button = new Button("CLOSE"));
360     bottom.add(new Label());
361     panel.add(bottom, BorderLayout.SOUTH);
362     button.addActionListener((actionListener) -> {
363       close();
364       System.exit(0);
365     });
366     return panel;
367   }
368
369   /**
370    * Build card list panel panel.
371    *
372    * @param table        the table
373    * @param latest       the latest
374    * @param fallback     the fallback
375    * @param nodeSpecific the node specific
376    * @param lookup       the lookup
377    * @return the panel
378    */
379   public Panel buildCardListPanel(Panel table, Checkbox latest, Checkbox fallback,
380                                   Checkbox nodeSpecific, Checkbox lookup) {
381     Panel panel = new Panel();
382     panel.setLayout(new BorderLayout());
383     table.setLayout(new GridLayout(0, 2));
384     ScrollPane sp = new ScrollPane();
385     sp.add(table);
386     panel.add(sp, BorderLayout.CENTER);
387     Panel p1 = new Panel();
388     p1.setLayout(new GridLayout(1, 4));
389     p1.add(latest);
390     p1.add(fallback);
391     p1.add(lookup);
392     p1.add(nodeSpecific);
393     panel.add(p1, BorderLayout.NORTH);
394     Panel bottom = new Panel();
395     bottom.setLayout(new GridLayout(1, 5));
396     bottom.add(new Label());
397     Button button = null;
398     bottom.add(button = new Button("List"));
399     button.addActionListener((actionListener) -> populateKeyValue(
400         manager.listConfiguration(buildMap("org.onap.config.type.ConfigurationQuery", null))));
401     bottom.add(new Label());
402     bottom.add(button = new Button("CLOSE"));
403     bottom.add(new Label());
404     panel.add(bottom, BorderLayout.SOUTH);
405     button.addActionListener((actionListener) -> {
406       close();
407       System.exit(0);
408     });
409     return panel;
410   }
411
412   private void populateKeyValue(Map<String, String> collection) {
413     table.removeAll();
414     Set<String> keys = collection.keySet();
415     for (String key : keys) {
416       table.add(new Label(key));
417       table.add(new Label(collection.get(key)));
418     }
419     table.validate();
420   }
421
422   private void showCard(ItemEvent ie) {
423     if (ie.getStateChange() == ItemEvent.SELECTED) {
424       String usecase = (ie.getSource() instanceof Checkbox) ? ((Checkbox) ie.getSource()).getLabel()
425           : ((Checkbox) ie.getItem()).getLabel();
426       cards.show(cardPanel, usecase);
427       if (usecase.equals("List")) {
428         keyChoice.removeAll();
429       }
430       keyChoice.setEnabled(!usecase.equals("List"));
431       getKeysButton.setEnabled(!usecase.equals("List"));
432     }
433   }
434
435   private void close() {
436     try {
437       if (connector != null) {
438         connector.close();
439         connector = null;
440         vm.detach();
441       }
442     } catch (Exception exception) {
443       //Do nothing
444     }
445   }
446
447   private void connect() {
448     try {
449       close();
450       if (!validateHostPort()) {
451         return;
452       }
453       JMXServiceURL url = null;
454       if (localRemote.getSelectedCheckbox().getLabel().equals("Local")) {
455         url = new JMXServiceURL(
456             (vm = VirtualMachine.attach(pid.getSelectedItem())).getAgentProperties()
457                 .getProperty("com.sun.management.jmxremote.localConnectorAddress"));
458       } else {
459         url = new JMXServiceURL(
460             "service:jmx:rmi:///jndi/rmi://" + host.getText() + ":" + port.getText() + "/jmxrmi");
461       }
462       Map<String, String[]> env = new HashMap<>();
463       String[] credentials = {user.getText(), password.getText()};
464       env.put(JMXConnector.CREDENTIALS, credentials);
465       connector = JMXConnectorFactory.connect(url, env);
466       MBeanServerConnection mbsc = connector.getMBeanServerConnection();
467       ObjectName mbeanName = new ObjectName("org.openecomp.jmx:name=SystemConfig");
468       manager = JMX.newMBeanProxy(mbsc, mbeanName, ConfigurationManager.class, true);
469       message("Message", "Success!!!");
470       populateTenants(manager.getTenants());
471       populateNamespaces(manager.getNamespaces());
472     } catch (Exception exception) {
473       message("Error", exception.getMessage());
474     }
475   }
476
477   private boolean validateHostPort() {
478     if (localRemote.getSelectedCheckbox().getLabel().equals("Local")) {
479       if (pid.getSelectedItem() == null || pid.getSelectedItem().trim().length() == 0
480           || !pid.getSelectedItem().matches("^[1-9][0-9]*$")) {
481         message("Error", "pid is mandatory numeric value greater than 0.");
482         return false;
483       }
484     } else {
485       if (host.getText() == null || host.getText().trim().length() == 0) {
486         message("Error", "Host is mandatory.");
487         return false;
488       }
489       if (port.getText() == null || port.getText().trim().length() == 0
490           || !port.getText().matches("^[1-9][0-9]*$")) {
491         message("Error", "Port is mandatory numeric value greater than 0.");
492         return false;
493       }
494     }
495     return true;
496   }
497
498   private void populateTenants(Collection<String> collection) {
499     tenantChoice.removeAll();
500     for (String item : collection) {
501       tenantChoice.add(item);
502     }
503   }
504
505   private void populateNamespaces(Collection<String> collection) {
506     namespaceChoice.removeAll();
507     keyChoice.removeAll();
508     for (String item : collection) {
509       namespaceChoice.add(item);
510     }
511   }
512
513   private void populateKeys(Collection<String> collection) {
514     keyChoice.removeAll();
515     for (String item : collection) {
516       keyChoice.add(item);
517     }
518   }
519
520   private void message(String title, String text) {
521     Dialog dialog = new Dialog(container, title, true);
522     dialog.setLayout(new BorderLayout());
523     dialog.add(new Label(text), BorderLayout.CENTER);
524     Button ok = new Button("OK");
525     Panel panel = new Panel();
526     panel.setLayout(new GridLayout(1, 3));
527     panel.add(new Label());
528     panel.add(ok);
529     panel.add(new Label());
530     ok.addActionListener((actionListener) -> dialog.setVisible(false));
531     dialog.add(panel, BorderLayout.SOUTH);
532     dialog.pack();
533     centerDialog(dialog);
534     dialog.setVisible(true);
535   }
536
537   private void centreWindow(Frame frame) {
538     Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
539     int x1 = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
540     int y1 = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
541     frame.setLocation(x1, y1);
542   }
543
544   private void centerDialog(Dialog dialog) {
545     Dimension dimension = container.getSize();
546     container.getLocationOnScreen();
547     int x1 =
548         container.getLocationOnScreen().x + (int) ((dimension.getWidth() - dialog.getWidth()) / 2);
549     int y1 = container.getLocationOnScreen().y
550         + (int) ((dimension.getHeight() - dialog.getHeight()) / 2);
551     dialog.setLocation(x1, y1);
552   }
553
554   private void setWindowPosition(Frame window, int screen) {
555     GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
556     GraphicsDevice[] allDevices = env.getScreenDevices();
557     int topLeftX;
558     int topLeftY;
559     int screenX;
560     int screenY;
561     int windowPosX;
562     int windowPosY;
563
564     if (screen < allDevices.length && screen > -1) {
565       topLeftX = allDevices[screen].getDefaultConfiguration().getBounds().x;
566       topLeftY = allDevices[screen].getDefaultConfiguration().getBounds().y;
567
568       screenX = allDevices[screen].getDefaultConfiguration().getBounds().width;
569       screenY = allDevices[screen].getDefaultConfiguration().getBounds().height;
570     } else {
571       topLeftX = allDevices[0].getDefaultConfiguration().getBounds().x;
572       topLeftY = allDevices[0].getDefaultConfiguration().getBounds().y;
573
574       screenX = allDevices[0].getDefaultConfiguration().getBounds().width;
575       screenY = allDevices[0].getDefaultConfiguration().getBounds().height;
576     }
577
578     windowPosX = ((screenX - window.getWidth()) / 2) + topLeftX;
579     windowPosY = ((screenY - window.getHeight()) / 2) + topLeftY;
580
581     window.setLocation(windowPosX, windowPosY);
582   }
583
584   private void populateAvailablePids() {
585     pid.removeAll();
586     for (VirtualMachineDescriptor desc : VirtualMachine.list()) {
587       try {
588         VirtualMachine vm = null;
589         JMXServiceURL url = new JMXServiceURL(
590             (vm = VirtualMachine.attach(desc.id())).getAgentProperties()
591                 .getProperty("com.sun.management.jmxremote.localConnectorAddress"));
592         Set set = JMXConnectorFactory.connect(url, null).getMBeanServerConnection()
593             .queryMBeans(new ObjectName("org.openecomp.jmx:name=SystemConfig"), null);
594         if (!set.isEmpty()) {
595           pid.add(desc.id());
596         }
597         vm.detach();
598       } catch (Exception exception) {
599         //do nothing
600       }
601     }
602   }
603 }