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