com.devoteam.srit.xmlloader.gui.frames.JFrameEditableParameters.java Source code

Java tutorial

Introduction

Here is the source code for com.devoteam.srit.xmlloader.gui.frames.JFrameEditableParameters.java

Source

/* 
 * Copyright 2012 Devoteam http://www.devoteam.com
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 * 
 * 
 * This file is part of Multi-Protocol Test Suite (MTS).
 * 
 * Multi-Protocol Test Suite (MTS) is free software: you can redistribute
 * it and/or modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of the
 * License.
 * 
 * Multi-Protocol Test Suite (MTS) is distributed in the hope that it will
 * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty 
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Multi-Protocol Test Suite (MTS).
 * If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package com.devoteam.srit.xmlloader.gui.frames;

import com.devoteam.srit.xmlloader.core.Tester;
import com.devoteam.srit.xmlloader.core.exception.ParameterException;
import com.devoteam.srit.xmlloader.core.log.GlobalLogger;
import com.devoteam.srit.xmlloader.core.log.TextEvent;
import com.devoteam.srit.xmlloader.core.parameters.EditableParameterProvider;
import java.awt.EventQueue;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;

import org.dom4j.Element;

import com.devoteam.srit.xmlloader.gui.TesterGui;
import com.devoteam.srit.xmlloader.gui.model.ModelEditableParameters;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Vector;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author  gpasquiers
 */
public class JFrameEditableParameters extends javax.swing.JDialog
        implements TableModelListener, EditableParameterProvider {

    /** Creates new form JFrameEditableParameters */
    public JFrameEditableParameters() {
        initComponents();
        this.setAlwaysOnTop(true);
        this.jTable1.getModel().addTableModelListener(this);
    }

    public JFrameEditableParameters(JFrame jFrame, boolean modal) {
        super(jFrame, modal);
        initComponents();
        this.setAlwaysOnTop(true);
        this.jTable1.getModel().addTableModelListener(this);
    }

    public void toto() {

    }

    @Override
    public void setVisible(boolean b) {
        if (b) {
            valueChanged = false;
            for (Element e : this.elements)
                elementsOrigin.add(e.createCopy());
        } else {
            elementsOrigin.clear();
            valueChanged = false;
        }
        super.setVisible(b);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable() {
            public String getToolTipText(MouseEvent event) {
                int col = convertColumnIndexToModel(columnAtPoint(event.getPoint()));
                int row = rowAtPoint(event.getPoint());
                return (String) getValueAt(row, col);
            }
        };
        jButtonOK = new javax.swing.JButton();
        jButtonDefaults = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();

        setTitle("Edit parameters");
        setLocationByPlatform(true);

        jTable1.setModel(new com.devoteam.srit.xmlloader.gui.model.ModelEditableParameters());
        jScrollPane1.setViewportView(jTable1);

        jButtonOK.setText("OK");
        jButtonOK.setEnabled(false);
        jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonOKActionPerformed(evt);
            }
        });

        jButtonDefaults.setText("Defaults");
        jButtonDefaults.setEnabled(false);
        jButtonDefaults.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDefaultsActionPerformed(evt);
            }
        });

        jButton1.setText("Cancel");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        jTree1.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jTree1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jTree1.setToggleClickCount(1);
        jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTree1ValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(jTree1);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup().addContainerGap()
                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 151,
                                org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                .add(layout.createSequentialGroup().add(jButtonDefaults)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(jButtonOK)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(jButton1))
                                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 405,
                                        Short.MAX_VALUE))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup().addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                .add(layout.createSequentialGroup()
                                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 320,
                                                Short.MAX_VALUE)
                                        .add(3, 3, 3))
                                .add(layout.createSequentialGroup()
                                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 294,
                                                Short.MAX_VALUE)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                                .add(jButton1).add(jButtonOK).add(jButtonDefaults))))
                        .addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonDefaultsActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonDefaultsActionPerformed
    {//GEN-HEADEREND:event_jButtonDefaultsActionPerformed
        this.elements.clear();
        for (Element e : elementsDefault) {
            this.elements.add(e.createCopy());
        }
        changeTable();
        this.jButtonOK.setEnabled(true);
        this.jButtonDefaults.setEnabled(false);
    }//GEN-LAST:event_jButtonDefaultsActionPerformed

    private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonOKActionPerformed
    {//GEN-HEADEREND:event_jButtonOKActionPerformed
        if (null != this.jTable1.getCellEditor())
            this.jTable1.getCellEditor().stopCellEditing();
        this.jButtonOK.setEnabled(false);
        this.jButtonDefaults.setEnabled(true);
        this.setVisible(false);
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                TesterGui.instance().reload(false);
                jButtonOK.setEnabled(false);
            }
        });
    }//GEN-LAST:event_jButtonOKActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton1ActionPerformed
    {//GEN-HEADEREND:event_jButton1ActionPerformed
        this.elements.clear();
        for (Element e : elementsOrigin)
            this.elements.add(e.createCopy());
        changeTable();
        this.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTree1ValueChanged
        changeTable();
    }//GEN-LAST:event_jTree1ValueChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonDefaults;
    private javax.swing.JButton jButtonOK;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTree jTree1;
    // End of variables declaration//GEN-END:variables
    private List<Element> elements = null;
    private List<Element> elementsOrigin = null;
    private List<Element> elementsDefault = null;
    private boolean valueChanged = false;

    // <editor-fold defaultstate="collapsed" desc=" User Code " >

    // private List<Element> elements;

    public void clear() {
        this.elements = null;
        this.elementsDefault = null;
        this.elementsOrigin = null;
        ((ModelEditableParameters) this.jTable1.getModel()).clear();
    }

    public void setReadOnly(boolean readOnly) {
        this.jTable1.setEnabled(readOnly);
        this.jButtonDefaults.setEnabled(readOnly);
        this.jButtonOK.setEnabled(readOnly);
    }

    public void fill(final List<Element> elts) {
        fill(elts, true);
    }

    public void fill(final List<Element> elts, boolean resetDefaults) {
        if (this.elements == null) {
            for (Element e : elts) {
                try {
                    String value = e.attributeValue("value");
                    if (null != value) {
                        e.attribute("value").setValue(parsing(value));
                    }
                } catch (Exception ee) {
                    GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE, ee,
                            "Error in editable parameters window hile parsing parameters value : ", e);
                }
            }

            this.elements = new LinkedList<Element>();
            elementsOrigin = new LinkedList<Element>();
            if (resetDefaults) {
                elementsDefault = new LinkedList<Element>();
                this.elements.clear();
                for (Element e : elts) {
                    this.elements.add(e.createCopy());
                    elementsDefault.add(e.createCopy());
                }
            } else {
                this.elements.clear();
                for (Element e : elts) {
                    this.elements.add(e.createCopy());
                }
            }

            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    doFill(elements);
                }
            });
        }
    }

    private String parsing(String string) throws ParameterException {
        if (null != string) {
            List<String> l = Tester.getInstance().getTest().getParameterPool().parse(string);
            if (l.isEmpty()) {
                string = "";
            } else {
                string = l.get(0);
            }
            return string;
        } else {
            return null;
        }

    }

    /**
     * Sets the tree data.
     *
     * @param elements
     */
    private void doFill(List<Element> elements) {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
        jTree1.setRootVisible(false);
        String key = null;
        for (Element e : elements) {
            if (e.attributeValue("name").contains(".")) {
                String name = e.attributeValue("name");
                DefaultMutableTreeNode eltNode = getExistingNode(name, root);
                if (eltNode == null) {
                    eltNode = new DefaultMutableTreeNode(name.substring(1, name.indexOf(".")));
                    if (key == null)
                        key = name.substring(0, name.indexOf("."));
                    name = name.substring(name.indexOf(".") + 1);
                    if (name.contains("."))
                        eltNode.add(getNodeChild(name));
                    root.add(eltNode);
                } else {
                    int max = 0;
                    DefaultMutableTreeNode depth = eltNode;
                    while (!depth.isRoot()) {
                        depth = (DefaultMutableTreeNode) depth.getParent();
                        max++;
                    }
                    for (int i = 0; i < max; i++)
                        name = name.substring(name.indexOf(".") + 1);
                    if (name.contains("."))
                        eltNode.add(getNodeChild(name));
                }
            }
        }
        if (root.getChildCount() == 0) {
            DefaultMutableTreeNode eltNode = new DefaultMutableTreeNode("Default");
            root.add(eltNode);
        }
        ((DefaultTreeModel) jTree1.getModel()).setRoot(root);
        ((DefaultTreeModel) jTree1.getModel()).reload();
        fillTable(getEltsForTable(key));
        this.jButtonOK.setEnabled(false);
    }

    /**
     * Return the child (and his child recursively) from the name of the parameter.
     *
     * @param name
     * @return
     */
    private DefaultMutableTreeNode getNodeChild(String name) {
        DefaultMutableTreeNode eltNode;
        if (name.substring(name.indexOf(".") + 1).contains(".")) {
            eltNode = new DefaultMutableTreeNode(name.substring(0, name.indexOf(".")));
            DefaultMutableTreeNode elmtNode = getNodeChild(name.substring(name.indexOf(".") + 1));
            eltNode.add(elmtNode);
        } else {
            eltNode = new DefaultMutableTreeNode(name.substring(0, name.indexOf(".")));
        }
        return eltNode;
    }

    /**
     * Get the existing node from the parameters's name.
     * It returns null if there is no interesting node.
     *
     * @param name - parameter name
     * @param root - root of the tree to analyse
     * @return
     */
    private DefaultMutableTreeNode getExistingNode(String name, DefaultMutableTreeNode root) {
        DefaultMutableTreeNode eltNode = null;
        String current;
        if (name.startsWith("["))
            name = name.substring(1);
        for (int i = 0, max = root.getChildCount(); i < max; i++) {
            current = (String) ((DefaultMutableTreeNode) root.getChildAt(i)).getUserObject();
            if (current.equalsIgnoreCase(name.substring(0, name.indexOf("."))))
                eltNode = getLastSameNode(name.substring(name.indexOf(".") + 1, name.length()),
                        (DefaultMutableTreeNode) root.getChildAt(i));
        }
        return eltNode;
    }

    /**
     * Get the deeper interesting node from the parameter's name.
     *
     * @param name - parameter name
     * @param root - root of the tree to analyse
     * @return
     */
    private DefaultMutableTreeNode getLastSameNode(String name, DefaultMutableTreeNode root) {
        DefaultMutableTreeNode eltNode = root;
        if (name.contains(".")) {
            for (int i = 0, max = root.getChildCount(); i < max; i++) {
                String current = (String) ((DefaultMutableTreeNode) root.getChildAt(i)).getUserObject();
                if (current.equalsIgnoreCase(name.substring(0, name.indexOf("."))))
                    eltNode = getLastSameNode(name.substring(name.indexOf(".") + 1),
                            (DefaultMutableTreeNode) root.getChildAt(i));
            }
        }
        return eltNode;
    }

    /**
     * update the table from the selected node in the tree
     *
     */
    private void changeTable() {
        if (jTree1.getSelectionPath() != null) {
            String key = jTree1.getSelectionPath().toString();
            fillTable(getEltsForTable(key));
        } else {
            List<Object> nodes = new ArrayList<Object>();
            TreeNode treeNode = ((DefaultMutableTreeNode) ((DefaultTreeModel) jTree1.getModel()).getRoot())
                    .getFirstChild();
            nodes.add(treeNode);
            treeNode = treeNode.getParent();
            while (treeNode != null) {
                nodes.add(0, treeNode);
                treeNode = treeNode.getParent();
            }

            String key = (new TreePath(nodes.toArray())).toString();
            fillTable(getEltsForTable(key));
        }
    }

    /**
     * Returns the elements concerned by the key (node selected in the tree)
     *
     * @param key - TreePath in string format
     * @return
     */
    private List<Element> getEltsForTable(String key) {
        if (key == null)
            return this.elements;
        if (key.contains("[root,"))
            key = key.substring(7, key.length() - 1); // 7 => '[root, '
        else
            key = key.substring(1, key.length() - 1);
        key = key.replaceAll(", ", ".");
        List<Element> dispElts = new LinkedList<Element>();
        for (Element e : this.elements) {
            if (e.attributeValue("name").contains(".")) {
                if (e.attributeValue("name").startsWith("[" + key + ".")) {
                    Element elt = e.createCopy();
                    elt.attribute("name").setValue(e.attributeValue("name").substring(key.length() + 2,
                            e.attributeValue("name").length() - 1));
                    dispElts.add(elt);
                }
            } else
                dispElts.add(e.createCopy());
        }
        return dispElts;
    }

    private void fillTable(final List<Element> elements) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                doFillTable(elements);
            }
        });
    }

    private void doFillTable(List<Element> elts) {
        ((ModelEditableParameters) this.jTable1.getModel()).fill(elts);
        if (!valueChanged)
            this.jButtonOK.setEnabled(false);
    }

    /**
     * Update the parameters from the changes of the user in the interface.
     *
     */
    private void apply() {
        this.apply(this.elements);
    }

    public void apply(List<Element> elts) {
        if (elts != null) {
            this.jButtonOK.setEnabled(true);
            valueChanged = true;
            String key = "";
            if (jTree1.getSelectionPath() == null) {
                for (Element e : elts) {
                    Iterator<Vector> iterator = (Iterator<Vector>) ((ModelEditableParameters) this.jTable1
                            .getModel()).getElements().iterator();
                    while (iterator.hasNext()) {
                        Vector pair = iterator.next();
                        String name = (String) pair.get(0);
                        if (!name.startsWith("["))
                            name = "[" + name + "]";
                        if (e.attributeValue("name").equalsIgnoreCase(name)) {
                            e.attribute("value").setValue((String) pair.get(2));
                        }
                    }
                }
            } else {
                key = jTree1.getSelectionPath().toString();
                key = key.substring(7, key.length() - 1); // 7 => '[root, '
                key = key.replaceAll(", ", ".");
                for (Element e : elts) {
                    if (e.attributeValue("name").contains(".")) {
                        Iterator<Vector> iterator = (Iterator<Vector>) ((ModelEditableParameters) this.jTable1
                                .getModel()).getElements().iterator();
                        while (iterator.hasNext()) {
                            Vector pair = iterator.next();
                            if (e.attributeValue("name").equalsIgnoreCase("[" + key + "." + pair.get(0) + "]")) {
                                e.attribute("value").setValue((String) pair.get(2));
                            }
                        }

                    } else {
                        Iterator<Vector> iterator = (Iterator<Vector>) ((ModelEditableParameters) this.jTable1
                                .getModel()).getElements().iterator();
                        while (iterator.hasNext()) {
                            Vector pair = iterator.next();
                            String name = (String) pair.get(0);
                            if (!name.startsWith("["))
                                name = "[" + name + "]";
                            if (e.attributeValue("name").equalsIgnoreCase(name)) {
                                e.attribute("value").setValue((String) pair.get(2));
                            }
                        }
                    }
                }
            }
        }
    }

    public void tableChanged(TableModelEvent e) {
        this.apply();
    }

    public String getParameterValue(String name) {
        if (null != this.elements) {
            for (Element elts : this.elements) {
                if (name.equalsIgnoreCase(elts.attributeValue("name"))) {
                    return elts.attributeValue("value");
                }
            }
            return null;
        } else {
            return null;
        }
    }

    // </editor-fold>

}