Example usage for org.eclipse.jdt.core IJavaProject getPackageFragmentRoot

List of usage examples for org.eclipse.jdt.core IJavaProject getPackageFragmentRoot

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject getPackageFragmentRoot.

Prototype

IPackageFragmentRoot getPackageFragmentRoot(IResource resource);

Source Link

Document

Returns a package fragment root for the given resource, which must either be a folder representing the top of a package hierarchy, or a ZIP archive (e.g.

Usage

From source file:org.evosuite.eclipse.popup.actions.TestGenerationAction.java

License:Open Source License

/**
 * Main action: check if evosuite-tests exists, and add test generation job
 * /*from w  w w  . j a v  a  2 s . co m*/
 * @param target
 */
public void generateTests(IResource target) {
    Boolean disabled = System.getProperty("evosuite.disable") != null; //  && System.getProperty("evosuite.disable").equals("1")
    if (disabled) {
        MessageDialog.openInformation(shell, "Sorry!", "The EvoSuite Plugin is disabled :(");
        return;
    }
    System.out.println("EvoSuite Plugin is enabled");
    System.out.println("[TestGenerationAction] Generating tests for " + target.toString());
    IFolder folder = target.getProject().getFolder("evosuite-tests");
    if (!folder.exists()) {
        // Create evosuite-tests directory and add as source folder
        try {
            folder.create(false, true, null);
            IJavaProject jProject = JavaCore.create(target.getProject());

            IPackageFragmentRoot root = jProject.getPackageFragmentRoot(folder);
            IClasspathEntry[] oldEntries = jProject.getRawClasspath();
            IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
            System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
            newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath());
            jProject.setRawClasspath(newEntries, null);

        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    addTestJob(target);
}

From source file:org.fusesource.ide.camel.editor.globalconfiguration.beans.BeanConfigUtil.java

License:Open Source License

private IPackageFragmentRoot findPackageFragmentRootWithFacade(final IProject project,
        IJavaProject javaProject) {
    IMavenProjectFacade facade = MavenPlugin.getMavenProjectRegistry().create(project,
            new NullProgressMonitor());
    if (facade != null) {
        IPath[] paths = facade.getCompileSourceLocations();
        if (paths != null && paths.length > 0) {
            for (IPath p : paths) {
                if (p == null)
                    continue;
                IResource res = project.findMember(p);
                if (res != null) {
                    return javaProject.getPackageFragmentRoot(res);
                }/*from w w  w . j a va 2s . c om*/
            }
        }
    }
    return null;
}

From source file:org.fusesource.ide.camel.editor.globalconfiguration.beans.BeanConfigUtil.java

License:Open Source License

private IPackageFragmentRoot findPackageFragmentRoot(final IProject project, IJavaProject javaProject)
        throws CoreException {
    IPackageFragmentRoot fromFacade = findPackageFragmentRootWithFacade(project, javaProject);
    if (fromFacade != null) {
        return fromFacade;
    } else {//from  www. j a  va2  s  . c o  m
        IPackageFragmentRoot[] allPackageFragmentRoots = javaProject.getAllPackageFragmentRoots();
        if (allPackageFragmentRoots.length == 1) {
            return allPackageFragmentRoots[0];
        } else {
            IFolder tstFolder = project.getFolder("src/main/java"); //$NON-NLS-1$
            IPackageFragmentRoot tstRoot = javaProject.getPackageFragmentRoot(tstFolder);
            if (tstRoot.exists()) {
                return tstRoot;
            } else {
                tstFolder.create(true, true, new NullProgressMonitor());

                // now refresh the package root to ensure we have the right fragment
                tstRoot = javaProject.getPackageFragmentRoot(tstFolder);
            }
            return tstRoot;
        }
    }
}

From source file:org.fusesource.ide.camel.editor.properties.AdvancedEndpointPropertiesSection.java

License:Open Source License

/**
 * /*from ww w . j av  a  2  s . com*/
 * @param props
 * @param page
 * @param ignorePathProperties
 * @param group
 */
protected void generateTabContents(List<Parameter> props, final Composite page, boolean ignorePathProperties,
        String group) {
    for (Parameter p : props) {
        final Parameter prop = p;

        // atm we don't want to care about path parameters if thats not the path tab
        if (ignorePathProperties && p.getKind() != null && p.getKind().equalsIgnoreCase("path"))
            continue;

        // we don't display items which don't fit the group
        if (p.getGroup() != null && p.getGroup().trim().length() > 0) {
            // a group has been explicitely defined, so use it
            if (group.equalsIgnoreCase(p.getGroup()) == false
                    && p.getKind().equalsIgnoreCase(GROUP_PATH) == false)
                continue;
        } else if (prop.getKind().equalsIgnoreCase(GROUP_PATH) && group.equalsIgnoreCase(GROUP_PATH)) {
            // special handling for path properties - otherwise the else would kick all props of type path
        } else {
            // no group defined, fall back to use label
            if (prop.getLabel() != null && PropertiesUtils.containsLabel(group, prop) == false)
                continue;
            if (prop.getLabel() == null && group.equalsIgnoreCase(GROUP_COMMON) == false)
                continue;
        }

        ISWTObservableValue uiObservable = null;
        IObservableValue modelObservable = null;
        IValidator validator = null;

        String s = Strings.humanize(p.getName());
        if (p.getDeprecated() != null && p.getDeprecated().equalsIgnoreCase("true"))
            s += " (deprecated)";

        Label l = toolkit.createLabel(page, s);
        l.setLayoutData(new GridData());
        if (p.getDescription() != null) {
            l.setToolTipText(p.getDescription());
        }
        if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
            l.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE));
        }

        Control c = null;

        // BOOLEAN PROPERTIES
        if (CamelComponentUtils.isBooleanProperty(prop)) {
            Button checkBox = toolkit.createButton(page, "", SWT.CHECK | SWT.BORDER);
            Boolean b = (Boolean) PropertiesUtils.getTypedPropertyFromUri(selectedEP, prop, component);
            checkBox.setSelection(b);
            checkBox.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    PropertiesUtils.updateURIParams(selectedEP, prop, ((Button) e.getSource()).getSelection(),
                            component, modelMap);
                }
            });
            checkBox.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = checkBox;

            //initialize the map entry
            modelMap.put(p.getName(), checkBox.getSelection());
            // create observables for the control
            uiObservable = WidgetProperties.selection().observe(checkBox);

            // TEXT PROPERTIES
        } else if (CamelComponentUtils.isTextProperty(prop)) {
            Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")
                    || p.getName().equalsIgnoreCase("id")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (((String) selectedEP.getParameter("uri")).startsWith("ref:")) {
                            // check for broken refs
                            String refId = ((String) selectedEP.getParameter("uri")).trim().length() > "ref:"
                                    .length()
                                            ? ((String) selectedEP.getParameter("uri"))
                                                    .substring("ref:".length())
                                            : null;
                            if (refId == null || refId.trim().length() < 1 || selectedEP.getCamelContext()
                                    .getEndpointDefinitions().get(refId) == null) {
                                return ValidationStatus
                                        .error("The entered reference does not exist in your context!");
                            }
                        }

                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }

            // NUMBER PROPERTIES
        } else if (CamelComponentUtils.isNumberProperty(prop)) {
            Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.RIGHT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    String val = txt.getText();
                    try {
                        Double.parseDouble(val);
                        txt.setBackground(ColorConstants.white);
                        PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                    } catch (NumberFormatException ex) {
                        // invalid character found
                        txt.setBackground(ColorConstants.red);
                        return;
                    }
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);
            validator = new IValidator() {
                /*
                 * (non-Javadoc)
                 * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                 */
                @Override
                public IStatus validate(Object value) {
                    if (prop.getRequired() != null && prop.getRequired().equalsIgnoreCase("true")
                            && (value == null || value.toString().trim().length() < 1)) {
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                    // only check non-empty fields
                    if (value != null && value.toString().trim().length() > 0) {
                        try {
                            Double.parseDouble(value.toString());
                        } catch (NumberFormatException ex) {
                            return ValidationStatus
                                    .error("The parameter " + prop.getName() + " requires a numeric value.");
                        }
                    }
                    return ValidationStatus.ok();
                }
            };

            // CHOICE PROPERTIES
        } else if (CamelComponentUtils.isChoiceProperty(prop)) {
            CCombo choiceCombo = new CCombo(page, SWT.BORDER | SWT.FLAT | SWT.READ_ONLY | SWT.SINGLE);
            toolkit.adapt(choiceCombo, true, true);
            choiceCombo.setEditable(false);
            choiceCombo.setItems(CamelComponentUtils.getChoices(prop));
            String selectedValue = PropertiesUtils.getPropertyFromUri(selectedEP, prop, component);
            for (int i = 0; i < choiceCombo.getItems().length; i++) {
                if (selectedValue != null && choiceCombo.getItem(i).equalsIgnoreCase(selectedValue)) {
                    choiceCombo.select(i);
                    break;
                } else if (selectedValue == null && p.getDefaultValue() != null
                        && choiceCombo.getItem(i).equalsIgnoreCase(p.getDefaultValue())) {
                    choiceCombo.select(i);
                    break;
                }
            }
            choiceCombo.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    CCombo choice = (CCombo) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, choice.getText(), component, modelMap);
                }
            });
            choiceCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = choiceCombo;
            //initialize the map entry
            modelMap.put(p.getName(), choiceCombo.getText());
            // create observables for the control
            uiObservable = WidgetProperties.selection().observe(choiceCombo);
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            // FILE PROPERTIES
        } else if (CamelComponentUtils.isFileProperty(prop)) {
            final Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));

            Button btn_browse = toolkit.createButton(page, "...", SWT.BORDER | SWT.PUSH);
            btn_browse.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    DirectoryDialog dd = new DirectoryDialog(page.getShell());
                    String pathName = dd.open();
                    if (pathName != null) {
                        txtField.setText(pathName);
                    }
                }
            });
            btn_browse.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
            c = txtField;
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);

            // EXPRESSION PROPERTIES
        } else if (CamelComponentUtils.isExpressionProperty(prop)) {
            Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);

            // DATAFORMAT PROPERTIES
        } else if (CamelComponentUtils.isDataFormatProperty(prop)) {
            Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);

            // UNSUPPORTED PROPERTIES / REFS
        } else if (CamelComponentUtils.isUnsupportedProperty(prop)) {

            // TODO: check how to handle lists and maps - for now we treat them as string field only

            Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);

            // CLASS BASED PROPERTIES - REF OR CLASSNAMES AS STRINGS
        } else {
            // must be some class as all other options were missed
            final Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));

            URLClassLoader child = CamelComponentUtils.getProjectClassLoader();
            Class classToLoad;
            try {
                if (prop.getJavaType().indexOf("<") != -1) {
                    classToLoad = child
                            .loadClass(prop.getJavaType().substring(0, prop.getJavaType().indexOf("<")));
                } else {
                    classToLoad = child.loadClass(prop.getJavaType());
                }
            } catch (ClassNotFoundException ex) {
                CamelEditorUIActivator.pluginLog()
                        .logWarning("Cannot find class " + prop.getJavaType() + " on classpath.", ex);
                classToLoad = null;
            }

            final IProject project = CamelUtils.getDiagramEditor().getModel().getResource().getProject();
            final Class fClass = classToLoad;

            Button btn_create = toolkit.createButton(page, " + ", SWT.BORDER | SWT.PUSH);
            btn_create.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    NewClassCreationWizard wiz = new NewClassCreationWizard();
                    wiz.addPages();
                    wiz.init(PlatformUI.getWorkbench(), null);
                    NewClassWizardPage wp = (NewClassWizardPage) wiz.getStartingPage();
                    WizardDialog wd = new WizardDialog(e.display.getActiveShell(), wiz);
                    if (fClass.isInterface()) {
                        wp.setSuperInterfaces(Arrays.asList(fClass.getName()), true);
                    } else {
                        wp.setSuperClass(fClass.getName(), true);
                    }
                    wp.setAddComments(true, true);
                    IPackageFragmentRoot fragroot = null;
                    try {
                        IJavaProject javaProject = (IJavaProject) project.getNature(JavaCore.NATURE_ID);
                        IMavenProjectFacade facade = MavenPlugin.getMavenProjectRegistry().create(project,
                                new NullProgressMonitor());
                        IPath[] paths = facade.getCompileSourceLocations();
                        if (paths != null && paths.length > 0) {
                            for (IPath p : paths) {
                                if (p == null)
                                    continue;
                                IResource res = project.findMember(p);
                                fragroot = javaProject.getPackageFragmentRoot(res);
                                break;
                            }
                            if (fragroot != null)
                                wp.setPackageFragmentRoot(fragroot, true);
                            wp.setPackageFragment(PropertiesUtils.getPackage(javaProject, fragroot), true);
                        }
                    } catch (Exception ex) {
                        CamelEditorUIActivator.pluginLog().logError(ex);
                    }
                    if (Window.OK == wd.open()) {
                        String value = wp.getCreatedType().getFullyQualifiedName();
                        if (value != null)
                            txtField.setText(value);
                    }
                }
            });
            btn_create.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
            btn_create.setEnabled(fClass != null);

            Button btn_browse = toolkit.createButton(page, "...", SWT.BORDER | SWT.PUSH);
            btn_browse.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    try {
                        IJavaProject javaProject = (IJavaProject) project.getNature(JavaCore.NATURE_ID);
                        IJavaElement[] elements = new IJavaElement[] { javaProject };
                        IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements);

                        FilteredTypesSelectionDialog dlg = new FilteredTypesSelectionDialog(
                                Display.getDefault().getActiveShell(), false,
                                PlatformUI.getWorkbench().getProgressService(), scope,
                                IJavaSearchConstants.CLASS);

                        if (Window.OK == dlg.open()) {
                            Object o = dlg.getFirstResult();
                            if (o instanceof SourceType) {
                                txtField.setText(((SourceType) o).getFullyQualifiedName());
                            }
                        }
                    } catch (Exception ex) {
                        CamelEditorUIActivator.pluginLog().logError(ex);
                    }
                }
            });
            btn_browse.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
            btn_browse.setEnabled(fClass != null);
            c = txtField;
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);

        }

        // create UpdateValueStrategy and assign to the binding
        UpdateValueStrategy strategy = new UpdateValueStrategy();
        strategy.setBeforeSetValidator(validator);

        // create observables for the Map entries
        modelObservable = Observables.observeMapEntry(modelMap, p.getName());
        // bind the observables
        Binding bindValue = dbc.bindValue(uiObservable, modelObservable, strategy, null);
        ControlDecorationSupport.create(bindValue, SWT.TOP | SWT.LEFT);

        if (p.getDescription() != null)
            c.setToolTipText(p.getDescription());
    }
}

From source file:org.fusesource.ide.camel.editor.properties.creators.AbstractClassBasedParameterPropertyUICreator.java

License:Open Source License

/**
 * @param parent/*from ww w  .j  a  v  a 2  s  .c o m*/
 * @param project
 * @param fClass
 */
private void createCreateButton(Composite parent, final IProject project, final Class<?> fClass) {
    Button btn_create = getWidgetFactory().createButton(parent, " + ", SWT.FLAT | SWT.PUSH);
    btn_create.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            NewClassCreationWizard wiz = new NewClassCreationWizard();
            wiz.addPages();
            wiz.init(PlatformUI.getWorkbench(), null);
            NewClassWizardPage wp = (NewClassWizardPage) wiz.getStartingPage();
            WizardDialog wd = new WizardDialog(e.display.getActiveShell(), wiz);
            if (fClass.isInterface()) {
                wp.setSuperInterfaces(Arrays.asList(fClass.getName()), true);
            } else {
                wp.setSuperClass(fClass.getName(), true);
            }
            wp.setAddComments(true, true);
            setInitialPackageFrament(project, wp);
            if (Window.OK == wd.open()) {
                String value = wp.getCreatedType().getFullyQualifiedName();
                if (value != null)
                    getControl().setText(value);
            }
        }

        private void setInitialPackageFrament(final IProject project, NewClassWizardPage wp) {
            try {
                IJavaProject javaProject = (IJavaProject) project.getNature(JavaCore.NATURE_ID);
                if (javaProject != null) {
                    IPackageFragmentRoot fragroot = findPackageFragmentRoot(project, javaProject);
                    wp.setPackageFragmentRoot(fragroot, true);
                    wp.setPackageFragment(PropertiesUtils.getPackage(javaProject, fragroot), true);
                }
            } catch (Exception ex) {
                CamelEditorUIActivator.pluginLog().logError(ex);
            }
        }

        private IPackageFragmentRoot findPackageFragmentRoot(final IProject project, IJavaProject javaProject)
                throws JavaModelException {
            IMavenProjectFacade facade = MavenPlugin.getMavenProjectRegistry().create(project,
                    new NullProgressMonitor());
            if (facade != null) {
                IPath[] paths = facade.getCompileSourceLocations();
                if (paths != null && paths.length > 0) {
                    for (IPath p : paths) {
                        if (p == null)
                            continue;
                        IResource res = project.findMember(p);
                        return javaProject.getPackageFragmentRoot(res);
                    }
                }
            } else {
                IPackageFragmentRoot[] allPackageFragmentRoots = javaProject.getAllPackageFragmentRoots();
                if (allPackageFragmentRoots.length == 1) {
                    return allPackageFragmentRoots[0];
                }
            }
            return null;
        }
    });
    btn_create.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    btn_create.setEnabled(fClass != null);
}

From source file:org.fusesource.ide.camel.editor.properties.DetailsSection.java

License:Open Source License

/**
 * /*from   www .  ja  v a  2  s .c om*/
 * @param props
 * @param page
 * @param group
 */
protected void generateTabContents(List<Parameter> props, final Composite page, final String group) {
    for (Parameter p : props) {
        final Parameter prop = p;

        // we don't display items which don't fit the group
        if (group.equals(DEFAULT_GROUP) == false && group.equals(prop.getGroup()) == false)
            continue;
        if (group.equals(DEFAULT_GROUP) && prop.getGroup() != null && prop.getGroup().trim().length() > 0)
            continue;

        // we don't want to display properties for internal element attributes like inputs or outputs
        if ((p.getKind().equalsIgnoreCase("element") && p.getType().equalsIgnoreCase("array")
                && p.getName().equalsIgnoreCase("exception") == false)
                || p.getJavaType().equals("org.apache.camel.model.OtherwiseDefinition"))
            continue;

        ISWTObservableValue uiObservable = null;
        IObservableList uiListObservable = null;
        IObservableValue modelObservable = null;
        IObservableList modelListObservable = null;
        IValidator validator = null;

        String s = Strings.humanize(p.getName());
        if (p.getDeprecated() != null && p.getDeprecated().equalsIgnoreCase("true"))
            s += " (deprecated)";

        Label l = getWidgetFactory().createLabel(page, s);
        l.setLayoutData(new GridData());
        if (p.getDescription() != null) {
            l.setToolTipText(p.getDescription());
        }
        if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
            l.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE));
        }

        Control c = null;

        // DESCRIPTION PROPERTIES
        if (CamelComponentUtils.isDescriptionProperty(prop)) {
            String description = null;
            if (this.selectedEP.getDescription() != null) {
                description = this.selectedEP.getDescription();
            } else {
                description = this.eip.getParameter(p.getName()).getDefaultValue();
            }

            Text txtField = getWidgetFactory().createText(page, description,
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    selectedEP.setDescription(txt.getText());
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        // TODO: add validation for descriptions (xml escape chars etc)
                        return ValidationStatus.ok();
                    }
                };
            }

            // BOOLEAN PROPERTIES
        } else if (CamelComponentUtils.isBooleanProperty(prop)) {
            Button checkBox = getWidgetFactory().createButton(page, "", SWT.CHECK | SWT.BORDER);
            Boolean b = Boolean.parseBoolean((this.selectedEP.getParameter(p.getName()) != null
                    ? this.selectedEP.getParameter(p.getName()).toString()
                    : this.eip.getParameter(p.getName()).getDefaultValue()));
            checkBox.setSelection(b);
            checkBox.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    Button chkBox = (Button) e.getSource();
                    selectedEP.setParameter(prop.getName(), chkBox.getSelection());
                }
            });
            checkBox.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = checkBox;

            //initialize the map entry
            modelMap.put(p.getName(), checkBox.getSelection());
            // create observables for the control
            uiObservable = WidgetProperties.selection().observe(checkBox);

            // TEXT PROPERTIES
        } else if (CamelComponentUtils.isTextProperty(prop)) {
            Text txtField = getWidgetFactory().createText(page,
                    (String) (this.selectedEP.getParameter(p.getName()) != null
                            ? this.selectedEP.getParameter(p.getName())
                            : this.eip.getParameter(p.getName()).getDefaultValue()),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    selectedEP.setParameter(prop.getName(), txt.getText());
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")
                    || p.getName().equalsIgnoreCase("id")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (selectedEP.getParameter("uri") != null
                                && ((String) selectedEP.getParameter("uri")).startsWith("ref:")) {
                            // check for broken refs
                            String refId = ((String) selectedEP.getParameter("uri")).trim().length() > "ref:"
                                    .length()
                                            ? ((String) selectedEP.getParameter("uri"))
                                                    .substring("ref:".length())
                                            : null;
                            if (refId == null || refId.trim().length() < 1 || selectedEP.getCamelContext()
                                    .getEndpointDefinitions().get(refId) == null) {
                                return ValidationStatus
                                        .error("The entered reference does not exist in your context!");
                            }
                        }

                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }

            // NUMBER PROPERTIES
        } else if (CamelComponentUtils.isNumberProperty(prop)) {
            Text txtField = getWidgetFactory().createText(page,
                    (String) (this.selectedEP.getParameter(p.getName()) != null
                            ? this.selectedEP.getParameter(p.getName())
                            : this.eip.getParameter(p.getName()).getDefaultValue()),
                    SWT.SINGLE | SWT.BORDER | SWT.RIGHT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    String val = txt.getText();
                    try {
                        Double.parseDouble(val);
                        txt.setBackground(ColorConstants.white);
                        selectedEP.setParameter(prop.getName(), txt.getText());
                    } catch (NumberFormatException ex) {
                        // invalid character found
                        txt.setBackground(ColorConstants.red);
                        return;
                    }
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);
            validator = new IValidator() {
                /*
                 * (non-Javadoc)
                 * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                 */
                @Override
                public IStatus validate(Object value) {
                    if (prop.getRequired() != null && prop.getRequired().equalsIgnoreCase("true")
                            && (value == null || value.toString().trim().length() < 1)) {
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                    // only check non-empty fields
                    if (value != null && value.toString().trim().length() > 0) {
                        try {
                            Double.parseDouble(value.toString());
                        } catch (NumberFormatException ex) {
                            return ValidationStatus
                                    .error("The parameter " + prop.getName() + " requires a numeric value.");
                        }
                    }
                    return ValidationStatus.ok();
                }
            };

            // CHOICE PROPERTIES
        } else if (CamelComponentUtils.isChoiceProperty(prop)) {
            CCombo choiceCombo = new CCombo(page, SWT.BORDER | SWT.FLAT | SWT.READ_ONLY | SWT.SINGLE);
            getWidgetFactory().adapt(choiceCombo, true, true);
            choiceCombo.setEditable(false);
            choiceCombo.setItems(CamelComponentUtils.getChoices(prop));
            String value = (String) (this.selectedEP.getParameter(p.getName()) != null
                    ? this.selectedEP.getParameter(p.getName())
                    : this.eip.getParameter(p.getName()).getDefaultValue());
            for (int i = 0; i < choiceCombo.getItems().length; i++) {
                if (choiceCombo.getItem(i).equalsIgnoreCase(value)) {
                    choiceCombo.select(i);
                    break;
                }
            }
            choiceCombo.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    CCombo choice = (CCombo) e.getSource();
                    selectedEP.setParameter(prop.getName(), choice.getText());
                }
            });
            choiceCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = choiceCombo;
            //initialize the map entry
            modelMap.put(p.getName(), choiceCombo.getText());
            // create observables for the control
            uiObservable = WidgetProperties.selection().observe(choiceCombo);
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }

            // REF PROPERTIES
        } else if (CamelComponentUtils.isRefProperty(prop)) {
            CCombo choiceCombo = new CCombo(page, SWT.BORDER | SWT.FLAT | SWT.READ_ONLY | SWT.SINGLE);
            getWidgetFactory().adapt(choiceCombo, true, true);
            choiceCombo.setEditable(false);
            choiceCombo.setItems(CamelComponentUtils.getRefs(this.selectedEP.getCamelFile()));
            String value = (String) (this.selectedEP.getParameter(p.getName()) != null
                    ? this.selectedEP.getParameter(p.getName())
                    : this.eip.getParameter(p.getName()).getDefaultValue());
            for (int i = 0; i < choiceCombo.getItems().length; i++) {
                if (choiceCombo.getItem(i).equalsIgnoreCase(value)) {
                    choiceCombo.select(i);
                    break;
                }
            }
            choiceCombo.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    CCombo choice = (CCombo) e.getSource();
                    selectedEP.setParameter(prop.getName(), choice.getText());
                }
            });
            choiceCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = choiceCombo;
            //initialize the map entry
            modelMap.put(p.getName(), choiceCombo.getText());
            // create observables for the control
            uiObservable = WidgetProperties.selection().observe(choiceCombo);
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }

            // FILE PROPERTIES
        } else if (CamelComponentUtils.isFileProperty(prop)) {
            final Text txtField = getWidgetFactory().createText(page,
                    (String) (this.selectedEP.getParameter(p.getName()) != null
                            ? this.selectedEP.getParameter(p.getName())
                            : this.eip.getParameter(p.getName()).getDefaultValue()),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    selectedEP.setParameter(prop.getName(), txt.getText());
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));

            Button btn_browse = getWidgetFactory().createButton(page, "...", SWT.BORDER | SWT.PUSH);
            btn_browse.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    DirectoryDialog dd = new DirectoryDialog(page.getShell());
                    String pathName = dd.open();
                    if (pathName != null) {
                        txtField.setText(pathName);
                    }
                }
            });
            btn_browse.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
            c = txtField;
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);

            // LIST PROPERTIES
        } else if (CamelComponentUtils.isListProperty(prop)) {
            org.eclipse.swt.widgets.List list = new org.eclipse.swt.widgets.List(page,
                    SWT.BORDER | SWT.FLAT | SWT.READ_ONLY | SWT.SINGLE);
            getWidgetFactory().adapt(list, true, true);
            list.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));

            ArrayList<String> listElements = this.selectedEP.getParameter(prop.getName()) != null
                    ? (ArrayList<String>) this.selectedEP.getParameter(prop.getName())
                    : new ArrayList<String>();
            list.setItems(listElements.toArray(new String[listElements.size()]));

            c = list;
            //initialize the map entry
            modelMap.put(p.getName(), Arrays.asList(list.getItems()));
            // create observables for the control
            uiListObservable = WidgetProperties.items().observe(list);
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof List && ((List) value).isEmpty() == false) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }

            // EXPRESSION PROPERTIES
        } else if (CamelComponentUtils.isExpressionProperty(prop)) {
            CCombo choiceCombo = new CCombo(page, SWT.BORDER | SWT.FLAT | SWT.READ_ONLY | SWT.SINGLE);
            getWidgetFactory().adapt(choiceCombo, true, true);
            choiceCombo.setEditable(false);
            choiceCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));

            final CamelModelElement expressionElement = this.selectedEP.getParameter(prop.getName()) != null
                    ? (CamelModelElement) this.selectedEP.getParameter(prop.getName())
                    : null;
            choiceCombo.setItems(CamelComponentUtils.getOneOfList(prop));

            final ExpandableComposite eform = getWidgetFactory().createExpandableComposite(page,
                    ExpandableComposite.TREE_NODE | ExpandableComposite.CLIENT_INDENT);
            eform.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 4, 1));
            eform.setText("Expression Settings...");
            eform.setLayout(new GridLayout(1, true));
            eform.addExpansionListener(new IExpansionListener() {
                /*
                 * (non-Javadoc)
                 * @see org.eclipse.ui.forms.events.IExpansionListener#expansionStateChanging(org.eclipse.ui.forms.events.ExpansionEvent)
                 */
                @Override
                public void expansionStateChanging(ExpansionEvent e) {
                }

                /*
                 * (non-Javadoc)
                 * @see org.eclipse.ui.forms.events.IExpansionListener#expansionStateChanged(org.eclipse.ui.forms.events.ExpansionEvent)
                 */
                @Override
                public void expansionStateChanged(ExpansionEvent e) {
                    page.layout(true);
                    refresh();
                    aTabbedPropertySheetPage.resizeScrolledComposite();
                }
            });

            choiceCombo.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                  * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                  */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    CCombo choice = (CCombo) e.getSource();
                    String language = choice.getText();
                    languageChanged(language, eform, expressionElement, page, prop);
                }
            });

            if (expressionElement != null) {
                String value = expressionElement.getNodeTypeId();
                if (expressionElement.getParameter("expression") != null
                        && expressionElement.getParameter("expression") instanceof CamelModelElement) {
                    CamelModelElement ex = (CamelModelElement) expressionElement.getParameter("expression");
                    value = ex.getTranslatedNodeName();
                }
                choiceCombo.deselectAll();
                for (int i = 0; i < choiceCombo.getItems().length; i++) {
                    if (choiceCombo.getItem(i).equalsIgnoreCase(value)) {
                        choiceCombo.select(i);
                        languageChanged(value, eform, expressionElement, page, prop);
                        break;
                    }
                }
            }

            c = choiceCombo;
            //initialize the map entry
            modelMap.put(p.getName(), choiceCombo.getText());
            // create observables for the control
            uiObservable = WidgetProperties.selection().observe(choiceCombo);
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }

            // DATAFORMAT PROPERTIES
        } else if (CamelComponentUtils.isDataFormatProperty(prop)) {
            CCombo choiceCombo = new CCombo(page, SWT.BORDER | SWT.FLAT | SWT.READ_ONLY | SWT.SINGLE);
            getWidgetFactory().adapt(choiceCombo, true, true);
            choiceCombo.setEditable(false);
            choiceCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));

            CamelModelElement dataformatElement = this.selectedEP.getParameter(prop.getName()) != null
                    ? (CamelModelElement) this.selectedEP.getParameter(prop.getName())
                    : null;
            choiceCombo.setItems(CamelComponentUtils.getOneOfList(prop));

            final ExpandableComposite eform = getWidgetFactory().createExpandableComposite(page,
                    ExpandableComposite.TREE_NODE | ExpandableComposite.CLIENT_INDENT);
            eform.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 4, 1));
            eform.setText("Data Format Settings...");
            eform.setLayout(new GridLayout(1, true));
            eform.addExpansionListener(new IExpansionListener() {
                /*
                 * (non-Javadoc)
                 * @see org.eclipse.ui.forms.events.IExpansionListener#expansionStateChanging(org.eclipse.ui.forms.events.ExpansionEvent)
                 */
                @Override
                public void expansionStateChanging(ExpansionEvent e) {
                }

                /*
                 * (non-Javadoc)
                 * @see org.eclipse.ui.forms.events.IExpansionListener#expansionStateChanged(org.eclipse.ui.forms.events.ExpansionEvent)
                 */
                @Override
                public void expansionStateChanged(ExpansionEvent e) {
                    page.layout(true);
                    refresh();
                    aTabbedPropertySheetPage.resizeScrolledComposite();
                }
            });

            choiceCombo.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                  * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                  */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    CCombo choice = (CCombo) e.getSource();
                    String dataformat = choice.getText();
                    CamelModelElement dataFormatElement = selectedEP.getParameter(prop.getName()) != null
                            ? (CamelModelElement) selectedEP.getParameter(prop.getName())
                            : null;
                    dataFormatChanged(dataformat, eform, dataFormatElement, page, prop);
                }
            });

            if (dataformatElement != null) {
                String value = dataformatElement.getNodeTypeId();
                choiceCombo.deselectAll();
                for (int i = 0; i < choiceCombo.getItems().length; i++) {
                    if (choiceCombo.getItem(i).equalsIgnoreCase(value)) {
                        choiceCombo.select(i);
                        dataFormatChanged(value, eform, dataformatElement, page, prop);
                        break;
                    }
                }
            }

            c = choiceCombo;
            //initialize the map entry
            modelMap.put(p.getName(), choiceCombo.getText());
            // create observables for the control
            uiObservable = WidgetProperties.selection().observe(choiceCombo);
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }

            // UNSUPPORTED PROPERTIES / REFS
        } else if (CamelComponentUtils.isUnsupportedProperty(prop)) {

            // TODO: check how to handle lists and maps - for now we treat them as string field only

            Text txtField = getWidgetFactory().createText(page,
                    (String) (this.selectedEP.getParameter(p.getName()) != null
                            ? this.selectedEP.getParameter(p.getName())
                            : this.eip.getParameter(p.getName()).getDefaultValue()),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    selectedEP.setParameter(prop.getName(), txt.getText());
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);

            // CLASS BASED PROPERTIES - REF OR CLASSNAMES AS STRINGS
        } else {
            // must be some class as all other options were missed
            final Text txtField = getWidgetFactory().createText(page,
                    (String) (this.selectedEP.getParameter(p.getName()) != null
                            ? this.selectedEP.getParameter(p.getName())
                            : this.eip.getParameter(p.getName()).getDefaultValue()),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    selectedEP.setParameter(prop.getName(), txt.getText());
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));

            URLClassLoader child = CamelComponentUtils.getProjectClassLoader();
            Class classToLoad;
            try {
                if (prop.getJavaType().indexOf("<") != -1) {
                    classToLoad = child
                            .loadClass(prop.getJavaType().substring(0, prop.getJavaType().indexOf("<")));
                } else {
                    classToLoad = child.loadClass(prop.getJavaType());
                }
            } catch (ClassNotFoundException ex) {
                CamelEditorUIActivator.pluginLog()
                        .logWarning("Cannot find class " + prop.getJavaType() + " on classpath.", ex);
                classToLoad = null;
            }

            final IProject project = CamelUtils.getDiagramEditor().getModel().getResource().getProject();
            final Class fClass = classToLoad;

            Button btn_create = getWidgetFactory().createButton(page, " + ", SWT.BORDER | SWT.PUSH);
            btn_create.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    NewClassCreationWizard wiz = new NewClassCreationWizard();
                    wiz.addPages();
                    wiz.init(PlatformUI.getWorkbench(), null);
                    NewClassWizardPage wp = (NewClassWizardPage) wiz.getStartingPage();
                    WizardDialog wd = new WizardDialog(e.display.getActiveShell(), wiz);
                    if (fClass.isInterface()) {
                        wp.setSuperInterfaces(Arrays.asList(fClass.getName()), true);
                    } else {
                        wp.setSuperClass(fClass.getName(), true);
                    }
                    wp.setAddComments(true, true);
                    IPackageFragmentRoot fragroot = null;
                    try {
                        IJavaProject javaProject = (IJavaProject) project.getNature(JavaCore.NATURE_ID);
                        IMavenProjectFacade facade = MavenPlugin.getMavenProjectRegistry().create(project,
                                new NullProgressMonitor());
                        IPath[] paths = facade.getCompileSourceLocations();
                        if (paths != null && paths.length > 0) {
                            for (IPath p : paths) {
                                if (p == null)
                                    continue;
                                IResource res = project.findMember(p);
                                fragroot = javaProject.getPackageFragmentRoot(res);
                                break;
                            }
                            if (fragroot != null)
                                wp.setPackageFragmentRoot(fragroot, true);
                            wp.setPackageFragment(PropertiesUtils.getPackage(javaProject, fragroot), true);
                        }
                    } catch (Exception ex) {
                        CamelEditorUIActivator.pluginLog().logError(ex);
                    }
                    if (Window.OK == wd.open()) {
                        String value = wp.getCreatedType().getFullyQualifiedName();
                        if (value != null)
                            txtField.setText(value);
                    }
                }
            });
            btn_create.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
            btn_create.setEnabled(fClass != null);

            Button btn_browse = getWidgetFactory().createButton(page, "...", SWT.BORDER | SWT.PUSH);
            btn_browse.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    try {
                        IJavaProject javaProject = (IJavaProject) project.getNature(JavaCore.NATURE_ID);
                        IJavaElement[] elements = new IJavaElement[] { javaProject };
                        IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements);

                        FilteredTypesSelectionDialog dlg = new FilteredTypesSelectionDialog(
                                Display.getDefault().getActiveShell(), false,
                                PlatformUI.getWorkbench().getProgressService(), scope,
                                IJavaSearchConstants.CLASS);

                        if (Window.OK == dlg.open()) {
                            Object o = dlg.getFirstResult();
                            if (o instanceof SourceType) {
                                txtField.setText(((SourceType) o).getFullyQualifiedName());
                                selectedEP.setParameter(prop.getName(), txtField.getText());
                            }
                        }
                    } catch (Exception ex) {
                        CamelEditorUIActivator.pluginLog().logError(ex);
                    }
                }
            });
            btn_browse.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
            btn_browse.setEnabled(fClass != null);
            c = txtField;
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);

        }

        // bind the observables
        Binding bindValue = null;

        if (uiObservable != null) {
            // create observables for the Map entries
            modelObservable = Observables.observeMapEntry(modelMap, p.getName());

            // create UpdateValueStrategy and assign to the binding
            UpdateValueStrategy strategy = new UpdateValueStrategy();
            strategy.setBeforeSetValidator(validator);

            bindValue = dbc.bindValue(uiObservable, modelObservable, strategy, null);
        } else if (uiListObservable != null) {
            modelListObservable = Observables.staticObservableList((List) modelMap.get(p.getName()),
                    String.class);
            UpdateListStrategy listStrategy = new UpdateListStrategy() {
                /* (non-Javadoc)
                 * @see org.eclipse.core.databinding.UpdateListStrategy#doAdd(org.eclipse.core.databinding.observable.list.IObservableList, java.lang.Object, int)
                 */
                @Override
                protected IStatus doAdd(IObservableList observableList, Object element, int index) {
                    super.doAdd(observableList, element, index);
                    if (prop.getRequired() != null && prop.getRequired().equalsIgnoreCase("true")) {
                        if (observableList.size() < 1)
                            return ValidationStatus.error("Parameter " + prop.getName()
                                    + " is a mandatory field and cannot be empty.");
                    }
                    return ValidationStatus.ok();
                }

                /* (non-Javadoc)
                 * @see org.eclipse.core.databinding.UpdateListStrategy#doRemove(org.eclipse.core.databinding.observable.list.IObservableList, int)
                 */
                @Override
                protected IStatus doRemove(IObservableList observableList, int index) {
                    super.doRemove(observableList, index);
                    if (prop.getRequired() != null && prop.getRequired().equalsIgnoreCase("true")) {
                        if (observableList.size() < 1)
                            return ValidationStatus.error("Parameter " + prop.getName()
                                    + " is a mandatory field and cannot be empty.");
                    }
                    return ValidationStatus.ok();
                }
            };
            bindValue = dbc.bindList(uiListObservable, modelListObservable, listStrategy, null);
        }
        ControlDecorationSupport.create(bindValue, SWT.TOP | SWT.LEFT);

        if (p.getDescription() != null)
            c.setToolTipText(p.getDescription());
    }
    page.layout();
}

From source file:org.fusesource.ide.camel.editor.propertysheet.AdvancedEndpointPropertiesSection.java

License:Open Source License

/**
 * //from   w  w  w .  j a va 2s. co  m
 * @param props
 * @param page
 */
protected void generateTabContents(List<UriParameter> props, final Composite page,
        boolean ignorePathProperties) {
    // display all the properties in alphabetic order - sorting needed
    Collections.sort(props, new Comparator<UriParameter>() {
        /* (non-Javadoc)
         * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
         */
        @Override
        public int compare(UriParameter o1, UriParameter o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });

    for (UriParameter p : props) {
        // atm we don't want to care about path parameters
        if (ignorePathProperties && p.getKind().equalsIgnoreCase("path"))
            continue;

        final UriParameter prop = p;

        ISWTObservableValue uiObservable = null;
        IObservableValue modelObservable = null;
        IValidator validator = null;

        String s = Strings.humanize(p.getName());
        if (p.getDeprecated() != null && p.getDeprecated().equalsIgnoreCase("true"))
            s += " (deprecated)";

        Label l = toolkit.createLabel(page, s);
        l.setLayoutData(new GridData());
        if (p.getDescription() != null) {
            l.setToolTipText(p.getDescription());
        }
        if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
            l.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE));
        }

        Control c = null;

        // BOOLEAN PROPERTIES
        if (CamelComponentUtils.isBooleanProperty(prop)) {
            Button checkBox = toolkit.createButton(page, "", SWT.CHECK | SWT.BORDER);
            Boolean b = (Boolean) PropertiesUtils.getTypedPropertyFromUri(selectedEP, prop, component);
            checkBox.setSelection(b);
            checkBox.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    PropertiesUtils.updateURIParams(selectedEP, prop, ((Button) e.getSource()).getSelection(),
                            component, modelMap);
                }
            });
            checkBox.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = checkBox;

            //initialize the map entry
            modelMap.put(p.getName(), checkBox.getSelection());
            // create observables for the control
            uiObservable = WidgetProperties.selection().observe(checkBox);

            // TEXT PROPERTIES
        } else if (CamelComponentUtils.isTextProperty(prop)) {
            Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (selectedEP.getUri().startsWith("ref:")) {
                            // check for broken refs
                            String refId = selectedEP.getUri().trim().length() > "ref:".length()
                                    ? selectedEP.getUri().substring("ref:".length())
                                    : null;
                            if (refId == null || refId.trim().length() < 1 || selectedEP.getParent().getParent()
                                    .getCamelContextEndpointUris().get(refId) == null) {
                                return ValidationStatus
                                        .error("The entered reference does not exist in your context!");
                            }
                        }

                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }

            // NUMBER PROPERTIES
        } else if (CamelComponentUtils.isNumberProperty(prop)) {
            Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.RIGHT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    String val = txt.getText();
                    try {
                        Double.parseDouble(val);
                        txt.setBackground(ColorConstants.white);
                        PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                    } catch (NumberFormatException ex) {
                        // invalid character found
                        txt.setBackground(ColorConstants.red);
                        return;
                    }
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);
            validator = new IValidator() {
                /*
                 * (non-Javadoc)
                 * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                 */
                @Override
                public IStatus validate(Object value) {
                    if (prop.getRequired() != null && prop.getRequired().equalsIgnoreCase("true")
                            && (value == null || value.toString().trim().length() < 1)) {
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                    // only check non-empty fields
                    if (value != null && value.toString().trim().length() > 0) {
                        try {
                            Double.parseDouble(value.toString());
                        } catch (NumberFormatException ex) {
                            return ValidationStatus
                                    .error("The parameter " + prop.getName() + " requires a numeric value.");
                        }
                    }
                    return ValidationStatus.ok();
                }
            };

            // CHOICE PROPERTIES
        } else if (CamelComponentUtils.isChoiceProperty(prop)) {
            CCombo choiceCombo = new CCombo(page, SWT.BORDER | SWT.FLAT | SWT.READ_ONLY | SWT.SINGLE);
            toolkit.adapt(choiceCombo, true, true);
            choiceCombo.setEditable(false);
            choiceCombo.setItems(CamelComponentUtils.getChoices(prop));
            for (int i = 0; i < choiceCombo.getItems().length; i++) {
                if (choiceCombo.getItem(i)
                        .equalsIgnoreCase(PropertiesUtils.getPropertyFromUri(selectedEP, prop, component))) {
                    choiceCombo.select(i);
                    break;
                }
            }
            choiceCombo.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    CCombo choice = (CCombo) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, choice.getText(), component, modelMap);
                }
            });
            choiceCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = choiceCombo;
            //initialize the map entry
            modelMap.put(p.getName(), choiceCombo.getText());
            // create observables for the control
            uiObservable = WidgetProperties.selection().observe(choiceCombo);
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            // FILE PROPERTIES
        } else if (CamelComponentUtils.isFileProperty(prop)) {
            final Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));

            Button btn_browse = toolkit.createButton(page, "...", SWT.BORDER | SWT.PUSH);
            btn_browse.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    DirectoryDialog dd = new DirectoryDialog(page.getShell());
                    String pathName = dd.open();
                    if (pathName != null) {
                        txtField.setText(pathName);
                    }
                }
            });
            btn_browse.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
            c = txtField;
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);

            // EXPRESSION PROPERTIES
        } else if (CamelComponentUtils.isExpressionProperty(prop)) {
            Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);

            // UNSUPPORTED PROPERTIES / REFS
        } else if (CamelComponentUtils.isUnsupportedProperty(prop)) {

            // TODO: check how to handle lists and maps - for now we treat them as string field only

            Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1));
            c = txtField;
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);

            // CLASS BASED PROPERTIES - REF OR CLASSNAMES AS STRINGS
        } else {
            // must be some class as all other options were missed
            final Text txtField = toolkit.createText(page,
                    PropertiesUtils.getPropertyFromUri(selectedEP, prop, component),
                    SWT.SINGLE | SWT.BORDER | SWT.LEFT);
            txtField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    Text txt = (Text) e.getSource();
                    PropertiesUtils.updateURIParams(selectedEP, prop, txt.getText(), component, modelMap);
                }
            });
            txtField.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));

            URLClassLoader child = CamelComponentUtils.getProjectClassLoader();
            Class classToLoad;
            try {
                if (prop.getJavaType().indexOf("<") != -1) {
                    classToLoad = child
                            .loadClass(prop.getJavaType().substring(0, prop.getJavaType().indexOf("<")));
                } else {
                    classToLoad = child.loadClass(prop.getJavaType());
                }
            } catch (ClassNotFoundException ex) {
                Activator.getLogger().warning("Cannot find class " + prop.getJavaType() + " on classpath.", ex);
                classToLoad = null;
            }

            final IProject project = Activator.getDiagramEditor().getCamelContextFile().getProject();
            final Class fClass = classToLoad;

            Button btn_create = toolkit.createButton(page, " + ", SWT.BORDER | SWT.PUSH);
            btn_create.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    NewClassCreationWizard wiz = new NewClassCreationWizard();
                    wiz.addPages();
                    wiz.init(PlatformUI.getWorkbench(), null);
                    NewClassWizardPage wp = (NewClassWizardPage) wiz.getStartingPage();
                    WizardDialog wd = new WizardDialog(e.display.getActiveShell(), wiz);
                    if (fClass.isInterface()) {
                        wp.setSuperInterfaces(Arrays.asList(fClass.getName()), true);
                    } else {
                        wp.setSuperClass(fClass.getName(), true);
                    }
                    wp.setAddComments(true, true);
                    IPackageFragmentRoot fragroot = null;
                    try {
                        IJavaProject javaProject = (IJavaProject) project.getNature(JavaCore.NATURE_ID);
                        IMavenProjectFacade facade = MavenPlugin.getMavenProjectRegistry().create(project,
                                new NullProgressMonitor());
                        IPath[] paths = facade.getCompileSourceLocations();
                        if (paths != null && paths.length > 0) {
                            for (IPath p : paths) {
                                if (p == null)
                                    continue;
                                IResource res = project.findMember(p);
                                fragroot = javaProject.getPackageFragmentRoot(res);
                                break;
                            }
                            if (fragroot != null)
                                wp.setPackageFragmentRoot(fragroot, true);
                            wp.setPackageFragment(PropertiesUtils.getPackage(javaProject, fragroot), true);
                        }
                    } catch (Exception ex) {
                        Activator.getLogger().error(ex);
                    }
                    if (Window.OK == wd.open()) {
                        String value = wp.getCreatedType().getFullyQualifiedName();
                        if (value != null)
                            txtField.setText(value);
                    }
                }
            });
            btn_create.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
            btn_create.setEnabled(fClass != null);

            Button btn_browse = toolkit.createButton(page, "...", SWT.BORDER | SWT.PUSH);
            btn_browse.addSelectionListener(new SelectionAdapter() {
                /* (non-Javadoc)
                 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
                 */
                @Override
                public void widgetSelected(SelectionEvent e) {
                    try {
                        IJavaProject javaProject = (IJavaProject) project.getNature(JavaCore.NATURE_ID);
                        IJavaElement[] elements = new IJavaElement[] { javaProject };
                        IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements);

                        FilteredTypesSelectionDialog dlg = new FilteredTypesSelectionDialog(
                                Display.getDefault().getActiveShell(), false,
                                PlatformUI.getWorkbench().getProgressService(), scope,
                                IJavaSearchConstants.CLASS);

                        if (Window.OK == dlg.open()) {
                            Object o = dlg.getFirstResult();
                            if (o instanceof SourceType) {
                                txtField.setText(((SourceType) o).getFullyQualifiedName());
                            }
                        }
                    } catch (Exception ex) {
                        Activator.getLogger().error(ex);
                    }
                }
            });
            btn_browse.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
            btn_browse.setEnabled(fClass != null);
            c = txtField;
            if (p.getRequired() != null && p.getRequired().equalsIgnoreCase("true")) {
                validator = new IValidator() {
                    /*
                     * (non-Javadoc)
                     * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
                     */
                    @Override
                    public IStatus validate(Object value) {
                        if (value != null && value instanceof String && value.toString().trim().length() > 0) {
                            return ValidationStatus.ok();
                        }
                        return ValidationStatus.error(
                                "Parameter " + prop.getName() + " is a mandatory field and cannot be empty.");
                    }
                };
            }
            //initialize the map entry
            modelMap.put(p.getName(), txtField.getText());
            // create observables for the control
            uiObservable = WidgetProperties.text(SWT.Modify).observe(txtField);

        }

        // create UpdateValueStrategy and assign to the binding
        UpdateValueStrategy strategy = new UpdateValueStrategy();
        strategy.setBeforeSetValidator(validator);

        // create observables for the Map entries
        modelObservable = Observables.observeMapEntry(modelMap, p.getName());
        // bind the observables
        Binding bindValue = dbc.bindValue(uiObservable, modelObservable, strategy, null);
        ControlDecorationSupport.create(bindValue, SWT.TOP | SWT.LEFT);

        if (p.getDescription() != null)
            c.setToolTipText(p.getDescription());
    }
}

From source file:org.gw4e.eclipse.test.fwk.ProjectHelper.java

License:Open Source License

public static IPackageFragmentRoot addFolderToClassPath(IJavaProject jproject, String containerName)
        throws CoreException {
    IProject project = jproject.getProject();

    IFolder folder = project.getFolder(containerName);
    if (!folder.exists()) {
        createFolder(folder, false, true, new NullProgressMonitor());
    }/*from w w w  .j a  va 2s .co m*/

    IClasspathEntry cpe = JavaCore.newLibraryEntry(folder.getFullPath(), null, null);
    addToClasspath(jproject, cpe);
    return jproject.getPackageFragmentRoot(folder);
}

From source file:org.gw4e.eclipse.test.fwk.ProjectHelper.java

License:Open Source License

public static IFile createDummyClass(IJavaProject project) throws CoreException, IOException {
    String clazz = "import org.graphwalker.core.machine.ExecutionContext ; public class Dummy extends org.gw4e.core.machine.ExecutionContext {}";
    IFolder folder = project.getProject().getFolder("src/test/java");
    IPackageFragmentRoot srcFolder = project.getPackageFragmentRoot(folder);
    IPackageFragment pkg = srcFolder.getPackageFragment("");
    ICompilationUnit cu = pkg.createCompilationUnit("Dummy.java", clazz, false, new NullProgressMonitor());
    cu.save(new NullProgressMonitor(), true);

    return (IFile) cu.getResource();
}

From source file:org.gw4e.eclipse.test.fwk.ProjectHelper.java

License:Open Source License

public static IFile createDummyClassWitherror(IJavaProject project) throws CoreException, IOException {
    String clazz = "import org.graphwalker.core.machine.ExecutionContext ; public class Dummy1 extends org.gw4e.core.machine.ExecutionContext {}";
    IFolder folder = project.getProject().getFolder("src/test/java");
    IPackageFragmentRoot srcFolder = project.getPackageFragmentRoot(folder);
    IPackageFragment pkg = srcFolder.getPackageFragment("");
    ICompilationUnit cu = pkg.createCompilationUnit("Dummy.java", clazz, false, new NullProgressMonitor());
    cu.save(new NullProgressMonitor(), true);
    return (IFile) cu.getResource();
}