Example usage for org.eclipse.jface.viewers IStructuredSelection getFirstElement

List of usage examples for org.eclipse.jface.viewers IStructuredSelection getFirstElement

Introduction

In this page you can find the example usage for org.eclipse.jface.viewers IStructuredSelection getFirstElement.

Prototype

public Object getFirstElement();

Source Link

Document

Returns the first element in this selection, or null if the selection is empty.

Usage

From source file:com.amalto.workbench.actions.XSDChangeToComplexTypeAction.java

License:Open Source License

@Override
public IStatus doAction() {

    try {//from w  w  w . ja  va 2 s  .  c o  m
        IStructuredSelection selection = (IStructuredSelection) page.getTreeViewer().getSelection();
        isConcept = false;
        TreePath tPath = null;
        if (((TreeSelection) selection).getPaths().length > 0) {
            tPath = ((TreeSelection) selection).getPaths()[0];
        }
        // fliu
        // add declNew to support convert action invoked from new concept/new element menu, in this case
        // declNew is the new created one not the selected one in tree vew
        if (declNew != null) {
            decl = declNew;
            checkConcept();
        } else if (selection.getFirstElement() instanceof XSDModelGroup) {
            for (int i = 0; i < tPath.getSegmentCount(); i++) {
                if (tPath.getSegment(i) instanceof XSDElementDeclaration) {
                    decl = (XSDElementDeclaration) tPath.getSegment(i);
                } else if (tPath.getSegment(i) instanceof XSDParticle) {
                    decl = (XSDElementDeclaration) ((XSDParticle) tPath.getSegment(i)).getTerm();
                }
            }
            checkConcept();
        } else if (selection.getFirstElement() instanceof XSDElementDeclaration) {
            decl = (XSDElementDeclaration) selection.getFirstElement();
            // check if concept or "just" element
            checkConcept();

        } else if (selection.getFirstElement() instanceof XSDParticle) {
            // if it's a particle,it should change the element of its
            // content
            decl = (XSDElementDeclaration) ((XSDParticle) selection.getFirstElement()).getContent();
        } else {
            // if(selection.getFirstElement() instanceof XSDParticle )
            if (selection.getFirstElement() != null) {
                // a sub element
                decl = (XSDElementDeclaration) ((XSDParticle) selection.getFirstElement()).getTerm();
            }
        }

        // /save current Type Definition
        // XSDTypeDefinition current = decl.getTypeDefinition();
        List<XSDComplexTypeDefinition> types = Util.getComplexTypes(decl.getSchema());
        if (showDlg) {
            if (decl.getTypeDefinition() instanceof XSDComplexTypeDefinition) {
                boolean confirm = MessageDialog.openConfirm(page.getSite().getShell(), Messages.Warning,
                        Messages.XSDChangeToCXX_ChangeToAnotherTypeWarning);
                if (!confirm) {
                    return Status.CANCEL_STATUS;
                }
            }

            if (tPath != null) {
                for (int i = 0; i < tPath.getSegmentCount(); i++) {
                    if (tPath.getSegment(i) instanceof XSDElementDeclaration) {
                        XSDTypeDefinition type = (((XSDElementDeclaration) tPath.getSegment(i))
                                .getTypeDefinition());
                        if (!type.equals(decl.getTypeDefinition())) {
                            types.remove(type);
                        }
                    }
                    if (tPath.getSegment(i) instanceof XSDParticle) {
                        XSDTypeDefinition type = ((XSDElementDeclaration) (((XSDParticle) tPath.getSegment(i))
                                .getTerm())).getTypeDefinition();
                        if (!type.equals(decl.getTypeDefinition())) {
                            types.remove(type);
                        }
                    }
                }
            }
            dialog = new ComplexTypeInputDialog(this, page.getSite().getShell(), "", schema, //$NON-NLS-1$
                    decl.getTypeDefinition(), types, isXSDModelGroup);

            dialog.setBlockOnOpen(true);
            int ret = dialog.open();
            if (ret == Dialog.CANCEL) {
                return Status.CANCEL_STATUS;
            }
        }

        if (!showDlg && !validateType()) {
            return Status.CANCEL_STATUS;
        }

        XSDFactory factory = XSDSchemaBuildingTools.getXSDFactory();
        boolean anonymous = (typeName == null) || ("".equals(typeName));//$NON-NLS-1$
        boolean alreadyExists = false;

        XSDComplexTypeDefinition complexType = null;
        // the sub element created if needed
        XSDParticle subParticle = null;
        XSDParticle groupParticle = null;
        XSDElementDeclaration subElement = null;

        // check if already exist
        // add by ymli; fix the bug:0012278;
        XSDElementDeclaration parent = null;
        Object pObject = Util.getParent(decl);
        if (pObject instanceof XSDElementDeclaration) {
            parent = (XSDElementDeclaration) pObject;
        }

        if (!anonymous) {
            List<XSDComplexTypeDefinition> list = Util.getComplexTypes(schema);
            if (typeName.lastIndexOf(" : ") != -1) {//$NON-NLS-1$
                typeName = typeName.substring(0, typeName.lastIndexOf(" : "));//$NON-NLS-1$
            }
            for (XSDComplexTypeDefinition td : list) {
                if ((td.getName().equals(typeName))) {
                    alreadyExists = true;
                    complexType = td;
                    break;
                }
            }

        } else {
            XSDComplexTypeDefinition declComplexType = null;
            if (parent != null && decl.getTypeDefinition() instanceof XSDComplexTypeDefinition) {
                declComplexType = (XSDComplexTypeDefinition) decl.getTypeDefinition();
            }
            if (declComplexType != null && declComplexType.getSchema() != null
                    && declComplexType.getName() == null) {
                alreadyExists = true;
            }
            if (decl.getTypeDefinition() instanceof XSDSimpleTypeDefinition) {
                alreadyExists = false;
            }
        }

        if (alreadyExists) {
            XSDParticle partCnt = (XSDParticle) complexType.getContentType();
            partCnt.unsetMaxOccurs();
            partCnt.unsetMinOccurs();
            XSDTypeDefinition superType = null;
            for (XSDTypeDefinition type : types) {
                if (type.getName().equals(superTypeName)) {
                    superType = type;
                    break;
                }
            }

            if (superType != null) {
                XSDModelGroup mdlGrp = (XSDModelGroup) partCnt.getTerm();
                boolean status = updateCompositorType(superType, mdlGrp);
                if (!status) {
                    return Status.CANCEL_STATUS;
                }

                complexType.setDerivationMethod(XSDDerivationMethod.EXTENSION_LITERAL);
                complexType.setBaseTypeDefinition(superType);
            }
            if (isAbstract) {
                complexType.setAbstract(isAbstract);
            } else {
                complexType.unsetAbstract();
            }

            if (parent != null) {
                parent.updateElement();
            }
            if (complexType != null) {
                complexType.updateElement();
            }
        } else {// Create if does not exist

            // add an element declaration
            subElement = factory.createXSDElementDeclaration();
            if (declNew != null) {
                // crate a new entity
                if (declNew.getName() != null) {
                    subElement.setName(declNew.getName() + "Id");//$NON-NLS-1$
                }
            } else {
                // create a complex element
                subElement.setName("subelement");//$NON-NLS-1$
            }
            subElement.setTypeDefinition(
                    schema.resolveSimpleTypeDefinition(schema.getSchemaForSchemaNamespace(), "string"));//$NON-NLS-1$

            subParticle = factory.createXSDParticle();
            subParticle.unsetMaxOccurs();
            subParticle.unsetMinOccurs();
            subParticle.setContent(subElement);
            subParticle.updateElement();

            // create group
            XSDModelGroup group = factory.createXSDModelGroup();
            if (isChoice) {
                group.setCompositor(XSDCompositor.CHOICE_LITERAL);
            } else if (isAll) {
                group.setCompositor(XSDCompositor.ALL_LITERAL);
            } else {
                group.setCompositor(XSDCompositor.SEQUENCE_LITERAL);
            }
            group.getContents().add(0, subParticle);
            group.updateElement();

            // create the complex type
            complexType = factory.createXSDComplexTypeDefinition();
            if (!anonymous) {
                XSDTypeDefinition superType = null;
                for (XSDTypeDefinition type : types) {
                    if (type.getName().equals(superTypeName)) {
                        superType = type;
                        break;
                    }
                }
                complexType.setName(typeName);
                if (superType != null) {
                    complexType.setDerivationMethod(XSDDerivationMethod.EXTENSION_LITERAL);
                    complexType.setBaseTypeDefinition(superType);
                    updateCompositorType(superType, group);
                }
                if (isAbstract) {
                    complexType.setAbstract(isAbstract);
                } else {
                    complexType.unsetAbstract();
                }
                schema.getContents().add(complexType);
            }
            complexType.updateElement();

            // add the group
            groupParticle = factory.createXSDParticle();
            groupParticle.unsetMaxOccurs();
            groupParticle.unsetMinOccurs();
            groupParticle.setContent(group);
            groupParticle.updateElement();

            complexType.setContent(groupParticle);
            complexType.updateElement();
        } // end if NOT already exusts

        // set complex type to concept
        if (anonymous) {
            decl.setAnonymousTypeDefinition(complexType);
        } else {
            decl.setTypeDefinition(complexType);
        }

        if (isConcept) {
            buildUniqueKey(factory, decl, complexType, anonymous, alreadyExists);
        } // if isConcept

        decl.updateElement();
        schema.update();
        page.refresh();

        declNew = null;
        page.markDirty();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages.XSDChangeToCXX_ErrorMsg1, e.getLocalizedMessage()));
        return Status.CANCEL_STATUS;
    }

    return Status.OK_STATUS;
}

From source file:com.amalto.workbench.actions.XSDChangeToSimpleTypeAction.java

License:Open Source License

@Override
public IStatus doAction() {
    try {//from www  .  jav a 2s . com
        XSDElementDeclaration decl = null;
        IStructuredSelection selection = (IStructuredSelection) page.getTreeViewer().getSelection();
        // fliu
        // add declNew to support convert action invoked from new concept/new element menu, in this case
        // declNew is the new created one not the selected one in tree vew
        if (declNew != null) {
            decl = declNew;
        } else if (selection.getFirstElement() instanceof XSDElementDeclaration) {
            isConcept = true;
            decl = (XSDElementDeclaration) selection.getFirstElement();

        } else {
            isConcept = false;
            if (selection.getFirstElement() != null) {
                decl = (XSDElementDeclaration) ((XSDParticle) selection.getFirstElement()).getTerm();
            }
        }

        // build list of custom types and built in types
        List<String> customTypes = new ArrayList<String>();
        for (XSDTypeDefinition type : schema.getTypeDefinitions()) {
            if (type instanceof XSDSimpleTypeDefinition) {
                if (type.getTargetNamespace() != null
                        && !type.getTargetNamespace().equals(XSDConstants.SCHEMA_FOR_SCHEMA_URI_2001)
                        || type.getTargetNamespace() == null) {
                    customTypes.add(type.getName());
                }
            }
        }
        List<String> builtInTypes = XSDUtil.getBuiltInTypes();

        if (showDlg) {
            String name = decl.getTypeDefinition().getName();

            if (decl.getTypeDefinition() instanceof XSDComplexTypeDefinition) {
                name = null;
                boolean confirm = MessageDialog.openConfirm(page.getSite().getShell(), Messages.Warning,
                        Messages.XSDChangeToCXX_ChangeToAnotherTypeWarning);
                if (!confirm) {
                    return Status.CANCEL_STATUS;
                }
            }

            dialog = new SimpleTypeInputDialog(this, page.getSite().getShell(), schema,
                    Messages.XSDChangeToXX_DialogTitle, customTypes, builtInTypes, name);

            dialog.setBlockOnOpen(true);
            int ret = dialog.open();
            if (ret == Window.CANCEL) {
                return Status.CANCEL_STATUS;
            }
        }

        // if concept
        // remove all unique keys and make new one
        if (isConcept) {
            // remove exisitng unique key(s)
            ArrayList keys = new ArrayList();
            EList list = decl.getIdentityConstraintDefinitions();
            for (Iterator iter = list.iterator(); iter.hasNext();) {
                XSDIdentityConstraintDefinition icd = (XSDIdentityConstraintDefinition) iter.next();
                if (icd.getIdentityConstraintCategory().equals(XSDIdentityConstraintCategory.UNIQUE_LITERAL)) {
                    keys.add(icd);
                }
            }
            decl.getIdentityConstraintDefinitions().removeAll(keys);
            // add new unique Key
            XSDFactory factory = XSDSchemaBuildingTools.getXSDFactory();
            XSDIdentityConstraintDefinition uniqueKey = factory.createXSDIdentityConstraintDefinition();
            uniqueKey.setIdentityConstraintCategory(XSDIdentityConstraintCategory.UNIQUE_LITERAL);
            uniqueKey.setName(decl.getName());
            XSDXPathDefinition selector = factory.createXSDXPathDefinition();
            selector.setVariety(XSDXPathVariety.SELECTOR_LITERAL);
            selector.setValue(".");//$NON-NLS-1$
            uniqueKey.setSelector(selector);
            XSDXPathDefinition field = factory.createXSDXPathDefinition();
            field.setVariety(XSDXPathVariety.FIELD_LITERAL);
            field.setValue(".");//$NON-NLS-1$
            uniqueKey.getFields().add(field);
            decl.getIdentityConstraintDefinitions().add(uniqueKey);
        }

        // Save current type definition
        XSDTypeDefinition current = decl.getTypeDefinition();

        // set new one
        if (builtIn) {
            decl.setTypeDefinition(
                    schema.resolveSimpleTypeDefinition(schema.getSchemaForSchemaNamespace(), typeName));
        } else {
            // check if concept already exists
            if (typeName != null && typeName.length() > 0) {
                XSDSimpleTypeDefinition std = null;
                String ns = "";//$NON-NLS-1$
                if (typeName.lastIndexOf(" : ") != -1) {//$NON-NLS-1$
                    ns = typeName.substring(typeName.lastIndexOf(" : ") + 3);//$NON-NLS-1$
                    typeName = typeName.substring(0, typeName.lastIndexOf(" : "));//$NON-NLS-1$
                }
                for (XSDTypeDefinition typeDef : schema.getTypeDefinitions()) {
                    if (typeDef instanceof XSDSimpleTypeDefinition) {
                        if (typeDef.getName().equals(typeName)) {
                            std = (XSDSimpleTypeDefinition) typeDef;
                            break;
                        }
                    }
                }
                if (std == null) {
                    std = schema.resolveSimpleTypeDefinition(typeName);
                    std.setBaseTypeDefinition(
                            schema.resolveSimpleTypeDefinition(schema.getSchemaForSchemaNamespace(), "string"));//$NON-NLS-1$

                    if (typeName.equals(EUUIDCustomType.MULTI_LINGUAL.getName())) {
                        XSDPatternFacet f = XSDSchemaBuildingTools.getXSDFactory().createXSDPatternFacet();
                        f.setLexicalValue("(\\[\\w+\\:[^\\[\\]]*\\]){0,}");//$NON-NLS-1$
                        std.getFacetContents().add(f);
                    }

                    schema.getContents().add(std);
                }

                decl.setTypeDefinition(std);
            } else {
                XSDFactory factory = XSDSchemaBuildingTools.getXSDFactory();
                simpleType = factory.createXSDSimpleTypeDefinition();
                simpleType.setBaseTypeDefinition(
                        schema.resolveSimpleTypeDefinition(schema.getSchemaForSchemaNamespace(), "string"));//$NON-NLS-1$
                decl.setAnonymousTypeDefinition(simpleType);
            }
        }
        decl.updateElement();

        // remove current if no more in use
        // if (current != null) {
        // if ( (current.getName()!=null) && //anonymous type
        // (!schema.getSchemaForSchemaNamespace().equals(current.getTargetNamespace()))
        // ){
        // List eut =Util.findElementsUsingType(schema, current.getTargetNamespace(), current.getName());
        // if (eut.size()==0)
        // schema.getContents().remove(current);
        // }
        // }

        declNew = null;
        page.refresh();
        page.markDirty();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages.XSDChangeToXX_ErrorMsg1, e.getLocalizedMessage()));
        return Status.CANCEL_STATUS;
    }
    return Status.OK_STATUS;
}

From source file:com.amalto.workbench.actions.XSDCopyConceptAction.java

License:Open Source License

public void run() {
    try {//from www  . ja  v a 2s . c o  m
        WorkbenchClipboard.getWorkbenchClipboard().conceptsReset();
        WorkbenchClipboard.getWorkbenchClipboard().particlesReset();
        IStructuredSelection selection = (IStructuredSelection) page.getTreeViewer().getSelection();
        if (selection.getFirstElement() instanceof XSDElementDeclaration) {
            for (Iterator<XSDElementDeclaration> iter = selection.iterator(); iter.hasNext();) {
                XSDElementDeclaration concept = iter.next();

                if (concept instanceof XSDElementDeclaration)
                    WorkbenchClipboard.getWorkbenchClipboard().add(concept);
            }
        } else if (selection.getFirstElement() instanceof XSDParticle) {
            for (Iterator<XSDParticle> iter = selection.iterator(); iter.hasNext();) {
                XSDParticle particle = iter.next();

                if (particle instanceof XSDParticle)
                    WorkbenchClipboard.getWorkbenchClipboard().add(particle);
            }
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages.XSDCopyConceptAction_ErrorMsg, e.getLocalizedMessage()));

    }
    // return true;
}

From source file:com.amalto.workbench.actions.XSDDeleteIdentityConstraintAction.java

License:Open Source License

public IStatus doAction() {
    try {//from  www  .  j  a  va2 s.c  om

        // xsdIdenty is to support the multiple delete action on key press,
        // which each delete action on identity must be explicit passed a xsd key to
        // delete
        XSDIdentityConstraintDefinition constraint = xsdIdenty;
        XSDElementDeclaration decl = null;
        if (constraint != null) {
            decl = (XSDElementDeclaration) constraint.getContainer();
            if (decl == null)
                return Status.CANCEL_STATUS;
        }

        if (decl == null) {
            IStructuredSelection selection = (IStructuredSelection) page.getTreeViewer().getSelection();
            constraint = (XSDIdentityConstraintDefinition) selection.getFirstElement();
            decl = (XSDElementDeclaration) constraint.getContainer();
        }
        /*
         * REMOVE so that simple elements can be made if (
         * (constraint.getIdentityConstraintCategory().equals(XSDIdentityConstraintCategory.UNIQUE_LITERAL)) &&
         * (decl.getContainer().equals(decl.getSchema())) ) { MessageDialog.openError(
         * this.page.getSite().getShell(), "Error", "Entities must have an unique key" ); return; }
         */

        decl.getIdentityConstraintDefinitions().remove(constraint);
        decl.updateElement();
        xsdIdenty = null;
        page.refresh();
        page.markDirty();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages.XSDDeleteXX_ErrorMsg, e.getLocalizedMessage()));
        return Status.CANCEL_STATUS;
    }
    return Status.OK_STATUS;
}

From source file:com.amalto.workbench.actions.XSDEditFacetAction.java

License:Open Source License

@Override
public IStatus doAction() {
    try {//from   ww  w.  j a  v  a  2 s. c  o  m

        IStructuredSelection selection = (IStructuredSelection) page.getTreeViewer().getSelection();

        XSDComponent xSDCom = null;
        if (selection.getFirstElement() instanceof XSDSimpleTypeDefinition) {
            std = (XSDSimpleTypeDefinition) selection.getFirstElement();
        } else {
            TreePath tPath = ((TreeSelection) selection).getPaths()[0];
            for (int i = 0; i < tPath.getSegmentCount(); i++) {
                if (tPath.getSegment(i) instanceof XSDSimpleTypeDefinition) {
                    std = (XSDSimpleTypeDefinition) (tPath.getSegment(i));
                }
            }
        }
        // std = (XSDSimpleTypeDefinition)((IStructuredSelection)selection).getFirstElement();
        /**
         * totalDigits, fractionDigits, maxInclusive, maxExclusive, minInclusive, minExclusive
         */
        if (facetName.equals("pattern")) {//$NON-NLS-1$
            editPattern();
        } else if (facetName.equals("enumeration")) {//$NON-NLS-1$
            editEnumeration();
        } else if (facetName.equals("length")) {//$NON-NLS-1$
            editLength();
        } else if (facetName.equals("minLength")) {//$NON-NLS-1$
            editMinLength();
        } else if (facetName.equals("maxLength")) {//$NON-NLS-1$
            editMaxLength();
        } else if (facetName.equals("totalDigits")) {//$NON-NLS-1$
            editTotalDigits();
        } else if (facetName.equals("fractionDigits")) {//$NON-NLS-1$
            editFractionDigits();
        } else if (facetName.equals("maxInclusive")) {//$NON-NLS-1$
            editMaxInclusive();
        } else if (facetName.equals("maxExclusive")) {//$NON-NLS-1$
            editMaxExclusive();
        } else if (facetName.equals("minInclusive")) {//$NON-NLS-1$
            editMinInclusive();
        } else if (facetName.equals("minExclusive")) {//$NON-NLS-1$
            editMinExclusive();
        } else if (facetName.equals("whiteSpace")) {//$NON-NLS-1$
            editWhiteSpace();
        }

        else {
            MessageDialog.openError(page.getSite().getShell(), Messages._Error,
                    Messages.bind(Messages.XSDEditFacetAction_ErrorMsg1, facetName));
            return Status.CANCEL_STATUS;
        }

        std.updateElement();

        page.getTreeViewer().refresh(true);
        page.markDirty();
        page.refresh();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages.XSDEditFacetAction_ErrorMsg2, e.getLocalizedMessage()));
        return Status.CANCEL_STATUS;
    }
    return Status.OK_STATUS;
}

From source file:com.amalto.workbench.actions.XSDEditParticleAction.java

License:Open Source License

@Override
public IStatus doAction() {
    try {/* w ww .j a  va  2s  . co m*/
        IStructuredSelection selection = (IStructuredSelection) page.getTreeViewer().getSelection();

        String originalXpath = getOriginalXpath();
        String entity = originalXpath.substring(0, originalXpath.indexOf("/")); //$NON-NLS-1$

        selParticle = (XSDParticle) selection.getFirstElement();

        if (!(selParticle.getTerm() instanceof XSDElementDeclaration)) {
            return Status.CANCEL_STATUS;
        }

        XSDElementDeclaration decl = (XSDElementDeclaration) selParticle.getContent();

        XSDElementDeclaration ref = null;
        if (decl.isElementDeclarationReference()) {
            // it is a ref
            ref = decl.getResolvedElementDeclaration();
        }

        EList eDecls = decl.getSchema().getElementDeclarations();

        ArrayList<String> elementDeclarations = new ArrayList<String>();
        for (Iterator iter = eDecls.iterator(); iter.hasNext();) {
            XSDElementDeclaration d = (XSDElementDeclaration) iter.next();
            if (d.getTargetNamespace() != null
                    && d.getTargetNamespace().equals(IConstants.DEFAULT_NAME_SPACE)) {
                continue;
            }

            if (!d.getQName().equals(entity)) {
                elementDeclarations.add(
                        d.getQName() + (d.getTargetNamespace() != null ? " : " + d.getTargetNamespace() : "")); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
        elementDeclarations.add(""); //$NON-NLS-1$

        XSDIdentityConstraintDefinition identify = null;

        XSDXPathDefinition keyPath = null;
        List<Object> keyInfo = Util.getKeyInfo(decl);
        boolean isPK = false;
        if (keyInfo != null && keyInfo.size() > 0) {
            identify = (XSDIdentityConstraintDefinition) keyInfo.get(0);
            keyPath = (XSDXPathDefinition) keyInfo.get(1);
            isPK = true;
        }
        initEleName = decl.getName();
        dialog = new BusinessElementInputDialog(this, page.getSite().getShell(),
                Messages.XSDEditParticleAction_InputDialogTitle, decl.getName(),
                ref == null ? null : ref.getQName(), elementDeclarations, selParticle.getMinOccurs(),
                selParticle.getMaxOccurs(), false, isPK);
        dialog.setBlockOnOpen(true);
        int ret = dialog.open();
        if (ret == Window.CANCEL) {
            return Status.CANCEL_STATUS;
        }
        if (keyPath != null) {
            identify.getFields().remove(keyPath);
        }
        // find reference
        XSDElementDeclaration newRef = null;
        if (!"".equals(refName.trim())) { //$NON-NLS-1$
            newRef = Util.findReference(refName, schema);
            if (newRef == null) {
                MessageDialog.openError(this.page.getSite().getShell(), Messages._Error,
                        Messages.bind(Messages.XSDEditParticleAction_ErrorMsg, refName));
                return Status.CANCEL_STATUS;
            }
        } // ref

        // update validation rule
        Set<String> paths = new HashSet<String>();
        Util.collectElementPaths((IStructuredContentProvider) page.getElementsViewer().getContentProvider(),
                page.getSite(), selParticle, paths, null);
        //

        decl.setName("".equals(this.elementName) ? null : this.elementName); //$NON-NLS-1$
        if (keyPath != null) {
            XSDFactory factory = XSDSchemaBuildingTools.getXSDFactory();
            XSDXPathDefinition field = factory.createXSDXPathDefinition();
            field.setVariety(keyPath.getVariety());
            field.setValue(elementName);
            identify.getFields().add(field);
        }

        if (newRef != null) {
            decl.setResolvedElementDeclaration(newRef);
            decl.setTypeDefinition(null);
            Element elem = decl.getElement();
            if (elem.getAttributes().getNamedItem("type") != null) {
                elem.getAttributes().removeNamedItem("type");//$NON-NLS-1$
            }
            decl.updateElement();
        } else if (ref != null) {
            // fliu
            // no more element declarations --> we create a new Declaration with String simpleType definition
            // instead
            // FIXME: dereferecning and element is buggy

            XSDFactory factory = XSDSchemaBuildingTools.getXSDFactory();
            XSDElementDeclaration newD = factory.createXSDElementDeclaration();
            newD.setName(this.elementName);
            newD.updateElement();
            XSDSimpleTypeDefinition stringType = ((SchemaTreeContentProvider) page.getTreeViewer()
                    .getContentProvider()).getXsdSchema().getSchemaForSchema()
                            .resolveSimpleTypeDefinition(XSDConstants.SCHEMA_FOR_SCHEMA_URI_2001, "string"); //$NON-NLS-1$

            newD.setTypeDefinition(stringType);
            if (selParticle.getContainer() instanceof XSDModelGroup) {
                XSDModelGroup group = ((XSDModelGroup) selParticle.getContainer());
                ((XSDModelGroup) selParticle.getContainer()).getContents().remove(selParticle);
                selParticle = factory.createXSDParticle();
                selParticle.setContent(newD);
                group.getContents().add(selParticle);
            }
        }

        if (Util.changeElementTypeToSequence(decl, maxOccurs) == Status.CANCEL_STATUS) {
            return Status.CANCEL_STATUS;
        }

        selParticle.setMinOccurs(this.minOccurs);
        if (maxOccurs > -1) {
            selParticle.setMaxOccurs(this.maxOccurs);
        } else {
            if (selParticle.getElement().getAttributeNode("maxOccurs") != null) {
                selParticle.getElement().getAttributeNode("maxOccurs").setNodeValue("unbounded");//$NON-NLS-1$//$NON-NLS-2$
            } else {
                selParticle.getElement().setAttribute("maxOccurs", "unbounded");//$NON-NLS-1$//$NON-NLS-2$
            }
        }

        selParticle.updateElement();

        updateReference(originalXpath);

        if (elementExAdapter != null) {
            elementExAdapter.renameElement(decl.getSchema(), paths, decl.getName());
        }
        if (mapinfoExAdapter != null) {
            mapinfoExAdapter.renameElementMapinfo(paths, decl.getName());
        }

        page.refresh();
        page.markDirty();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages.XSDEditParticleAction_ErrorMsg1, e.getLocalizedMessage()));
        return Status.CANCEL_STATUS;
    }

    return Status.OK_STATUS;
}

From source file:com.amalto.workbench.actions.XSDEditXPathAction.java

License:Open Source License

public IStatus doAction() {
    try {/*from  w w w. j  av  a 2 s.  co  m*/
        IStructuredSelection selection = (IStructuredSelection) page.getTreeViewer().getSelection();
        XSDXPathDefinition xpath = (XSDXPathDefinition) selection.getFirstElement();
        icd = (XSDIdentityConstraintDefinition) xpath.getContainer();

        // InputDialog id = new InputDialog(
        // page.getSite().getShell(),
        // "Edit XPath",
        // "Enter a new XPath for the "+((xpath.getVariety().equals(XSDXPathVariety.FIELD_LITERAL))?"field":"selector"),
        // xpath.getValue(),
        // new IInputValidator() {
        // public String isValid(String newText) {
        // if ((newText==null) || "".equals(newText)) return "The XPath cannot be empty";
        // return null;
        // };
        // }
        // );
        // List<String> childNames = Util.getChildElementNames("", (XSDElementDeclaration) icd.getContainer());
        List<String> childNames = new ArrayList<String>();
        childNames.add("."); //$NON-NLS-1$
        SelectFieldDialog id = new SelectFieldDialog(page.getSite().getShell(),
                Messages.XSDEditXPathAction_DialogTitle, childNames, xpath.getValue());
        id.create();
        id.setBlockOnOpen(true);
        int ret = id.open();
        if (ret == Window.CANCEL) {
            return Status.CANCEL_STATUS;
        }
        String field = id.getField();
        if (field.length() == 0)
            return Status.CANCEL_STATUS;
        XSDXPathDefinition newXpath = XSDSchemaBuildingTools.getXSDFactory().createXSDXPathDefinition();
        newXpath.setValue(field);
        if (xpath.getVariety().equals(XSDXPathVariety.FIELD_LITERAL)) {
            int index = icd.getFields().indexOf(xpath);
            newXpath.setVariety(XSDXPathVariety.FIELD_LITERAL);
            icd.getFields().set(index, newXpath);
        } else {
            newXpath.setVariety(XSDXPathVariety.SELECTOR_LITERAL);
            icd.setSelector(newXpath);
        }

        icd.updateElement();
        page.refresh();
        page.getTreeViewer().setSelection(new StructuredSelection(newXpath), true);
        page.markDirty();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages.XSDEditXPathAction_ErrorMsg, e.getLocalizedMessage()));

        return Status.CANCEL_STATUS;
    }
    return Status.OK_STATUS;
}

From source file:com.amalto.workbench.actions.XSDGetXPathAction.java

License:Open Source License

@Override
public IStatus doAction() {
    try {/* w w w. j av a2 s  . c  om*/

        IStructuredSelection selection = (IStructuredSelection) page.getTreeViewer().getSelection();
        XSDParticle particle = (XSDParticle) selection.getFirstElement();
        XSDTerm term = particle.getTerm();

        if (!(term instanceof XSDElementDeclaration))
            return Status.CANCEL_STATUS;

        Clipboard clipboard = Util.getClipboard();

        String path = ""; //$NON-NLS-1$
        TreeItem item = page.getTreeViewer().getTree().getSelection()[0];
        do {
            XSDConcreteComponent component = (XSDConcreteComponent) item.getData();
            if (component instanceof XSDParticle) {
                if (((XSDParticle) component).getTerm() instanceof XSDElementDeclaration)
                    path = "/" + ((XSDElementDeclaration) ((XSDParticle) component).getTerm()).getName() + path; //$NON-NLS-1$
            } else if (component instanceof XSDElementDeclaration) {
                path = ((XSDElementDeclaration) component).getName() + path;
            }
            // System.out.println("          "+path+ "             $$"+component.toString()+"$$");
            item = item.getParentItem();
        } while (item != null);

        xpath = path;

        clipboard.setContents(new Object[] { path }, new Transfer[] { TextTransfer.getInstance() });
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages.XSDGetXPathAction_ErrorMsg, e.getLocalizedMessage()));
        return Status.CANCEL_STATUS;
    }
    return Status.OK_STATUS;
}

From source file:com.amalto.workbench.actions.XSDNewGroupFromParticleAction.java

License:Open Source License

public IStatus doAction() {
    try {// w w  w.  ja v a 2  s  . co m
        IStructuredSelection selection = (IStructuredSelection) page.getTreeViewer().getSelection();
        selParticle = (XSDParticle) selection.getFirstElement();

        if (!(selParticle.getContainer() instanceof XSDModelGroup))
            return Status.CANCEL_STATUS;

        XSDModelGroup group = (XSDModelGroup) selParticle.getContainer();
        // get position of the selected particle in the container
        int index = 0;
        int i = 0;
        for (Iterator iter = group.getContents().iterator(); iter.hasNext();) {
            XSDParticle p = (XSDParticle) iter.next();
            if (p.equals(selParticle)) {
                index = i;
                break;
            }
            i++;
        }

        dialog = new NewGroupDialog(this, page.getSite().getShell());
        dialog.setBlockOnOpen(true);
        int ret = dialog.open();
        if (ret == Dialog.CANCEL) {
            return Status.CANCEL_STATUS;
        }

        XSDFactory factory = XSDSchemaBuildingTools.getXSDFactory();

        // add an element declaration
        XSDElementDeclaration subElement = factory.createXSDElementDeclaration();
        subElement.setName("subelement");//$NON-NLS-1$
        subElement.setTypeDefinition(
                schema.resolveSimpleTypeDefinition(schema.getSchemaForSchemaNamespace(), "string"));//$NON-NLS-1$

        XSDParticle subParticle = factory.createXSDParticle();
        subParticle.setMinOccurs(1);
        subParticle.setMaxOccurs(1);
        subParticle.setContent(subElement);
        subParticle.updateElement();

        XSDModelGroup newGroup = factory.createXSDModelGroup();
        if (isChoice)
            newGroup.setCompositor(XSDCompositor.CHOICE_LITERAL);
        else if (isAll)
            newGroup.setCompositor(XSDCompositor.ALL_LITERAL);
        else
            newGroup.setCompositor(XSDCompositor.SEQUENCE_LITERAL);
        newGroup.getContents().add(0, subParticle);
        newGroup.updateElement();

        XSDParticle particle = factory.createXSDParticle();
        particle.setContent(newGroup);
        particle.setMinOccurs(this.minOccurs);
        particle.setMaxOccurs(this.maxOccurs);

        group.getContents().add(index + 1, particle);
        group.updateElement();

        page.refresh();
        page.getTreeViewer().setSelection(new StructuredSelection(particle), true);

        page.markDirty();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages.XSDNewGroupFromParticleAction_ErrorMsg, e.getLocalizedMessage()));

        return Status.CANCEL_STATUS;
    }

    return Status.CANCEL_STATUS;
}

From source file:com.amalto.workbench.actions.XSDNewGroupFromTypeAction.java

License:Open Source License

public IStatus doAction() {
    try {//from   w  w w. j a v  a  2  s .c  o  m

        IStructuredSelection selection = (IStructuredSelection) page.getTreeViewer().getSelection();
        if (selection.getFirstElement() instanceof XSDComplexTypeDefinition) {
            XSDComplexTypeDefinition ctd = (XSDComplexTypeDefinition) selection.getFirstElement();
            if (!(ctd.getContent() instanceof XSDParticle))
                return Status.CANCEL_STATUS;
            if (!(((XSDParticle) ctd.getContent()).getTerm() instanceof XSDModelGroup))
                return Status.CANCEL_STATUS;
            group = (XSDModelGroup) ((XSDParticle) ctd.getContent()).getTerm();
        } else if (selection.getFirstElement() instanceof XSDParticle) {
            group = (XSDModelGroup) ((XSDParticle) selection.getFirstElement()).getTerm();
        } else {
            return Status.CANCEL_STATUS;
        }

        dialog = new NewGroupDialog(this, page.getSite().getShell());
        dialog.setBlockOnOpen(true);
        int ret = dialog.open();
        if (ret == Window.CANCEL) {
            return Status.CANCEL_STATUS;
        }

        XSDFactory factory = XSDSchemaBuildingTools.getXSDFactory();

        // add an element declaration
        XSDElementDeclaration subElement = factory.createXSDElementDeclaration();
        subElement.setName("subelement");//$NON-NLS-1$
        subElement.setTypeDefinition(
                schema.resolveSimpleTypeDefinition(schema.getSchemaForSchemaNamespace(), "string"));//$NON-NLS-1$

        XSDParticle subParticle = factory.createXSDParticle();
        subParticle.setMinOccurs(1);
        subParticle.setMaxOccurs(1);
        subParticle.setContent(subElement);
        subParticle.updateElement();

        XSDModelGroup newGroup = factory.createXSDModelGroup();
        if (isChoice)
            newGroup.setCompositor(XSDCompositor.CHOICE_LITERAL);
        else if (isAll)
            newGroup.setCompositor(XSDCompositor.ALL_LITERAL);
        else
            newGroup.setCompositor(XSDCompositor.SEQUENCE_LITERAL);
        newGroup.getContents().add(0, subParticle);
        newGroup.updateElement();

        XSDParticle particle = factory.createXSDParticle();
        particle.setContent(newGroup);
        particle.setMinOccurs(this.minOccurs);
        particle.setMaxOccurs(this.maxOccurs);

        group.getContents().add(0, particle);
        group.updateElement();

        page.refresh();
        page.getTreeViewer().setSelection(new StructuredSelection(particle), true);
        page.markDirty();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(page.getSite().getShell(), Messages._Error,
                Messages.bind(Messages.XSDNewGroupFromTypeAction_ErrorMsg, e.getLocalizedMessage()));
        return Status.CANCEL_STATUS;
    }

    return Status.OK_STATUS;
}