Example usage for org.eclipse.jface.dialogs MessageDialog openQuestion

List of usage examples for org.eclipse.jface.dialogs MessageDialog openQuestion

Introduction

In this page you can find the example usage for org.eclipse.jface.dialogs MessageDialog openQuestion.

Prototype

public static boolean openQuestion(Shell parent, String title, String message) 

Source Link

Document

Convenience method to open a simple Yes/No question dialog.

Usage

From source file:cl.utfsm.acs.acg.gui.actions.SaveToCDBActionDelegate.java

License:Open Source License

@Override
public void run(IAction action) {

    if (_window == null)
        return;//  www .j  av a 2  s . co  m

    boolean confirmSave;
    confirmSave = MessageDialog.openQuestion(_window.getShell(), "Save to CDB",
            "Save the new contents to the CDB?");

    if (!confirmSave)
        return;

    final Display display = _window.getShell().getDisplay();

    new Thread(new Runnable() {

        public void run() {

            display.syncExec(new Runnable() {
                public void run() {
                    // Disable all views
                    IViewReference[] views = _window.getActivePage().getViewReferences();
                    for (int i = 0; i < views.length; i++) {
                        if (views[i].getView(false) instanceof IMyViewPart)
                            ((IMyViewPart) views[i].getView(false)).setEnabled(false);
                    }
                }
            });

            // Save and reload information from the CDB
            AlarmSystemManager.getInstance().saveToCDB();

            display.asyncExec(new Runnable() {
                public void run() {
                    // Enable all views, and reload their contents
                    IViewReference[] views = _window.getActivePage().getViewReferences();
                    for (int i = 0; i < views.length; i++) {
                        if (views[i].getView(false) instanceof IMyViewPart) {
                            IMyViewPart view = ((IMyViewPart) views[i].getView(false));
                            view.setEnabled(true);
                            view.refreshContents();
                        }
                    }
                }
            });

        }

    }).start();

}

From source file:cl.utfsm.acs.acg.gui.AlarmsView.java

License:Open Source License

private void createViewWidgets(Composite parent) {
    Listener hoverTree = new Listener() {
        public void handleEvent(Event event) {
            Point coords = new Point(event.x, event.y);
            TreeItem it = _tree.getItem(coords);
            String tooltip = "";
            if (it == null) {
                _tree.setToolTipText(tooltip);
                return;
            }/*from  w w w .j a va  2 s  .  c om*/
            NodeType type = (NodeType) it.getData();
            switch (type) {
            case FAULT_FAMILY: {
                tooltip = _alarmManager.getFaultFamily(it.getText()).getName();
                break;
            }
            case FAULT_CODE_DATA: {
                tooltip = _alarmManager
                        .getFaultCode(it.getParentItem().getParentItem().getText(), new Integer(it.getText()))
                        .getProblemDescription();
                break;
            }
            case FAULT_MEMBER_DATA: {
                tooltip = _alarmManager
                        .getFaultMember(it.getParentItem().getParentItem().getText(), it.getText()).getName();
                break;
            }
            }
            _tree.setToolTipText(tooltip);
        }
    };
    _deleteElement = new Listener() {
        public void handleEvent(Event event) {
            boolean choice = MessageDialog.openQuestion(AlarmsView.this.getViewSite().getShell(),
                    "Confirmation", "Are you sure you want to delete this element");
            if (choice == true) {

                TreeItem sel = null;
                if (_tree.getSelection() == null || _tree.getSelection().length == 0)
                    return;
                NodeType type = (NodeType) _tree.getSelection()[0].getData();
                if (type == NodeType.FAULT_CODE_LIST || type == NodeType.FAULT_MEMBER_LIST)
                    return;
                String alarm = _tree.getSelection()[0].getText();
                try {
                    if (type == NodeType.FAULT_FAMILY)
                        _alarmManager.deleteFaultFamily(_alarmManager.getFaultFamily(alarm));
                    else if (type == NodeType.FAULT_CODE_DATA) {
                        String ff = _tree.getSelection()[0].getParentItem().getParentItem().getText();
                        _alarmManager.deleteFaultCode(_alarmManager.getFaultFamily(ff),
                                _alarmManager.getFaultCode(ff, new Integer(alarm).intValue()));
                    } else if (type == NodeType.FAULT_MEMBER_DATA) {
                        String ff = _tree.getSelection()[0].getParentItem().getParentItem().getText();
                        _alarmManager.deleteFaultMember(_alarmManager.getFaultFamily(ff),
                                _alarmManager.getFaultMember(ff, alarm));
                    } else if (type == NodeType.FAULT_MEMBER_DEFAULT) {
                        String ff = _tree.getSelection()[0].getParentItem().getParentItem().getText();
                        _alarmManager.setFaultMemberDefault(_alarmManager.getFaultFamily(ff), null);
                    }
                } catch (IllegalOperationException e) {
                    ErrorDialog error = new ErrorDialog(AlarmsView.this.getViewSite().getShell(),
                            "Cannot delete the item", e.getMessage(),
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                    return;
                } catch (NullPointerException e) {
                    ErrorDialog error = new ErrorDialog(AlarmsView.this.getViewSite().getShell(),
                            "Cannot delete the item", e.getMessage(),
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                    return;
                }
                if (type != NodeType.FAULT_FAMILY) {
                    sel = _tree.getSelection()[0].getParentItem();
                    TreeItem tff = sel.getParentItem();
                    FaultFamily fft = _alarmManager.getFaultFamily(tff.getText());
                    if (fft.getFaultCodeCount() == 0
                            || (fft.getFaultMemberCount() == 0 && fft.getFaultMemberDefault() == null)) {
                        sel.setForeground(new Color(sel.getDisplay(), 255, 0, 0));
                        tff.setForeground(new Color(tff.getDisplay(), 255, 0, 0));
                    } else {
                        sel.setForeground(new Color(sel.getDisplay(), 0, 0, 0));
                        tff.setForeground(new Color(tff.getDisplay(), 0, 0, 0));
                    }
                    _tree.getSelection()[0].dispose();
                    _tree.setSelection(sel);
                    Event e = new Event();
                    _tree.notifyListeners(SWT.Selection, e);
                } else {
                    _tree.getSelection()[0].dispose();
                    if (_tree.getItemCount() > 0)
                        _tree.setSelection(_tree.getItems()[0]);
                    Event e = new Event();
                    _tree.notifyListeners(SWT.Selection, e);
                }
            }
        }

    };

    _addFaultMember = new Listener() {
        public void handleEvent(Event event) {
            TreeItem tmp = _tree.getSelection()[0];
            TreeItem tmp2 = null;
            while (tmp != null) {
                tmp2 = tmp;
                tmp = tmp.getParentItem();
            }
            String ff = tmp2.getText();
            InputDialog dialog = new InputDialog(AlarmsView.this.getViewSite().getShell(), "New Fault Member",
                    "Enter the Fault Member name", null, new IInputValidator() {
                        public String isValid(String newText) {
                            if (newText.trim().compareTo("") == 0)
                                return "The name is empty";
                            return null;
                        }
                    });
            dialog.setBlockOnOpen(true);
            dialog.open();
            int returnCode = dialog.getReturnCode();
            if (returnCode == InputDialog.OK) {
                FaultMember newFaultMember = new FaultMember();
                newFaultMember.setName(dialog.getValue());
                try {
                    _alarmManager.addFaultMember(_alarmManager.getFaultFamily(ff), newFaultMember);
                } catch (IllegalOperationException e) {
                    ErrorDialog error = new ErrorDialog(AlarmsView.this.getViewSite().getShell(),
                            "Cannot add the new Fault Member", e.getMessage(),
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                    return;
                } catch (NullPointerException e) {
                    ErrorDialog error = new ErrorDialog(AlarmsView.this.getViewSite().getShell(),
                            "Cannot add the new Fault Member", e.getMessage(),
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                    return;
                }
                sortFaultFamilyList();
                selectElementFromTree(ff, dialog.getValue(), null);
            }
        }
    };

    _addFaultMemberDefault = new Listener() {
        public void handleEvent(Event event) {
            TreeItem tmp = _tree.getSelection()[0];
            TreeItem tmp2 = null;
            while (tmp != null) {
                tmp2 = tmp;
                tmp = tmp.getParentItem();
            }
            String ff = tmp2.getText();
            FaultMemberDefault newFaultMemberDefault = new FaultMemberDefault();
            try {
                _alarmManager.setFaultMemberDefault(_alarmManager.getFaultFamily(ff), newFaultMemberDefault);
            } catch (IllegalOperationException e) {
                ErrorDialog error = new ErrorDialog(AlarmsView.this.getViewSite().getShell(),
                        "Cannot add the new Default Fault Member", e.getMessage(),
                        new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                error.setBlockOnOpen(true);
                error.open();
                return;
            } catch (NullPointerException e) {
                ErrorDialog error = new ErrorDialog(AlarmsView.this.getViewSite().getShell(),
                        "Cannot add the new Default Fault Member", e.getMessage(),
                        new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                error.setBlockOnOpen(true);
                error.open();
                return;
            }
            sortFaultFamilyList();
            selectElementFromTree(ff, "Default Member", null);
        }
    };

    _addFaultCode = new Listener() {
        public void handleEvent(Event event) {
            TreeItem tmp = _tree.getSelection()[0];
            TreeItem tmp2 = null;
            while (tmp != null) {
                tmp2 = tmp;
                tmp = tmp.getParentItem();
            }
            String ff = tmp2.getText();
            InputDialog dialog = new InputDialog(AlarmsView.this.getViewSite().getShell(), "New Fault Code",
                    "Enter the Fault Code Value", null, new IInputValidator() {
                        public String isValid(String newText) {
                            if (newText.trim().compareTo("") == 0)
                                return "The value is empty";
                            try {
                                new Integer(newText);
                            } catch (NumberFormatException e) {
                                return "The value is not a number";
                            }
                            return null;
                        }
                    });
            dialog.setBlockOnOpen(true);
            dialog.open();
            int returnCode = dialog.getReturnCode();
            if (returnCode == InputDialog.OK) {
                FaultCode newFaultCode = new FaultCode();
                newFaultCode.setValue(new Integer(dialog.getValue()).intValue());
                try {
                    _alarmManager.addFaultCode(_alarmManager.getFaultFamily(ff), newFaultCode);
                } catch (IllegalOperationException e) {
                    ErrorDialog error = new ErrorDialog(AlarmsView.this.getViewSite().getShell(),
                            "Cannot add the new Fault Code", e.getMessage(),
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                    return;
                } catch (NullPointerException e) {
                    ErrorDialog error = new ErrorDialog(AlarmsView.this.getViewSite().getShell(),
                            "Cannot add the new Fault Code", e.getMessage(),
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                    return;
                }
                sortFaultFamilyList();
                selectElementFromTree(ff, null, dialog.getValue());
            }
        }
    };

    _addFaultFamily = new Listener() {
        public void handleEvent(Event event) {
            InputDialog dialog = new InputDialog(AlarmsView.this.getViewSite().getShell(), "New Alarm",
                    "Enter the Fault Family name", null, new IInputValidator() {
                        public String isValid(String newText) {
                            if (newText.trim().compareTo("") == 0)
                                return "The name is empty";
                            return null;
                        }
                    });
            dialog.setBlockOnOpen(true);
            dialog.open();
            int returnCode = dialog.getReturnCode();
            if (returnCode == InputDialog.OK) {
                FaultFamily newAlarm = new FaultFamily();
                newAlarm.setName(dialog.getValue());
                try {
                    _alarmManager.addFaultFamily(newAlarm);
                } catch (IllegalOperationException e) {
                    ErrorDialog error = new ErrorDialog(AlarmsView.this.getViewSite().getShell(),
                            "Cannot add the new Alarm", e.getMessage(),
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                } catch (NullPointerException e) {
                    ErrorDialog error = new ErrorDialog(AlarmsView.this.getViewSite().getShell(),
                            "Cannot add the new Alarm", e.getMessage(),
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                    return;
                }
                sortFaultFamilyList();
                selectElementFromTree(dialog.getValue(), null, null);
            }
        }
    };

    _sash = new SashForm(parent, SWT.NONE);
    _sash.setLayout(new FillLayout());

    _alarmsComp = new Composite(_sash, SWT.NONE);
    GridLayout layout = new GridLayout();
    layout.numColumns = 1;
    _alarmsComp.setLayout(layout);

    _treeGroup = new Group(_alarmsComp, SWT.SHADOW_ETCHED_IN);
    GridData gd = new GridData();
    gd.horizontalAlignment = SWT.FILL;
    gd.verticalAlignment = SWT.FILL;
    gd.grabExcessHorizontalSpace = true;
    gd.grabExcessVerticalSpace = true;
    _treeGroup.setLayoutData(gd);
    GridLayout gl = new GridLayout();
    gl.numColumns = 1;
    _treeGroup.setLayout(gl);
    _treeGroup.setText("Fault Family List");

    /* The tree used to list the FF, FM and FCs */
    _tree = new Tree(_treeGroup, SWT.VIRTUAL | SWT.BORDER);
    gd = new GridData();
    gd.verticalAlignment = SWT.FILL;
    gd.horizontalAlignment = SWT.FILL;
    gd.grabExcessVerticalSpace = true;
    gd.grabExcessHorizontalSpace = true;
    _tree.setLayoutData(gd);
    //Menu treePopUp = new Menu(parent, SWT.POP_UP);
    Menu treePopUp = new Menu(parent);
    _tree.setMenu(treePopUp);
    treePopUp.addListener(SWT.Show, new Listener() {
        public void handleEvent(Event e) {
            //Point point = new Point(e.x, e.y);
            //TreeItem sel = _tree.getItem(point);
            TreeItem[] sel = _tree.getSelection();
            Menu treePopUp = _tree.getMenu();
            MenuItem[] items = treePopUp.getItems();
            for (int i = 0; i < items.length; i++)
                items[i].dispose();
            MenuItem mitem;
            if (sel == null || sel.length == 0) {
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Add Fault Family");
                mitem.addListener(SWT.Selection, _addFaultFamily);
                return;
            }
            NodeType type = (NodeType) sel[0].getData();
            switch (type) {
            case FAULT_FAMILY:
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Add Fault Family");
                mitem.addListener(SWT.Selection, _addFaultFamily);
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Delete Fault Family");
                mitem.addListener(SWT.Selection, _deleteElement);
                break;
            case FAULT_CODE_LIST:
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Add Fault Code");
                mitem.addListener(SWT.Selection, _addFaultCode);
                break;
            case FAULT_CODE_DATA:
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Add Fault Code");
                mitem.addListener(SWT.Selection, _addFaultCode);
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Delete Fault Code");
                mitem.addListener(SWT.Selection, _deleteElement);
                break;
            case FAULT_MEMBER_LIST:
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Add Fault Member");
                mitem.addListener(SWT.Selection, _addFaultMember);
                if (_alarmManager.getFaultFamily(sel[0].getParentItem().getText())
                        .getFaultMemberDefault() == null) {
                    mitem = new MenuItem(treePopUp, SWT.PUSH);
                    mitem.setText("Add Default Fault Member");
                    mitem.addListener(SWT.Selection, _addFaultMemberDefault);
                }
                break;
            case FAULT_MEMBER_DATA:
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Add Fault Member");
                mitem.addListener(SWT.Selection, _addFaultMember);
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Delete Fault Member");
                mitem.addListener(SWT.Selection, _deleteElement);
                break;
            case FAULT_MEMBER_DEFAULT:
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Delete Default Fault Member");
                mitem.addListener(SWT.Selection, _deleteElement);
                break;
            default:
                for (int i = 0; i < items.length; i++)
                    items[i].dispose();
                break;
            }
        }
    });
    _tree.addSelectionListener(new SelectionListener() {

        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);
        }

        public void widgetSelected(SelectionEvent e) {
            TreeItem[] tmp = ((Tree) e.widget).getSelection();
            if (tmp == null || tmp.length == 0) {
                _FFgroup.setVisible(false);
                ((GridData) _FFgroup.getLayoutData()).exclude = true;
                _FMgroup.setVisible(false);
                ((GridData) _FMgroup.getLayoutData()).exclude = true;
                _FCgroup.setVisible(false);
                ((GridData) _FCgroup.getLayoutData()).exclude = true;
                _FMDgroup.setVisible(false);
                ((GridData) _FMDgroup.getLayoutData()).exclude = true;
                _FCFMgroup.setVisible(false);
                ((GridData) _FCFMgroup.getLayoutData()).exclude = true;
                return;
            }

            TreeItem item = tmp[0];
            NodeType type = (NodeType) item.getData();

            /* Delete the label the first time we select something */
            Control c = _compInitial.getChildren()[0];
            if (c instanceof Label) {
                c.dispose();
                _compInitial.layout();
                c = _compInitial.getChildren()[0];
            }

            if (type == NodeType.FAULT_FAMILY) {
                _FFgroup.setVisible(true);
                ((GridData) _FFgroup.getLayoutData()).exclude = false;
                _FMgroup.setVisible(false);
                ((GridData) _FMgroup.getLayoutData()).exclude = true;
                _FCgroup.setVisible(false);
                ((GridData) _FCgroup.getLayoutData()).exclude = true;
                _FMDgroup.setVisible(false);
                ((GridData) _FMDgroup.getLayoutData()).exclude = true;
                _FCFMgroup.setVisible(false);
                ((GridData) _FCFMgroup.getLayoutData()).exclude = true;

                //_FFgroup.moveAbove(c);
                fillFFWidgets(item.getText());
            } else if (type == NodeType.FAULT_CODE_LIST) {
                _FFgroup.setVisible(false);
                ((GridData) _FFgroup.getLayoutData()).exclude = true;
                _FMgroup.setVisible(false);
                ((GridData) _FMgroup.getLayoutData()).exclude = true;
                _FCgroup.setVisible(false);
                ((GridData) _FCgroup.getLayoutData()).exclude = true;
                _FMDgroup.setVisible(false);
                ((GridData) _FMDgroup.getLayoutData()).exclude = true;
                _FCFMgroup.setVisible(true);
                ((GridData) _FCFMgroup.getLayoutData()).exclude = false;
                fillFCFMWidgets();
            } else if (type == NodeType.FAULT_CODE_DATA) {
                _FFgroup.setVisible(false);
                ((GridData) _FFgroup.getLayoutData()).exclude = true;
                _FMgroup.setVisible(false);
                ((GridData) _FMgroup.getLayoutData()).exclude = true;
                _FCgroup.setVisible(true);
                ((GridData) _FCgroup.getLayoutData()).exclude = false;
                _FMDgroup.setVisible(false);
                ((GridData) _FMDgroup.getLayoutData()).exclude = true;
                _FCFMgroup.setVisible(false);
                ((GridData) _FCFMgroup.getLayoutData()).exclude = true;

                //_FCgroup.moveAbove(c);
                fillFCWidgets(Integer.parseInt(item.getText()), item.getParentItem().getParentItem().getText());
            } else if (type == NodeType.FAULT_MEMBER_LIST) {
                _FFgroup.setVisible(false);
                ((GridData) _FFgroup.getLayoutData()).exclude = true;
                _FMgroup.setVisible(false);
                ((GridData) _FMgroup.getLayoutData()).exclude = true;
                _FCgroup.setVisible(false);
                ((GridData) _FCgroup.getLayoutData()).exclude = true;
                _FMDgroup.setVisible(false);
                ((GridData) _FMDgroup.getLayoutData()).exclude = true;
                _FCFMgroup.setVisible(true);
                ((GridData) _FCFMgroup.getLayoutData()).exclude = false;
                fillFCFMWidgets();
            } else if (type == NodeType.FAULT_MEMBER_DATA) {
                _FFgroup.setVisible(false);
                ((GridData) _FFgroup.getLayoutData()).exclude = true;
                _FMgroup.setVisible(true);
                ((GridData) _FMgroup.getLayoutData()).exclude = false;
                _FCgroup.setVisible(false);
                ((GridData) _FCgroup.getLayoutData()).exclude = true;
                _FMDgroup.setVisible(false);
                ((GridData) _FMDgroup.getLayoutData()).exclude = true;
                _FCFMgroup.setVisible(false);
                ((GridData) _FCFMgroup.getLayoutData()).exclude = true;

                //_FMgroup.moveAbove(c);
                fillFMWidgets(item.getText(), item.getParentItem().getParentItem().getText());
            } else if (type == NodeType.FAULT_MEMBER_DEFAULT) {
                _FFgroup.setVisible(false);
                ((GridData) _FFgroup.getLayoutData()).exclude = true;
                _FMgroup.setVisible(false);
                ((GridData) _FMgroup.getLayoutData()).exclude = true;
                _FCgroup.setVisible(false);
                ((GridData) _FCgroup.getLayoutData()).exclude = true;
                _FMDgroup.setVisible(true);
                ((GridData) _FMDgroup.getLayoutData()).exclude = false;
                _FCFMgroup.setVisible(false);
                ((GridData) _FCFMgroup.getLayoutData()).exclude = true;

                fillFMDWidgets(item.getParentItem().getParentItem().getText());
            }
            _compInitial.layout();
        }

    });
    _tree.addListener(SWT.MouseHover, hoverTree);

    _alarmsButtonsComp = new Composite(_alarmsComp, SWT.NONE);
    layout = new GridLayout();
    layout.numColumns = 2;
    _alarmsButtonsComp.setLayout(layout);

    _addAlarmButton = new Button(_alarmsButtonsComp, SWT.None);
    _addAlarmButton.setText("Add");
    _addAlarmButton.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ADD));

    _deleteAlarmButton = new Button(_alarmsButtonsComp, SWT.None);
    _deleteAlarmButton.setText("Delete");
    _deleteAlarmButton
            .setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_ETOOL_DELETE));

    _addAlarmButton.addListener(SWT.Selection, _addFaultFamily);

    _deleteAlarmButton.addListener(SWT.Selection, _deleteElement);

    /* Top widget of the right side */
    _compInitial = new Composite(_sash, SWT.SHADOW_ETCHED_IN);
    _compInitial.setLayout(new GridLayout());

    new Label(_compInitial, SWT.NONE).setText("Select an element");

    /* FF/FM/FC Details */
    createFFWidgets();
    createFCWidgets();
    createFMWidgets();
    createFMDWidgets();
    createFCFMWidgets();

    /* At the beginning we only show a label */
    _FFgroup.setVisible(false);
    _FCgroup.setVisible(false);
    _FMgroup.setVisible(false);
    _FMDgroup.setVisible(false);
    _FCFMgroup.setVisible(false);

    _sash.setWeights(new int[] { 3, 5 });
}

From source file:cl.utfsm.acs.acg.gui.ApplicationWorkbenchAdvisor.java

License:Open Source License

public boolean preShutdown() {
    return MessageDialog.openQuestion(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
            "Exit Application", "Do you want to close the Application? All unsaved changes will be lost.");
}

From source file:cl.utfsm.acs.acg.gui.CategoriesView.java

License:Open Source License

private void createViewWidgets(Composite parent) {
    SashForm sash = new SashForm(parent, SWT.HORIZONTAL);
    sash.setLayout(new FillLayout());

    /* Left pane */
    Composite categoriesComp = new Composite(sash, SWT.NONE);
    GridLayout layout = new GridLayout();
    layout.numColumns = 1;/*from  ww  w  .  j  a va2s  .c o m*/
    categoriesComp.setLayout(layout);

    _listGroup = new Group(categoriesComp, SWT.SHADOW_ETCHED_IN);
    GridData gd = new GridData();
    gd.horizontalAlignment = SWT.FILL;
    gd.verticalAlignment = SWT.FILL;
    gd.grabExcessHorizontalSpace = true;
    gd.grabExcessVerticalSpace = true;
    _listGroup.setLayoutData(gd);
    GridLayout gl = new GridLayout();
    gl.numColumns = 1;
    _listGroup.setLayout(gl);
    _listGroup.setText("Categories List");

    _categoriesList = new List(_listGroup, SWT.BORDER | SWT.V_SCROLL);
    _categoriesList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    _categoriesList.addSelectionListener(new SelectionListener() {
        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);
        }

        public void widgetSelected(SelectionEvent e) {
            Control c = _compInitial.getChildren()[0];
            if (c instanceof Label) {
                c.dispose();
            }
            _comp.setVisible(true);
            _comp.layout();

            /* Fill with the contents of the selected category */
            /* The default category is stored as the data of the _categoryList */
            /* and is shown with a "*" in the list */
            if (_categoriesList.getSelection() == null || _categoriesList.getSelection().length == 0) {
                _comp.setVisible(false);
                _comp.layout();
                return;
            }
            String categoryName = _categoriesList.getSelection()[0];
            if (categoryName.startsWith("*"))
                fillCategoryInfo((String) _categoriesList.getData());
            else
                fillCategoryInfo(categoryName);
            if (_ffList.getItemCount() == 0)
                _errorMessageLabel.setText("You have to select at least one Fault Family");
        }
    });

    /* Add and remove buttons */
    Composite categoriesButtonsComp = new Composite(categoriesComp, SWT.NONE);
    layout = new GridLayout();
    layout.numColumns = 2;
    categoriesButtonsComp.setLayout(layout);
    categoriesButtonsComp.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));

    _addCategoryButton = new Button(categoriesButtonsComp, SWT.None);
    _addCategoryButton.setText("Add");
    _addCategoryButton
            .setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ADD));

    _deleteCategoryButton = new Button(categoriesButtonsComp, SWT.None);
    _deleteCategoryButton.setText("Delete");
    _deleteCategoryButton
            .setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_ETOOL_DELETE));

    Listener addCategory = new Listener() {
        public void handleEvent(Event event) {
            InputDialog dialog = new InputDialog(CategoriesView.this.getViewSite().getShell(), "New Category",
                    "Enter the Category name", null, new IInputValidator() {
                        public String isValid(String newText) {
                            if (newText.trim().compareTo("") == 0)
                                return "The name is empty";
                            return null;
                        }
                    });
            dialog.setBlockOnOpen(true);
            dialog.open();
            int returnCode = dialog.getReturnCode();
            if (returnCode == InputDialog.OK) {
                if (_categoryManager.getCategoryByPath(dialog.getValue()) != null) {
                    ErrorDialog error = new ErrorDialog(CategoriesView.this.getViewSite().getShell(),
                            "Category already exist",
                            "The Category " + dialog.getValue()
                                    + " already exists in the current configuration",
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", "The Category " + dialog.getValue()
                                    + " already exists in the current configuration"),
                            IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                    return;
                }
                Category newCategory = new Category();
                newCategory.setPath(dialog.getValue());
                InputDialog dialog2 = new InputDialog(CategoriesView.this.getViewSite().getShell(),
                        "Category Description", "Enter the Description for the Category", null,
                        new IInputValidator() {
                            public String isValid(String newText) {
                                if (newText.trim().compareTo("") == 0)
                                    return "The name is empty";
                                return null;
                            }
                        });
                dialog2.setBlockOnOpen(true);
                dialog2.open();
                String description = dialog2.getValue();
                if (description == null)
                    return;
                if (returnCode == InputDialog.OK)
                    newCategory.setDescription(description);

                java.util.List<String> ffnames = sortFullFaultFamilyList();

                ListSelectionDialog dialog3 = new ListSelectionDialog(
                        PlatformUI.getWorkbench().getDisplay().getActiveShell(), ffnames,
                        new ArrayContentProvider(), new LabelProvider(), "");

                dialog3.setTitle("Fault Family Selection");
                dialog3.setMessage("List of Fault Families");
                dialog3.setBlockOnOpen(true);
                dialog3.open();

                Object ffselected[] = dialog3.getResult();
                if (ffselected == null)
                    return;
                if (ffselected.length == 0) {
                    try {
                        _categoryManager.addCategory(newCategory);
                    } catch (IllegalOperationException e) {
                        ErrorDialog error = new ErrorDialog(CategoriesView.this.getViewSite().getShell(),
                                "Category already exist",
                                "The Category " + dialog.getValue()
                                        + " already exists in the current configuration",
                                new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                        error.setBlockOnOpen(true);
                        error.open();
                        return;
                    }
                } else {
                    Alarms alarms = new Alarms();
                    for (int i = 0; i < ffselected.length; i++) {
                        try {
                            alarms.addFaultFamily(
                                    _alarmManager.getFaultFamily((String) ffselected[i]).getName());
                            //alarms.setFaultFamily(i, (String)ffselected[i]);                       
                        } catch (NullPointerException e) {
                        }
                        newCategory.setAlarms(alarms);
                    }
                    try {
                        _categoryManager.addCategory(newCategory);
                    } catch (IllegalOperationException e) {
                        ErrorDialog error = new ErrorDialog(CategoriesView.this.getViewSite().getShell(),
                                "Category already exist",
                                "The Category " + dialog.getValue()
                                        + " already exists in the current configuration",
                                new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                        error.setBlockOnOpen(true);
                        error.open();
                        return;
                    }
                }
                String[] items = new String[1];
                items[0] = dialog.getValue();
                refreshContents();
                _categoriesList.setSelection(items);
                Event e = new Event();
                _categoriesList.notifyListeners(SWT.Selection, e);
                IWorkbenchWindow _window = getViewSite().getWorkbenchWindow();
                IViewReference[] views = _window.getActivePage().getViewReferences();
                IMyViewPart view = ((IMyViewPart) views[3].getView(false));
                //view.refreshContents();
                view.fillWidgets();
                if (_ffList.getItemCount() == 0)
                    _errorMessageLabel.setText("You have to select at least one Fault Family");
            } else
                return;
        }
    };
    _addCategoryButton.addListener(SWT.Selection, addCategory);
    Listener deleteCategory = new Listener() {
        public void handleEvent(Event event) {
            boolean choice = MessageDialog.openQuestion(CategoriesView.this.getViewSite().getShell(),
                    "Confirmation", "Are you sure you want to delete this Category");
            if (choice == true) {
                String tmp[] = _categoriesList.getSelection();
                if (tmp == null || tmp.length == 0) {
                    ErrorDialog error = new ErrorDialog(CategoriesView.this.getViewSite().getShell(),
                            "Empty selection", "There are no Categories selected to be deleted",
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", ""), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                    return;
                }
                String category = tmp[0];
                if (category.startsWith("*")) {
                    ErrorDialog error = new ErrorDialog(CategoriesView.this.getViewSite().getShell(),
                            "Cannot delete Category", "The Category cannot be deleted",
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg",
                                    "There must be one default category. Please select a different one before removing this category."),
                            IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                    return;
                }
                try {
                    _categoryManager.deleteCategory(_categoryManager.getCategoryByPath(category));
                } catch (IllegalOperationException e) {
                    ErrorDialog error = new ErrorDialog(CategoriesView.this.getViewSite().getShell(),
                            "Cannot delete Category", "The Category cannot be deleted",
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                    return;
                }
                String[] items = null;
                if (_categoriesList.getSelection() != null && _categoriesList.getSelection().length != 0) {
                    items = _categoriesList.getSelection();
                    refreshContents();
                    if (items == null)
                        if (_categoriesList.getItemCount() > 0)
                            _categoriesList.setSelection(0);
                } else
                    _categoriesList.setSelection(items);
                Event e = new Event();
                _categoriesList.notifyListeners(SWT.Selection, e);
                IWorkbenchWindow _window = getViewSite().getWorkbenchWindow();
                IViewReference[] views = _window.getActivePage().getViewReferences();
                IMyViewPart view = ((IMyViewPart) views[3].getView(false));
                //view.refreshContents();
                view.fillWidgets();
            }
        }
    };
    _deleteCategoryButton.addListener(SWT.Selection, deleteCategory);

    /* To delete a FF from a given Category */
    Listener deleteFaultFamily = new Listener() {
        public void handleEvent(Event event) {
            Category c = _categoryManager.getCategoryByPath(_pathText.getText());
            try {
                String[] ff = c.getAlarms().getFaultFamily();
                Alarms alarms = new Alarms();
                String[] temp = _ffList.getSelection();
                //int j = 0;
                for (int i = 0; i < ff.length; i++) {
                    if (ff[i].compareTo(temp[0]) == 0) {
                        _ffList.remove(temp[0]);
                        c.getAlarms().removeFaultFamily(ff[i]);
                    } else {
                        alarms.addFaultFamily(ff[i]);
                        //alarms.setFaultFamily(j, ff[i]);
                        //j++;
                    }
                }
                c.setAlarms(alarms);
                _categoryManager.updateCategory(c, c);
                if (_ffList.getItemCount() == 0)
                    _errorMessageLabel.setText("You have to select at least one Fault Family");
                IWorkbenchWindow _window = getViewSite().getWorkbenchWindow();
                IViewReference[] views = _window.getActivePage().getViewReferences();
                IMyViewPart view = ((IMyViewPart) views[3].getView(false));
                //view.refreshContents();
                view.fillWidgets();
                boolean inUse = false;
                boolean def = false;
                String defCat = "";
                for (Category cat : _categoryManager.getAllCategories()) {
                    String[] ffs = cat.getAlarms().getFaultFamily();
                    for (String tff : ffs) {
                        if (tff.compareTo(temp[0]) == 0)
                            inUse = true;
                    }
                    if (cat.getIsDefault()) {
                        def = true;
                        defCat = cat.getPath();
                    }
                }
                if (!inUse) {
                    String msg;
                    if (def)
                        msg = "Default category: " + defCat;
                    else
                        msg = "No default category";
                    ErrorDialog error = new ErrorDialog(CategoriesView.this.getViewSite().getShell(),
                            "Fault Family isn't in any Categoty",
                            "The Fault Family is not part of any Category",
                            new Status(IStatus.WARNING, "cl.utfsm.acs.acg", "The Fault Family " + temp[0]
                                    + " is not part of any Category (" + msg + ")"),
                            IStatus.WARNING);
                    error.setBlockOnOpen(true);
                    error.open();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };

    /* To delete all FF from a given Category */
    Listener deleteAllFaultFamily = new Listener() {
        public void handleEvent(Event event) {
            Category c = _categoryManager.getCategoryByPath(_pathText.getText());
            try {
                String[] ff = c.getAlarms().getFaultFamily();
                Alarms alarms = new Alarms();
                for (int i = 0; i < ff.length; i++) {
                    _ffList.remove(ff[i]);
                    c.getAlarms().removeFaultFamily(ff[i]);
                }
                c.setAlarms(alarms);
                _categoryManager.updateCategory(c, c);
                IWorkbenchWindow _window = getViewSite().getWorkbenchWindow();
                IViewReference[] views = _window.getActivePage().getViewReferences();
                IMyViewPart view = ((IMyViewPart) views[3].getView(false));
                //view.refreshContents();
                view.fillWidgets();
                java.util.List<String> ffList = new ArrayList<String>();
                boolean def = false;
                String defCat = "";
                for (String cff : ff) {
                    Boolean inUse = false;
                    for (Category cat : _categoryManager.getAllCategories()) {
                        String[] ffs = cat.getAlarms().getFaultFamily();
                        for (String tff : ffs) {
                            if (tff.compareTo(cff) == 0)
                                inUse = true;
                        }
                        if (cat.getIsDefault()) {
                            def = true;
                            defCat = cat.getPath();
                        }
                    }
                    if (!inUse)
                        ffList.add(cff);
                }
                if (ffList.size() > 0) {
                    String list = "";
                    for (String ffel : ffList)
                        list = list + ffel + ", ";
                    list.substring(0, list.length() - 2);
                    String msg;
                    if (def)
                        msg = "Default category: " + defCat;
                    else
                        msg = "No default category";
                    ErrorDialog error = new ErrorDialog(CategoriesView.this.getViewSite().getShell(),
                            "Fault Family isn't in any Categoty",
                            "The Fault Family is not part of any Category",
                            new Status(IStatus.WARNING, "cl.utfsm.acs.acg", "The Fault Family(ies) " + list
                                    + " is not part of any Category (" + msg + ")"),
                            IStatus.WARNING);
                    error.setBlockOnOpen(true);
                    error.open();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (_ffList.getItemCount() == 0)
                _errorMessageLabel.setText("You have to select at least one Fault Family");
        }
    };

    /* To add a new FF to a Category */
    Listener addFaultFamily = new Listener() {
        public void handleEvent(Event event) {
            Category c = _categoryManager.getCategoryByPath(_pathText.getText());
            java.util.List<String> currentffs = new ArrayList<String>();
            try {
                String[] ffss = c.getAlarms().getFaultFamily();
                for (int i = 0; i < ffss.length; i++) {
                    currentffs.add(ffss[i]);
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            java.util.List<String> ffnames = sortFullFaultFamilyList();
            ListSelectionDialog dialog3 = new ListSelectionDialog(
                    PlatformUI.getWorkbench().getDisplay().getActiveShell(), ffnames,
                    new ArrayContentProvider(), new LabelProvider(), "");

            dialog3.setTitle("Fault Family Selection");
            dialog3.setMessage("List of Fault Families");
            dialog3.setBlockOnOpen(true);
            if (currentffs != null)
                dialog3.setInitialElementSelections(currentffs);
            dialog3.open();
            if (dialog3.getReturnCode() == InputDialog.OK) {
                Object ffselected[] = dialog3.getResult();
                try {
                    Alarms alarms = new Alarms();
                    for (int i = 0; i < ffselected.length; i++)
                        alarms.addFaultFamily(_alarmManager.getFaultFamily((String) ffselected[i]).getName());
                    c.setAlarms(alarms);
                    _categoryManager.updateCategory(c, c);
                    sortCategoryFaultFamilyList(c.getPath());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String[] items = _categoriesList.getSelection();
                refreshContents();
                _categoriesList.setSelection(items);
                Event e = new Event();
                _categoriesList.notifyListeners(SWT.Selection, e);
                IWorkbenchWindow _window = getViewSite().getWorkbenchWindow();
                IViewReference[] views = _window.getActivePage().getViewReferences();
                IMyViewPart view = ((IMyViewPart) views[3].getView(false));
                //view.refreshContents();
                view.fillWidgets();
                if (_ffList.getItemCount() == 0)
                    _errorMessageLabel.setText("You have to select at least one Fault Family");
            }
        }
    };

    /* Initial label when no categories are selected */
    _compInitial = new Composite(sash, SWT.NONE);
    _compInitial.setLayout(new GridLayout());
    new Label(_compInitial, SWT.NONE).setText("Select a category");

    /* Fill the right pane Group that will be shown when
     * a category is selected in the left list */
    layout = new GridLayout();
    layout.numColumns = 2;
    GridData gridData = new GridData();
    gridData.grabExcessHorizontalSpace = true;
    gridData.grabExcessVerticalSpace = true;
    gridData.horizontalAlignment = SWT.FILL;
    gridData.verticalAlignment = SWT.FILL;
    _comp = new Group(_compInitial, SWT.SHADOW_ETCHED_IN);
    _comp.setText("Category information");
    _comp.setLayout(layout);
    _comp.setLayoutData(gridData);

    _pathLabel = new Label(_comp, SWT.NONE);
    _pathLabel.setText("Category name");
    _pathText = new Text(_comp, SWT.SINGLE | SWT.BORDER);
    gridData = new GridData();
    gridData.horizontalAlignment = SWT.FILL;
    gridData.grabExcessHorizontalSpace = true;
    _pathText.setLayoutData(gridData);

    _descriptionLabel = new Label(_comp, SWT.NONE);
    _descriptionLabel.setText("Category description");
    _descriptionText = new Text(_comp, SWT.SINGLE | SWT.BORDER);
    gridData = new GridData();
    gridData.horizontalAlignment = SWT.FILL;
    gridData.grabExcessHorizontalSpace = true;
    _descriptionText.setLayoutData(gridData);

    _isDefaultLabel = new Label(_comp, SWT.NONE);
    _isDefaultLabel.setText("Is default category?");
    _isDefaultCheck = new Button(_comp, SWT.CHECK);

    _ffLabel = new Label(_comp, SWT.NONE);
    _ffLabel.setText("Fault Families:");
    gridData = new GridData();
    gridData.verticalAlignment = SWT.TOP;
    gridData.horizontalSpan = 2;
    _ffLabel.setLayoutData(gridData);
    _ffList = new List(_comp, SWT.V_SCROLL | SWT.BORDER);
    gridData = new GridData();
    gridData.horizontalAlignment = SWT.FILL;
    gridData.grabExcessHorizontalSpace = true;
    gridData.verticalAlignment = SWT.FILL;
    gridData.grabExcessVerticalSpace = true;
    gridData.horizontalSpan = 2;
    _ffList.setLayoutData(gridData);

    _errorMessageLabel = new Label(_comp, SWT.NONE);
    _errorMessageLabel.setText("A");
    _errorMessageLabel.setForeground(getViewSite().getShell().getDisplay().getSystemColor(SWT.COLOR_RED));
    gd = new GridData();
    gd.grabExcessHorizontalSpace = true;
    gd.horizontalAlignment = SWT.FILL;
    gd.horizontalSpan = 2;
    _errorMessageLabel.setLayoutData(gd);

    /* Adding a click right menu to modify the FF of a given Category */
    Menu treePopUp1 = new Menu(parent);
    MenuItem treePopUpAddFF = new MenuItem(treePopUp1, SWT.PUSH);
    treePopUpAddFF.setText("Add a new Fault Family");
    treePopUpAddFF.addListener(SWT.Selection, addFaultFamily);
    MenuItem treePopUpDeleteFF = new MenuItem(treePopUp1, SWT.PUSH);
    treePopUpDeleteFF.setText("Delete this Fault Family");
    treePopUpDeleteFF.addListener(SWT.Selection, deleteFaultFamily);
    MenuItem treePopUpDeleteAllFF = new MenuItem(treePopUp1, SWT.PUSH);
    treePopUpDeleteAllFF.setText("Delete All Fault Families");
    treePopUpDeleteAllFF.addListener(SWT.Selection, deleteAllFaultFamily);
    _ffList.setMenu(treePopUp1);

    /* Adding a click menu to add/delete Categories */
    Menu treePopUp2 = new Menu(parent);
    MenuItem treePopUpaddCategory = new MenuItem(treePopUp2, SWT.PUSH);
    treePopUpaddCategory.setText("Add a new Category");
    treePopUpaddCategory.addListener(SWT.Selection, addCategory);
    MenuItem treePopUpdeleteCategory = new MenuItem(treePopUp2, SWT.PUSH);
    treePopUpdeleteCategory.setText("Delete this Category");
    treePopUpdeleteCategory.addListener(SWT.Selection, deleteCategory);
    _categoriesList.setMenu(treePopUp2);
    _comp.setVisible(false);

    /* Set a weight for each side of the view */
    sash.setWeights(new int[] { 3, 5 });
    Listener updateCategory = new Listener() {
        public void handleEvent(Event e) {
            updateName();
        }
    };
    _descriptionText.addListener(SWT.Modify, updateCategory);
    _pathText.addListener(SWT.Modify, updateCategory);

    _isDefaultCheck.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event e) {
            String category;
            if (_categoriesList.getSelection()[0].startsWith("*"))
                category = (String) _categoriesList.getData();
            else
                category = _categoriesList.getSelection()[0];
            if (_categoryManager.getCategoryByPath(category).getIsDefault() == true) {
                _isDefaultCheck.setSelection(true);
                MessageBox messageBox = new MessageBox(PlatformUI.getWorkbench().getDisplay().getActiveShell(),
                        SWT.ICON_ERROR);
                messageBox.setMessage("The Default Category always must exist, you can only change it");
                messageBox.open();
            } else {
                _categoryManager.updateDefaultCategory(
                        _categoryManager.getCategoryByPath(_categoriesList.getSelection()[0]));
                String[] items = _categoriesList.getSelection();
                refreshContents();
                items[0] = "* " + items[0];
                _categoriesList.setSelection(items);
                Event e2 = new Event();
                _categoriesList.notifyListeners(SWT.Selection, e2);
                IWorkbenchWindow _window = getViewSite().getWorkbenchWindow();
                IViewReference[] views = _window.getActivePage().getViewReferences();
                IMyViewPart view = ((IMyViewPart) views[3].getView(false));
                //view.refreshContents();
                view.fillWidgets();
            }
        }
    });
}

From source file:cl.utfsm.acs.acg.gui.ReductionsView.java

License:Open Source License

private void createViewWidgets(Composite parent) {
    _addElement = new Listener() {
        public void handleEvent(Event event) {
            TreeItem sel = null;//from w w  w  .java  2  s.c  o  m
            TreeItem item = null;
            if (_tree.getSelection() == null || _tree.getSelection().length == 0)
                return;
            sel = _tree.getSelection()[0];
            NodeType type = (NodeType) sel.getData();
            item = sel;
            if (type == NodeType.NODE_REDUCTION_PARENT_DATA
                    || type == NodeType.MULTIPLICITY_REDUCTION_PARENT_DATA)
                item = sel.getParentItem();
            type = (NodeType) item.getData();
            java.util.List<FaultFamily> ffs = _alarmManager.getAllAlarms();
            java.util.List<String> ffnames = new ArrayList<String>();
            for (FaultFamily ff : ffs) {
                if (ff.getFaultCodeCount() > 0 && ff.getFaultMemberCount() > 0)
                    ffnames.add(ff.getName());
            }
            Collections.sort(ffnames, IGNORE_CASE_ORDER);
            ListDialog dialog = new ListDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell());
            dialog.setTitle("Create Reduction Rule");
            dialog.setMessage("Select Parent Fault Family");
            dialog.setBlockOnOpen(true);
            dialog.setInput(ffnames);
            dialog.setContentProvider(new ArrayContentProvider());
            dialog.setLabelProvider(new LabelProvider());
            dialog.open();
            if (dialog.getReturnCode() == InputDialog.CANCEL)
                return;
            String ffname = (String) dialog.getResult()[0];
            FaultMember[] fms = _alarmManager.getFaultFamily(ffname).getFaultMember();
            java.util.List<String> fmnames = new ArrayList<String>();
            for (FaultMember fm : fms) {
                fmnames.add(fm.getName());
            }
            Collections.sort(ffnames, IGNORE_CASE_ORDER);
            dialog = new ListDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell());
            dialog.setTitle("Create Reduction Rule");
            dialog.setMessage("Select Parent Fault Member");
            dialog.setBlockOnOpen(true);
            dialog.setInput(fmnames);
            dialog.setContentProvider(new ArrayContentProvider());
            dialog.setLabelProvider(new LabelProvider());
            dialog.open();
            if (dialog.getReturnCode() == InputDialog.CANCEL)
                return;
            String fmname = (String) dialog.getResult()[0];
            FaultCode[] fcs = _alarmManager.getFaultFamily(ffname).getFaultCode();
            java.util.List<String> fcvalues = new ArrayList<String>();
            for (FaultCode fc : fcs) {
                fcvalues.add(Integer.toString(fc.getValue()));
            }
            Collections.sort(ffnames, IGNORE_CASE_ORDER);
            dialog = new ListDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell());
            dialog.setTitle("Create Reduction Rule");
            dialog.setMessage("Select Parent Fault Code");
            dialog.setBlockOnOpen(true);
            dialog.setInput(fcvalues);
            dialog.setContentProvider(new ArrayContentProvider());
            dialog.setLabelProvider(new LabelProvider());
            dialog.open();
            if (dialog.getReturnCode() == InputDialog.CANCEL)
                return;
            String fcvalue = (String) dialog.getResult()[0];
            ReductionRule parent = null;
            boolean error = false;
            if (type == NodeType.NODE_REDUCTION) {
                parent = _reductionManager.getNRParentByTriplet(ffname, fmname, Integer.parseInt(fcvalue));
                TreeItem[] chs = _tree.getItems()[0].getItems();
                for (TreeItem ch : chs) {
                    if (ch.getText().compareTo("<" + ffname + "," + fmname + "," + fcvalue + ">") == 0)
                        error = true;
                }
            } else if (type == NodeType.MULTIPLICITY_REDUCTION) {
                parent = _reductionManager.getMRParentByTriplet(ffname, fmname, Integer.parseInt(fcvalue));
                TreeItem[] chs = _tree.getItems()[1].getItems();
                for (TreeItem ch : chs) {
                    if (ch.getText().compareTo("<" + ffname + "," + fmname + "," + fcvalue + ">") == 0)
                        error = true;
                }
            }
            if (error || parent != null) {
                ErrorDialog edialog = new ErrorDialog(ReductionsView.this.getViewSite().getShell(),
                        "Reduction Rule Already Exists",
                        "The reduction rule you are trying to create already exists", new Status(IStatus.ERROR,
                                "cl.utfsm.acs.acg", "The reduction rule parent already exists"),
                        IStatus.ERROR);
                edialog.setBlockOnOpen(true);
                edialog.open();
                return;
            } else
                parent = new ReductionRule(_alarmManager.getAlarm(ffname + ":" + fmname + ":" + fcvalue));
            TreeItem pTree = new TreeItem(item, SWT.NONE);
            pTree.setText("<" + ffname + "," + fmname + "," + fcvalue + ">");
            if (type == NodeType.NODE_REDUCTION) {
                pTree.setData(NodeType.NODE_REDUCTION_PARENT_DATA);
                parent.setIsNodeReduction(true);
            } else if (type == NodeType.MULTIPLICITY_REDUCTION) {
                pTree.setData(NodeType.MULTIPLICITY_REDUCTION_PARENT_DATA);
                parent.setIsNodeReduction(false);
            }
            _tree.setSelection(pTree);
            Event e = new Event();
            _tree.notifyListeners(SWT.Selection, e);
        }
    };

    _addRule = new Listener() {
        public void handleEvent(Event event) {
            Table t = (Table) event.widget;
            if (event.type == SWT.KeyUp)
                if (!(event.keyCode == SWT.CR || event.keyCode == ' '))
                    return;
            if (event.type == SWT.MouseDoubleClick) {
                Point pt = new Point(event.x, event.y);
                if (t.getItem(pt) == null)
                    return;
            }
            boolean isNode;
            if (_tree.getSelection() == null || _tree.getSelection().length == 0)
                return;
            TreeItem tmp1 = _tree.getSelection()[0];
            if ((NodeType) _tree.getSelection()[0].getData() == NodeType.NODE_REDUCTION_PARENT_DATA)
                isNode = true;
            else if ((NodeType) _tree.getSelection()[0]
                    .getData() == NodeType.MULTIPLICITY_REDUCTION_PARENT_DATA)
                isNode = false;
            else
                return;
            String[] tr = getTriplet(tmp1.getText());
            ReductionRule parent;
            if (isNode)
                parent = _reductionManager.getNRParentByTriplet(tr[0], tr[1], Integer.parseInt(tr[2]));
            else
                parent = _reductionManager.getMRParentByTriplet(tr[0], tr[1], Integer.parseInt(tr[2]));
            if (t.getSelection() == null || t.getSelection().length == 0)
                return;
            TableItem item = t.getSelection()[0];
            Alarm p, c;
            if (parent == null) {
                if (isNode)
                    p = _alarmManager.getAlarm(_NRParentFFCombo.getText() + ":" + _NRParentFMCombo.getText()
                            + ":" + _NRParentFCCombo.getText());
                else
                    p = _alarmManager.getAlarm(_MRParentFFCombo.getText() + ":" + _MRParentFMCombo.getText()
                            + ":" + _MRParentFCCombo.getText());
                if (p == null) {
                    if (isNode)
                        _NRParentErrorMessageLabel.setText("Couldn't find parent alarm.");
                    else
                        _MRParentErrorMessageLabel.setText("Couldn't find parent alarm.");
                    return;
                }
                c = null;
            } else {
                p = parent.getParent();
                c = parent.getChild(item.getText());
            }

            if (c == null) {
                //Add child
                c = _alarmManager.getAlarm(item.getText());
                if (c == null) {
                    if (isNode)
                        _NRParentErrorMessageLabel.setText("Couldn't find child alarm.");
                    else
                        _MRParentErrorMessageLabel.setText("Couldn't find child alarm.");
                    return;
                }
                try {
                    if (isNode)
                        _reductionManager.addNodeReductionRule(p, c);
                    else {
                        _reductionManager.addMultiReductionRule(p, c);
                        if (parent == null)
                            _reductionManager.updateMultiThreshold(p,
                                    Integer.parseInt(_MRParentThresholdText.getText()));
                    }
                    item.setImage(Activator.getDefault().getImageRegistry().get(Activator.IMG_TICKET));
                    if (parent == null)
                        _tree.getSelection()[0].setText("<" + p.getAlarmId().replace(':', ',') + ">");
                    if (isNode)
                        _NRParentErrorMessageLabel.setText("");
                    else
                        _MRParentErrorMessageLabel.setText("");
                } catch (IllegalOperationException e) {
                    if (isNode)
                        _NRParentErrorMessageLabel.setText(e.getMessage());
                    else
                        _MRParentErrorMessageLabel.setText(e.getMessage());
                }
            } else {
                //Remove child
                try {
                    //ReductionRule rr;
                    if (isNode) {
                        _reductionManager.deleteNodeReductionRule(p, c);
                        //rr = _reductionManager.getNRParentByTriplet(p.getTriplet().getFaultFamily(), p.getTriplet().getFaultMember(), p.getTriplet().getFaultCode());
                    } else {
                        _reductionManager.deleteMultiReductionRule(p, c);
                        //rr = _reductionManager.getMRParentByTriplet(p.getTriplet().getFaultFamily(), p.getTriplet().getFaultMember(), p.getTriplet().getFaultCode());
                    }
                } catch (IllegalOperationException e) {
                    e.printStackTrace();
                }
                item.setImage((org.eclipse.swt.graphics.Image) null);
            }
            fillMRParentChAlarmList(tr[0], tr[1], Integer.parseInt(tr[2]));
            sortReductionRulesList();
            Triplet t2 = p.getTriplet();
            if (isNode)
                selectElementFromTree(
                        "<" + t2.getFaultFamily() + "," + t2.getFaultMember() + "," + t2.getFaultCode() + ">",
                        true);
            else
                selectElementFromTree(
                        "<" + t2.getFaultFamily() + "," + t2.getFaultMember() + "," + t2.getFaultCode() + ">",
                        false);
        }
    };

    _removeElement = new Listener() {
        public void handleEvent(Event event) {
            boolean choice = MessageDialog.openQuestion(ReductionsView.this.getViewSite().getShell(),
                    "Confirmation", "Are you sure you want to delete this element");
            if (choice == true) {
                TreeItem sel = null;
                if (_tree.getSelection() == null || _tree.getSelection().length == 0)
                    return;
                NodeType type = (NodeType) _tree.getSelection()[0].getData();
                if (type == NodeType.NODE_REDUCTION || type == NodeType.MULTIPLICITY_REDUCTION)
                    return;
                TreeItem item = _tree.getSelection()[0];
                String[] tr = getTriplet(item.getText());
                try {
                    if (type == NodeType.NODE_REDUCTION_PARENT_DATA) {
                        //Remove all the NODE REDUCTION Rules in which this node is parent.
                        ReductionRule rr = _reductionManager.getNRParentByTriplet(tr[0], tr[1],
                                Integer.parseInt(tr[2]));
                        if (rr != null) {
                            Alarm p = rr.getParent();
                            List<Alarm> chL = rr.getChildren();
                            Alarm[] als = new Alarm[chL.size()];
                            chL.toArray(als);
                            for (int i = 0; i < als.length; i++)
                                _reductionManager.deleteNodeReductionRule(p, als[i]);
                        }
                    } else if (type == NodeType.MULTIPLICITY_REDUCTION_PARENT_DATA) {
                        //Remove all the MULTIPLICITY REDUCTION Rules in which this node is a parent.
                        ReductionRule rr = _reductionManager.getMRParentByTriplet(tr[0], tr[1],
                                Integer.parseInt(tr[2]));
                        if (rr != null) {
                            Alarm p = rr.getParent();
                            List<Alarm> chL = rr.getChildren();
                            Alarm[] als = new Alarm[chL.size()];
                            chL.toArray(als);
                            for (int i = 0; i < als.length; i++)
                                _reductionManager.deleteMultiReductionRule(p, als[i]);
                        }
                    }
                } catch (NullPointerException e) {
                    ErrorDialog error = new ErrorDialog(ReductionsView.this.getViewSite().getShell(),
                            "Cannot delete the item", e.getMessage(),
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                } catch (IllegalOperationException e) {
                    ErrorDialog error = new ErrorDialog(ReductionsView.this.getViewSite().getShell(),
                            "Cannot delete the item", e.getMessage(),
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                }
                sel = _tree.getSelection()[0].getParentItem();
                _tree.getSelection()[0].dispose();
                _tree.setSelection(sel);
                Event e = new Event();
                _tree.notifyListeners(SWT.Selection, e);
            }
        }
    };
    _sash = new SashForm(parent, SWT.NONE);
    _sash.setLayout(new FillLayout());

    _reductionsComp = new Composite(_sash, SWT.NONE);
    GridLayout layout = new GridLayout();
    layout.numColumns = 1;
    _reductionsComp.setLayout(layout);

    _treeGroup = new Group(_reductionsComp, SWT.SHADOW_ETCHED_IN);
    GridData gd = new GridData();
    gd.horizontalAlignment = SWT.FILL;
    gd.verticalAlignment = SWT.FILL;
    gd.grabExcessHorizontalSpace = true;
    gd.grabExcessVerticalSpace = true;
    _treeGroup.setLayoutData(gd);
    GridLayout gl = new GridLayout();
    gl.numColumns = 1;
    _treeGroup.setLayout(gl);
    _treeGroup.setText("Reduction Rules List");

    _tree = new Tree(_treeGroup, SWT.VIRTUAL | SWT.BORDER);
    gd = new GridData();
    gd.verticalAlignment = SWT.FILL;
    gd.horizontalAlignment = SWT.FILL;
    gd.grabExcessVerticalSpace = true;
    gd.grabExcessHorizontalSpace = true;
    _tree.setLayoutData(gd);
    Menu treePopUp = new Menu(parent);
    /*
    MenuItem treePopUpDelete = new MenuItem(treePopUp,SWT.PUSH);
    treePopUpDelete.setText("Delete");
    treePopUpDelete.addListener(SWT.Selection, _removeElement);
    MenuItem treePopUpAddRule = new MenuItem(treePopUp,SWT.PUSH);
    treePopUpAddRule.setText("Add Rule");
    treePopUpAddRule.addListener(SWT.Selection, _addElement);
    MenuItem treePopUpAddChildren = new MenuItem(treePopUp,SWT.PUSH);
    treePopUpAddChildren.setText("Add Children");
    //treePopUpAddChildren.addListener(SWT.Selection, _addElement);
    */
    _tree.setMenu(treePopUp);
    treePopUp.addListener(SWT.Show, new Listener() {
        public void handleEvent(Event e) {
            TreeItem sel = _tree.getSelection()[0];
            NodeType type = (NodeType) sel.getData();
            Menu treePopUp = _tree.getMenu();
            MenuItem[] items = treePopUp.getItems();
            for (int i = 0; i < items.length; i++)
                items[i].dispose();
            MenuItem mitem;
            switch (type) {
            case NODE_REDUCTION:
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Add Node Reduction Rule Parent");
                mitem.addListener(SWT.Selection, _addElement);
                break;
            case NODE_REDUCTION_PARENT_DATA:
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Delete Node Reduction Rules for this parent");
                mitem.addListener(SWT.Selection, _removeElement);
                break;
            case MULTIPLICITY_REDUCTION:
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Add Multiplicity Reduction Rule Parent");
                mitem.addListener(SWT.Selection, _addElement);
                break;
            case MULTIPLICITY_REDUCTION_PARENT_DATA:
                mitem = new MenuItem(treePopUp, SWT.PUSH);
                mitem.setText("Delete Multiplicity Reduction Rules for this parent");
                mitem.addListener(SWT.Selection, _removeElement);
                break;
            default:
                for (int i = 0; i < items.length; i++)
                    items[i].dispose();
                break;
            }
        }
    });

    _tree.addSelectionListener(new SelectionListener() {
        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);
        }

        public void widgetSelected(SelectionEvent e) {
            TreeItem[] tmp = ((Tree) e.widget).getSelection();
            if (tmp == null || tmp.length == 0)
                return;

            TreeItem item = tmp[0];
            NodeType type = (NodeType) item.getData();
            Control c = _compInitial.getChildren()[0];

            if (c instanceof Label) {
                c.dispose();
                _compInitial.layout();
                c = _compInitial.getChildren()[0];
            }

            if (type == NodeType.NODE_REDUCTION) {
                _NRParentGroup.setVisible(false);
                ((GridData) _NRParentGroup.getLayoutData()).exclude = true;
                _MRParentGroup.setVisible(false);
                ((GridData) _MRParentGroup.getLayoutData()).exclude = true;
            } else if (type == NodeType.NODE_REDUCTION_PARENT_DATA) {
                _NRParentGroup.setVisible(true);
                ((GridData) _NRParentGroup.getLayoutData()).exclude = false;
                _MRParentGroup.setVisible(false);
                ((GridData) _MRParentGroup.getLayoutData()).exclude = true;

                String[] triplet = getTriplet(item.getText());
                fillNRParentWidgets(triplet[0], triplet[1], Integer.parseInt(triplet[2]));
                _NRParentGroup.moveAbove(c);
                _compInitial.layout();
            } else if (type == NodeType.MULTIPLICITY_REDUCTION) {
                _NRParentGroup.setVisible(false);
                ((GridData) _NRParentGroup.getLayoutData()).exclude = true;
                _MRParentGroup.setVisible(false);
                ((GridData) _MRParentGroup.getLayoutData()).exclude = true;
            } else if (type == NodeType.MULTIPLICITY_REDUCTION_PARENT_DATA) {
                _NRParentGroup.setVisible(false);
                ((GridData) _NRParentGroup.getLayoutData()).exclude = true;
                _MRParentGroup.setVisible(true);
                ((GridData) _MRParentGroup.getLayoutData()).exclude = false;

                String[] triplet = getTriplet(item.getText());
                fillMRParentWidgets(triplet[0], triplet[1], Integer.parseInt(triplet[2]));

                _MRParentGroup.moveAbove(c);
                _compInitial.layout();
            }
        }
    });

    /* Top widget of the right side */
    _compInitial = new Composite(_sash, SWT.NONE);
    _compInitial.setLayout(new GridLayout());

    new Label(_compInitial, SWT.NONE).setText("Select a reduction rule");

    /* NR/MR Details */
    createNRParentWidgets();
    createMRParentWidgets();

    _NRParentGroup.setVisible(false);
    _MRParentGroup.setVisible(false);
    _sash.setWeights(new int[] { 3, 5 });
}

From source file:cl.utfsm.acs.acg.gui.SourcesView.java

License:Open Source License

private void createViewWidgets(final Composite parent) {
    _sash = new SashForm(parent, SWT.HORIZONTAL);
    _sash.setLayout(new FillLayout());

    /* Left pane */
    _sourcesComp = new Composite(_sash, SWT.NONE);
    GridLayout layout = new GridLayout();
    layout.numColumns = 1;/* w  w  w .  j av  a  2 s .  c o m*/
    _sourcesComp.setLayout(layout);

    _listGroup = new Group(_sourcesComp, SWT.SHADOW_ETCHED_IN);
    GridData gd = new GridData();
    gd.horizontalAlignment = SWT.FILL;
    gd.verticalAlignment = SWT.FILL;
    gd.grabExcessHorizontalSpace = true;
    gd.grabExcessVerticalSpace = true;
    _listGroup.setLayoutData(gd);
    GridLayout gl = new GridLayout();
    gl.numColumns = 1;
    _listGroup.setLayout(gl);
    _listGroup.setText("Sources List");

    _sourcesList = new List(_listGroup, SWT.BORDER);
    gd = new GridData();
    gd.verticalAlignment = SWT.FILL;
    gd.horizontalAlignment = SWT.FILL;
    gd.grabExcessVerticalSpace = true;
    gd.grabExcessHorizontalSpace = true;
    _sourcesList.setLayoutData(gd);

    _sourcesButtonsComp = new Composite(_sourcesComp, SWT.NONE);
    layout = new GridLayout();
    layout.numColumns = 2;
    _sourcesButtonsComp.setLayout(layout);

    _addSourceButton = new Button(_sourcesButtonsComp, SWT.None);
    _addSourceButton.setText("Add");
    _addSourceButton.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ADD));

    _deleteSourceButton = new Button(_sourcesButtonsComp, SWT.None);
    _deleteSourceButton.setText("Delete");
    _deleteSourceButton
            .setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_ETOOL_DELETE));

    /* Please change this in the future when more SOURCES will be available */
    _addSourceButton.setEnabled(false);
    _deleteSourceButton.setEnabled(false);
    _sourcesList.addSelectionListener(new SelectionListener() {
        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);
        }

        public void widgetSelected(SelectionEvent e) {
            String source = _sourcesList.getSelection()[0];
            Control c = _compInitial.getChildren()[0];
            if (c instanceof Label) {
                c.dispose();
                _group.setVisible(true);
                _group.layout();
            }
            fillSource(source);
            _compInitial.layout();
        }
    });

    _addSourceButton.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event event) {
            InputDialog dialog = new InputDialog(SourcesView.this.getViewSite().getShell(), "New source",
                    "Enter the source name", null, new IInputValidator() {
                        public String isValid(String newText) {
                            if (newText.trim().compareTo("") == 0)
                                return "The name is empty";
                            return null;
                        }
                    });
            dialog.setBlockOnOpen(true);
            dialog.open();
            int returnCode = dialog.getReturnCode();
            if (returnCode == InputDialog.OK) {
                Source newSource = new Source();
                newSource.setSourceId(dialog.getValue());
                try {
                    _sourceManager.addSource(newSource);
                } catch (IllegalOperationException e) {
                    ErrorDialog error = new ErrorDialog(SourcesView.this.getViewSite().getShell(),
                            "Source already exist",
                            "The source " + dialog.getValue() + " already exists in the current configuration",
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                    return;
                }
                refreshContents();
                if (_sourcesList.getItems().length != 0) {
                    int lenght = _sourcesList.getItems().length;
                    lenght -= 1;
                    _sourcesList.select(lenght);
                    _descriptionText.setText(_sourcesList.getItem(lenght).toString());
                }
            }
        }
    });

    _deleteSourceButton.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event event) {
            boolean choice = MessageDialog.openQuestion(SourcesView.this.getViewSite().getShell(),
                    "Confirmation", "Are you sure you want to delete this Source");
            if (choice == true) {
                String tmp[] = _sourcesList.getSelection();
                if (tmp.length == 0) {
                    MessageBox box = new MessageBox(getViewSite().getShell(),
                            SWT.OK | SWT.ICON_ERROR | SWT.APPLICATION_MODAL);
                    box.setText("Empty selection");
                    box.setMessage("There are no sources selected to be deleted");
                    box.open();
                    return;
                }
                String source = tmp[0];
                try {
                    _sourceManager.deleteSource(_sourceManager.getSource(source));
                } catch (IllegalOperationException e) {
                    ErrorDialog error = new ErrorDialog(SourcesView.this.getViewSite().getShell(),
                            "Cannot delete source", "The source cannot be deleted",
                            new Status(IStatus.ERROR, "cl.utfsm.acs.acg", e.getMessage()), IStatus.ERROR);
                    error.setBlockOnOpen(true);
                    error.open();
                }
                refreshContents();
                if (_sourcesList.getItems().length != 0) {
                    int lenght = _sourcesList.getItems().length;
                    lenght -= 1;
                    _sourcesList.select(lenght);
                    _sourceNameText.setText(_sourcesList.getItem(lenght).toString());
                }
            }
        }
    });

    /* Right pane */
    _compInitial = new Composite(_sash, SWT.NONE);
    _compInitial.setLayout(new GridLayout());
    new Label(_compInitial, SWT.NONE).setText("Select a source");

    layout = new GridLayout();
    layout.numColumns = 2;
    gd = new GridData();
    gd.horizontalAlignment = SWT.FILL;
    gd.verticalAlignment = SWT.FILL;
    gd.grabExcessHorizontalSpace = true;
    gd.grabExcessVerticalSpace = true;
    _group = new Group(_compInitial, SWT.SHADOW_ETCHED_IN);
    _group.setText("Source information");
    _group.setLayout(layout);
    _group.setLayoutData(gd);

    _sourceNameLabel = new Label(_group, SWT.NONE);
    _sourceNameLabel.setText("Source name");
    _sourceNameText = new Text(_group, SWT.BORDER);

    _descriptionLabel = new Label(_group, SWT.NONE);
    _descriptionLabel.setText("Description");
    _descriptionText = new Text(_group, SWT.BORDER);

    gd = new GridData();
    gd.horizontalAlignment = SWT.FILL;
    gd.grabExcessHorizontalSpace = true;

    _sourceNameText.setLayoutData(gd);
    _descriptionText.setLayoutData(gd);

    _group.setVisible(false);
    _sash.setWeights(new int[] { 3, 5 });

    /* TODO: This is temporal, since there is currently only
     * one source defined in the AS, and it's hardcoded */
    //setEnabled(false);

    _descriptionText.addListener(SWT.Modify, new Listener() {
        public void handleEvent(Event e) {
            updateSource();
        }
    });

    _errorMessageLabel = new Label(_group, SWT.NONE);
    _errorMessageLabel.setText("");
    _errorMessageLabel.setForeground(getViewSite().getShell().getDisplay().getSystemColor(SWT.COLOR_RED));
    gd = new GridData();
    gd.grabExcessHorizontalSpace = true;
    gd.horizontalAlignment = SWT.FILL;
    gd.horizontalSpan = 2;
    _errorMessageLabel.setLayoutData(gd);

    /* Please change this in the future when more SOURCES will be available */
    _sourceNameText.setEnabled(false);
    _descriptionText.setEnabled(false);
}

From source file:cn.dockerfoundry.ide.eclipse.explorer.ui.views.DockerContainersView.java

License:Open Source License

private void makeActions() {
    startAction = new Action() {
        public void run() {
            DockerContainerElement elem = getSelectedElement();

            if (elem != null & getClient() != null) {
                String message = "Are you sure you want to start this docker \"" + elem.getNames().get(0)
                        + "\"?";
                boolean b = MessageDialog.openQuestion(viewer.getControl().getShell(),
                        "Start a stopped container", message);
                if (b) {
                    try {
                        getClient().startContainer(elem.getId());
                        Thread.sleep(5 * 1000);
                        hookRefreshAction();
                    } catch (DockerException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }/* w w  w  . j  a  v a  2 s  .  com*/
                }
            } //end for if

        }
    };
    startAction.setText("Start");
    startAction.setToolTipText("Start a stopped container");
    startAction.setImageDescriptor(Activator.getImageDescriptor("icons/start.gif"));

    stopAction = new Action() {
        public void run() {
            DockerContainerElement elem = getSelectedElement();
            String status = elem.getStatus();
            if (elem != null & getClient() != null) {
                String message = "Are you sure you want to stop this docker \"" + elem.getNames().get(0)
                        + "\"?";
                boolean b = MessageDialog.openQuestion(viewer.getControl().getShell(),
                        "Stop a running container", message);
                if (b) {
                    try {
                        getClient().stopContainer(elem.getId(), 100);
                        Thread.sleep(5 * 1000);
                        hookRefreshAction();
                    } catch (DockerException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } //end for if
        }
    };
    stopAction.setText("Stop");
    stopAction.setToolTipText("Stop a running container");
    stopAction.setImageDescriptor(Activator.getImageDescriptor("icons/stop.gif"));

    unpauseAction = new Action() {
        public void run() {
            DockerContainerElement elem = getSelectedElement();
            String status = elem.getStatus();
            if (elem != null & getClient() != null) {
                String message = "Are you sure you want to unpause this docker \"" + elem.getNames().get(0)
                        + "\"?";
                boolean b = MessageDialog.openQuestion(viewer.getControl().getShell(),
                        "Unpause a paused container", message);
                if (b) {
                    try {
                        getClient().unpauseContainer(elem.getId());
                        Thread.sleep(5 * 1000);
                        hookRefreshAction();
                    } catch (DockerException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } //end for if
        }
    };
    unpauseAction.setText("Unpause");
    unpauseAction.setToolTipText("Unpause a paused container");
    unpauseAction.setImageDescriptor(Activator.getImageDescriptor("icons/unpause.gif"));

    pauseAction = new Action() {
        public void run() {
            DockerContainerElement elem = getSelectedElement();
            String status = elem.getStatus();
            if (elem != null & getClient() != null) {
                String message = "Are you sure you want to pause this docker \"" + elem.getNames().get(0)
                        + "\"?";
                boolean b = MessageDialog.openQuestion(viewer.getControl().getShell(),
                        "Pause all processes within a container", message);
                if (b) {
                    try {
                        getClient().pauseContainer(elem.getId());
                        Thread.sleep(5 * 1000);
                        hookRefreshAction();
                    } catch (DockerException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } //end for if
        }
    };
    pauseAction.setText("Pause");
    pauseAction.setToolTipText("Pause all processes within a container");
    pauseAction.setImageDescriptor(Activator.getImageDescriptor("icons/pause.gif"));

    renameAction = new Action() {
        public void run() {
            hookRenameAction();
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            hookRefreshAction();
        }
    };
    renameAction.setText("Rename");
    renameAction.setToolTipText("Rename an existing container");
    renameAction.setImageDescriptor(Activator.getImageDescriptor("icons/rename.gif"));

    deleteAction = new Action() {
        public void run() {
            DockerContainerElement elem = getSelectedElement();
            if (elem != null & getClient() != null) {
                String message = "Are you sure you want to remove this docker \"" + elem.getNames().get(0)
                        + "\"?";
                boolean b = MessageDialog.openQuestion(viewer.getControl().getShell(),
                        "Remove one or more containers", message);
                if (b) {
                    try {
                        getClient().removeContainer(elem.getId(), true);
                        Thread.sleep(5 * 1000);
                        hookRefreshAction();
                    } catch (DockerException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } //end for if
        }
    };
    deleteAction.setText("Remove");
    deleteAction.setToolTipText("Remove one or more containers");
    deleteAction.setImageDescriptor(
            PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));

    inspectAction = new Action() {
        public void run() {
            IViewPart propSheet = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
                    .findView(IPageLayout.ID_PROP_SHEET);

            if (propSheet != null) {
                PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().bringToTop(propSheet);
            } else {
                try {
                    PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
                            .showView(IPageLayout.ID_PROP_SHEET);
                } catch (PartInitException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    };
    inspectAction.setText("Inspect");
    inspectAction.setToolTipText("Return low-level information on a container");
    inspectAction.setImageDescriptor(Activator.getImageDescriptor("icons/inspect.gif"));

    showConsoleAction = new Action() {
        public void run() {

            DockerContainerElement elem = getSelectedElement();
            if (elem != null & getClient() != null) {
                IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                MessageConsole console = ConsoleHelper
                        .findConsole("Docker Container - " + elem.getNames().get(0));
                MessageConsoleStream out = console.newMessageStream();
                LogStream logStream = null;
                try {
                    logStream = getClient().logs(elem.getId(), /* LogsParameter.FOLLOW, */LogsParameter.STDERR,
                            LogsParameter.STDOUT, LogsParameter.TIMESTAMPS);

                    /*StringBuilder stringBuilder = new StringBuilder();
                    int index = 0;
                    while (logStream.hasNext()) {
                       stringBuilder.append(UTF_8.decode(logStream.next()
                             .content()));
                       index++;
                       if(index > 100)
                          break;
                    }                  
                    out.print(stringBuilder.toString());*/
                    out.println(logStream.readFully());
                    out.setActivateOnWrite(true);
                    out.setColor(Display.getDefault().getSystemColor(SWT.COLOR_BLUE));
                    out.close();
                } catch (DockerException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if (logStream != null) {
                        logStream.close();
                    }
                }

                try {
                    IConsoleView view = (IConsoleView) page.showView(IConsoleConstants.ID_CONSOLE_VIEW);
                    view.display(console);
                    view.setFocus();
                } catch (PartInitException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    showConsoleAction.setText("Show Console");
    showConsoleAction.setToolTipText("Show the console for the docker container -  [logs -ft --tail 0]");
    showConsoleAction.setImageDescriptor(Activator.getImageDescriptor("icons/console.gif"));

    showEnvAction = new Action() {
        public void run() {

            DockerContainerElement elem = getSelectedElement();
            if (elem != null & getClient() != null) {
                IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                MessageConsole console = ConsoleHelper
                        .findConsole("Docker Container - " + elem.getNames().get(0));
                MessageConsoleStream out = console.newMessageStream();
                LogStream logStream = null;
                try {
                    String execId = getClient().execCreate(elem.getId(), new String[] { "env" },
                            DockerClient.ExecParameter.STDOUT, DockerClient.ExecParameter.STDERR);

                    out.println("execId = " + execId);

                    logStream = getClient().execStart(execId);
                    String output = logStream.readFully();
                    out.println("Result:\n" + output);

                    out.setActivateOnWrite(true);
                    out.setColor(Display.getDefault().getSystemColor(SWT.COLOR_BLUE));
                    out.close();
                } catch (DockerException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if (logStream != null) {
                        logStream.close();
                    }
                }

                try {
                    IConsoleView view = (IConsoleView) page.showView(IConsoleConstants.ID_CONSOLE_VIEW);
                    view.display(console);
                    view.setFocus();
                } catch (PartInitException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    showEnvAction.setText("Show Env in Console");
    showEnvAction.setToolTipText("Show the environment variables in the console");
    showEnvAction.setImageDescriptor(Activator.getImageDescriptor("icons/env.gif"));

    showLinkAction = new Action() {
        public void run() {

            DockerContainerElement elem = getSelectedElement();
            if (elem != null & getClient() != null) {
                IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                MessageConsole console = ConsoleHelper
                        .findConsole("Docker Container - " + elem.getNames().get(0));
                MessageConsoleStream out = console.newMessageStream();
                LogStream logStream = null;
                try {
                    ContainerInfo info = getClient().inspectContainer(elem.getId());
                    HostConfig hostConfig = info.hostConfig();
                    List<String> links;
                    if (hostConfig != null && (links = hostConfig.links()) != null && links.size() > 0) {
                        out.setColor(Display.getDefault().getSystemColor(SWT.COLOR_BLUE));
                        out.println("Container [" + elem.getName() + "] has the following links:");
                        for (Iterator<String> iterator = links.iterator(); iterator.hasNext();) {
                            String link = (String) iterator.next();
                            out.println(link);
                        }
                    } else {
                        out.setColor(Display.getDefault().getSystemColor(SWT.COLOR_RED));
                        out.println("Container [" + elem.getName() + "] has not any links.");
                    }

                    out.setActivateOnWrite(true);
                    out.close();
                } catch (DockerException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if (logStream != null) {
                        logStream.close();
                    }
                }

                try {
                    IConsoleView view = (IConsoleView) page.showView(IConsoleConstants.ID_CONSOLE_VIEW);
                    view.display(console);
                    view.setFocus();
                } catch (PartInitException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    showLinkAction.setText("Show Docker Links in Console");
    showLinkAction.setToolTipText("Show the docker links in the console");
    showLinkAction.setImageDescriptor(Activator.getImageDescriptor("icons/link.gif"));

    refreshAction = new Action() {
        public void run() {
            hookRefreshAction();
        }
    };
    refreshAction.setText("Refresh");
    refreshAction.setToolTipText("Refresh the docker container list");
    refreshAction.setImageDescriptor(Activator.getImageDescriptor("icons/refresh.gif"));

    doubleClickAction = new Action() {
        public void run() {
            ISelection selection = viewer.getSelection();
            Object obj = ((IStructuredSelection) selection).getFirstElement();
            //showMessage("Double-click detected on " + obj.toString());
        }
    };
}

From source file:cn.dockerfoundry.ide.eclipse.server.ui.internal.DebugUIProvider.java

License:Open Source License

@Override
public boolean configureApp(DockerFoundryApplicationModule appModule, DockerFoundryServer cloudServer,
        IProgressMonitor monitor) throws CoreException {
    IModule[] mod = new IModule[] { appModule.getLocalModule() };

    boolean shouldRestart = DockerFoundryProperties.isModuleStopped.testProperty(mod, cloudServer);

    // If the application cannot yet launch then prompt the user to restart
    // the app in order for
    // any changes that enables debug to be set in the Cloud container
    if (!provider.canLaunch(appModule, cloudServer, monitor)) {

        final boolean[] shouldProceed = new boolean[] { true };

        // Ask if the module should be restarted in its current state.
        Display.getDefault().syncExec(new Runnable() {

            public void run() {
                Shell shell = CloudUiUtil.getShell();
                shouldProceed[0] = MessageDialog.openQuestion(shell, Messages.DebugUIProvider_DEBUG_TITLE,
                        Messages.DebugUIProvider_DEBUG_APP_RESTART_MESSAGE);
            }//from  ww  w  . ja  v a  2 s  .  com

        });

        shouldRestart = shouldProceed[0];
        if (!shouldProceed[0]) {
            return false;
        }
    }
    provider.configureApp(appModule, cloudServer, monitor);

    if (shouldRestart) {
        // Perform a full push and start
        cloudServer.getBehaviour().operations().applicationDeployment(mod, ApplicationAction.START)
                .run(monitor);
    }
    return true;

}

From source file:cn.dockerfoundry.ide.eclipse.server.ui.internal.editor.CloudUrlDialog.java

License:Open Source License

@Override
protected void okPressed() {
    final boolean[] shouldProceed = new boolean[] { false };

    BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {

        public void run() {
            try {
                DockerFoundryPlugin.getCloudFoundryClientFactory().getCloudFoundryOperations(url)
                        .getCloudInfo();
                shouldProceed[0] = true;
            } catch (Exception e) {
                shouldProceed[0] = MessageDialog.openQuestion(getParentShell(),
                        Messages.CloudUrlDialog_TEXT_INVALID_URL,
                        NLS.bind(Messages.CloudUrlDialog_TEXT_CONN_FAILED, url));
            }/* w  w w . ja  v a  2s  .c o  m*/
        }
    });

    if (shouldProceed[0]) {
        super.okPressed();
    }
}

From source file:cn.dockerfoundry.ide.eclipse.server.ui.internal.ServerWizardValidator.java

License:Open Source License

/**
 * /*from   w  ww.  j a v  a2  s. c  o m*/
 * @param status containing possible self-signed information. If null, no
 * further checks or validation will occur
 * @param context
 * @return {@link IStatus#OK} if self-signed was accepted. IStatus.ERROR if
 * Null if initial status is also null.
 */
protected ValidationStatus checkSelfSigned(final ValidationStatus status, final IRunnableContext context) {
    // If not status is passes that may contain self-signed information, no
    // further validation is possible
    if (status == null) {
        return null;
    }
    final ValidationStatus[] validationStatus = new ValidationStatus[] { status };

    IStatus iStatus = validationStatus[0].getStatus();

    if (validationStatus[0].getEventType() == ValidationEvents.SELF_SIGNED
            && iStatus.getException() instanceof SSLPeerUnverifiedException) {

        Display.getDefault().syncExec(new Runnable() {

            public void run() {

                // Now check if for this server URL there is a stored
                // value
                // indicating whether to user self-signed certs or not.
                boolean storedSelfSign = cfServer.getSelfSignedCertificate();

                if (!storedSelfSign) {
                    String message = NLS.bind(Messages.WARNING_SELF_SIGNED_PROMPT_USER, cfServer.getUrl());

                    if (MessageDialog.openQuestion(Display.getDefault().getActiveShell(),
                            Messages.TITLE_SELF_SIGNED_PROMPT_USER, message)) {
                        acceptSelfSigned = true;
                    }
                } else {
                    acceptSelfSigned = storedSelfSign;
                }

                // Re-validate if the user has selected to continue with
                // self-signed certificate
                if (acceptSelfSigned) {
                    validationStatus[0] = new ValidationStatus(Status.OK_STATUS, ValidationEvents.VALIDATION);
                } else {
                    // If user selected not to accept self-signed server, no
                    // further validation
                    // can be possible. Indicate this as an error
                    validationStatus[0] = new ValidationStatus(
                            DockerFoundryPlugin
                                    .getErrorStatus(Messages.ERROR_UNABLE_CONNECT_SERVER_CREDENTIALS),
                            ValidationEvents.SELF_SIGNED);
                }
            }
        });
    }

    // Always update the value in the server. For example, if a
    // previous run has determined that this URL needs
    // self-signed
    // certificate
    // but no SSL error was thrown, it means that Server
    // condition
    // has changed (i.e it no longer needs the certificate).
    cfServer.setSelfSignedCertificate(acceptSelfSigned);
    return validationStatus[0];
}