Example usage for org.eclipse.jdt.core IJavaElement getCorrespondingResource

List of usage examples for org.eclipse.jdt.core IJavaElement getCorrespondingResource

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaElement getCorrespondingResource.

Prototype

IResource getCorrespondingResource() throws JavaModelException;

Source Link

Document

Returns the resource that corresponds directly to this element, or null if there is no resource that corresponds to this element.

Usage

From source file:com.android.ide.eclipse.cheatsheets.actions.SetBreakpoint.java

License:Open Source License

public void run(final String[] params, ICheatSheetManager manager) {
    // param1 - project
    // param2 - path
    // param3 - type name
    // param4 - line number
    if (params == null || params[0] == null || params[1] == null || params[2] == null || params[3] == null) {
        return;/*from  w ww  . ja va  2s  .co m*/
    }
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();

    IProject project = workspaceRoot.getProject(params[0]);
    if (project == null || !project.isOpen()) {
        Activator.log("Invalid the project " + params[0] + ".");
        return;
    }
    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject == null || !javaProject.isOpen()) {
        Activator.log("Invalid the project: " + params[0] + ".");
        return;
    }
    IJavaElement element;
    try {
        element = javaProject.findElement(new Path(params[1]));

        if (element == null) {
            Activator.log("Invalid the path: " + params[1] + ".");
            return;
        }
        resource = element.getCorrespondingResource();
        if (resource == null || resource.getType() != IResource.FILE) {
            Activator.log("Invalid the path: " + params[1] + ".");
            return;
        }
    } catch (JavaModelException e1) {
        Activator.log("Invalid the " + params[1] + " path.");
        return;
    }
    String tname = params[2];
    Display.getDefault().syncExec(new Runnable() {

        public void run() {
            editor = openEditor(params, (IFile) resource);
        }
    });
    if (editor == null) {
        Activator.log("Cannot open the " + " " + params[0] + "file.");
        return;
    }
    try {
        //String markerType = "org.eclipse.jdt.debug.javaLineBreakpointMarker";
        int lnumber;
        try {
            lnumber = new Integer(params[3]).intValue();
        } catch (NumberFormatException e) {
            Activator.log("Invalid line number " + params[1]);
            return;
        }
        Map attributes = new HashMap(10);
        IDocumentProvider documentProvider = editor.getDocumentProvider();
        if (documentProvider == null) {
            return;
        }
        IDocument document = documentProvider.getDocument(editor.getEditorInput());
        int charstart = -1, charend = -1;
        try {
            IRegion line = document.getLineInformation(lnumber - 1);
            charstart = line.getOffset();
            charend = charstart + line.getLength();
        } catch (BadLocationException e) {
            Activator.log(e);
        }
        //BreakpointUtils.addJavaBreakpointAttributes(attributes, type);

        String handleId = element.getHandleIdentifier();
        attributes.put(HANDLE_ID, handleId);
        JavaCore.addJavaElementMarkerAttributes(attributes, element);
        IJavaLineBreakpoint breakpoint = JDIDebugModel.createLineBreakpoint(resource, tname, lnumber, charstart,
                charend, 0, true, attributes);

        IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager();
        breakpointManager.addBreakpoint(breakpoint);
    } catch (CoreException e) {
        Activator.log(e);
    }
}

From source file:de.loskutov.eclipse.jdepend.views.TreeFolder.java

License:Open Source License

public TreeFolder(IJavaElement javaElement) {
    super();//from  www  .  java 2s.  c o m
    this.javaElement = javaElement;
    children = new ArrayList<TreeObject>();
    iJavaElements = new ArrayList<IJavaElement>();
    addIJavaElement(javaElement);
    if (javaElement != null) {
        try {
            setIResource(javaElement.getCorrespondingResource());
        } catch (JavaModelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:de.plugins.eclipse.depclipse.model.TreeFolder.java

License:Open Source License

public TreeFolder(IJavaElement javaElement) {
    super();//from w ww  .  ja  va 2  s.  co  m
    this.javaElement = javaElement;
    children = new ArrayList<TreeObject>();
    iJavaElements = new ArrayList<IJavaElement>();
    addIJavaElement(javaElement);
    if (javaElement != null) {
        try {
            setIResource(javaElement.getCorrespondingResource());
        } catch (JavaModelException e) {
            // just do nothing here
        }
    }
}

From source file:de.tobject.findbugs.builder.WorkItem.java

License:Open Source License

public @CheckForNull IResource getCorespondingResource() {
    if (resource != null) {
        return resource;
    }/* www  . j  a  va2 s . c o m*/
    try {
        IResource resource1 = javaElt.getCorrespondingResource();
        if (resource1 != null) {
            return resource1;
        }
        IJavaElement ancestor = javaElt.getAncestor(IJavaElement.COMPILATION_UNIT);
        if (ancestor != null) {
            return ancestor.getCorrespondingResource();
        }
    } catch (JavaModelException e) {
        // ignore, just return nothing
    }
    return null;
}

From source file:edu.utdallas.fdaf.aspectj.reverse.internal.actions.UMLFromAspectJAction.java

License:Open Source License

/**
* Return the container associated with the selected IJavaElement
* @return the initial container//from   www. ja  v  a  2  s  .com
*/
protected IContainer getInitialContainer() {
    IContainer container = null;
    if (javaElements.size() > 0)

    {
        IJavaElement javaElement = javaElements.get(0);
        try {
            container = (IContainer) javaElement.getCorrespondingResource();
        } catch (JavaModelException e) {
            Activator.log(e);
            //                ReversePlugin.log(e);
        }
    }

    return container;
}

From source file:edu.washington.cs.cupid.jdt.types.JavaResourceAdapter.java

License:Open Source License

@Override
public IResource adapt(IJavaElement input) {
    try {//w  ww.ja  v  a2 s .co  m
        return input.getCorrespondingResource();
    } catch (JavaModelException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.wpi.cs.jburge.SEURAT.actions.AssociateArtifactAction.java

License:Open Source License

/** Executes the association. We get our selected rationale item and 
 * associated it with the java element selected.
 * //from   w  w  w. ja  v a  2  s  . c  o m
 */
public void run() {
    //Get our selected items. Send a message to the user to confirm that
    //this is the correct association.
    if (navigatorSelection != null) {
        ISelection selection = viewer.getSelection();
        obj = ((IStructuredSelection) selection).getFirstElement();
        if (obj instanceof TreeParent) {
            String assQ = "Associate '" + ((TreeParent) obj).getName() + "' with "
                    + navigatorSelection.getElementName() + "?";

            boolean selOk = showQuestion(assQ);
            //            showMessage(navigatorSelection.getHandleIdentifier());
            //            System.out.println(navigatorSelection.getHandleIdentifier());
            if (selOk) {
                cstart = 0;

                ourRes = null;
                try {

                    if (navigatorSelection.getElementType() == IJavaElement.COMPILATION_UNIT) {
                        ourRes = navigatorSelection.getCorrespondingResource();
                    } else {
                        ourRes = navigatorSelection.getUnderlyingResource();
                        if (ourRes != null) {
                            //                        ***                        System.out.println("this one wasn't null?");
                        }
                        //find the enclosing class file
                        IJavaElement nextE = navigatorSelection.getParent();
                        while ((nextE != null) && (nextE.getElementType() != IJavaElement.COMPILATION_UNIT)) {
                            //                        ***                        System.out.println("Name = " + nextE.getElementName());
                            //                        ***                     System.out.println("Type = " + nextE.getElementType());
                            nextE = nextE.getParent();
                        }
                        try {
                            //                        ***                     System.out.println("getting our resource");
                            //                  ourRes = nextE.getUnderlyingResource();
                            ourRes = nextE.getCorrespondingResource();
                            ourRes = nextE.getResource();
                        } catch (JavaModelException ex) {
                            System.out.println("exception getting resource?");
                        }
                        //                     ***                     System.out.println("Final name = " + nextE.getElementName());
                        //                     ***                     System.out.println("Final type = " + nextE.getElementType());
                        if (ourRes == null) {
                            //see if we can get the element from the working copy
                            IJavaElement original = nextE.getPrimaryElement();
                            //                        Get working copy has been deprecated
                            //                        IJavaElement original = ((ICompilationUnit) ((ICompilationUnit) nextE).getWorkingCopy()).getOriginalElement();
                            ourRes = original.getCorrespondingResource();

                        }
                    }
                    //                  ourRes = navigatorSelection.getUnderlyingResource();
                    if (ourRes == null) {
                        //                     ***                     System.out.println("why would our resource be null?");
                    }
                    //                  ***                  System.out.println("FullPath = " + ourRes.getFullPath().toString());
                    //                  ***                  System.out.println("now checking file extension?");
                    if (ourRes.getFullPath().getFileExtension().compareTo("java") == 0) {
                        //                     ***                     System.out.println("creating our file?");
                        IJavaElement myJavaElement = JavaCore.create((IFile) ourRes);
                        //                     ***                  System.out.println("created an element?");
                        if (myJavaElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                            //                        ***                     System.out.println("Compilation Unit");
                            ICompilationUnit myCompilationUnit = (ICompilationUnit) myJavaElement;

                            IType[] myTypes = myCompilationUnit.getTypes();
                            boolean found = false;
                            int i = 0;
                            while ((!found) && i < myTypes.length) {
                                //selected item was the class itself
                                if (navigatorSelection.getElementType() == IJavaElement.COMPILATION_UNIT) {
                                    //                              ***                            System.out.println("found the class");
                                    if (myTypes[i].isClass()) {
                                        found = true;
                                        cstart = myTypes[i].getNameRange().getOffset();
                                    }
                                } else if (navigatorSelection.getElementType() == IJavaElement.FIELD) {
                                    //                              ***                            System.out.println("looking for types");
                                    IField[] myFields = myTypes[i].getFields();
                                    for (int j = 0; j < myFields.length; j++) {
                                        if (myFields[j].getElementName()
                                                .compareTo(navigatorSelection.getElementName()) == 0) {
                                            //                                    ***                               System.out.println("found a type");
                                            found = true;
                                            cstart = myFields[j].getNameRange().getOffset();
                                        }
                                    }

                                } else if (navigatorSelection.getElementType() == IJavaElement.METHOD) {
                                    //                              ***                            System.out.println("looking for a method");
                                    IMethod[] myMethods = myTypes[i].getMethods();
                                    for (int j = 0; j < myMethods.length; j++) {
                                        if (myMethods[j].getElementName()
                                                .compareTo(navigatorSelection.getElementName()) == 0) {
                                            //                                    ***                               System.out.println("found a method");
                                            found = true;
                                            cstart = myMethods[j].getNameRange().getOffset();
                                        }
                                    }
                                }
                                //don't forget to increment!
                                i++;
                            } //end while
                        } else {
                            //                        ***                      System.out.println("not a compilation unit?");
                            System.out.println(myJavaElement.getElementType());
                        }
                        //ok... now what type is our selected item? 
                        System.out.println("got the resource?");
                        if (ourRes == null) {
                            System.out.println("null resource???");
                        }
                    } else {
                        System.out.println("not a java file?");
                    }
                    //                  from the newsgroup - in a runnable?                  
                    ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
                        public void run(IProgressMonitor monitor) {
                            try {
                                //                           ***                  System.out.println("line number = " + new Integer(lineNumber).toString());
                                IMarker ratM = ourRes.createMarker("SEURAT.ratmarker");
                                String dbname = RationaleDB.getDbName();
                                String markD = "Alt: '" + ((TreeParent) obj).getName() + "'   Rationale DB: '"
                                        + dbname + "'";
                                ratM.setAttribute(IMarker.MESSAGE, markD);
                                ratM.setAttribute(IMarker.CHAR_START, cstart);
                                ratM.setAttribute(IMarker.CHAR_END, cstart + 1);
                                ratM.setAttribute(IMarker.SEVERITY, 0);
                                String artName = navigatorSelection.getElementName();
                                ratM.setAttribute("alternative", ((TreeParent) obj).getName());
                                SEURATResourcePropertiesManager.addPersistentProperty(ourRes, "Rat", "true");
                                RationaleDB d = RationaleDB.getHandle();
                                d.associateAlternative(((TreeParent) obj).getName(),
                                        navigatorSelection.getHandleIdentifier(), ourRes.getName(), artName,
                                        markD);

                            } catch (CoreException e) {
                                e.printStackTrace();
                            }
                        }
                    }, null);
                    //                  ***                  System.out.println("adding persistent property");

                    SEURATDecoratorManager.addSuccessResources(ourRes);
                    //                  ***                  System.out.println("added our property");  
                    // Refresh the label decorations... Change it to DemoDecoratorWithImageCaching if image caching should be used
                    //                  ((TreeParent) obj).setStatus(RationaleErrorLevel.ERROR);
                    viewer.update((TreeParent) obj, null);
                    SEURATLightWeightDecorator.getRatDecorator().refresh();
                    //                  ***                  System.out.println("refresh");

                } catch (Exception ex) {
                    ex.printStackTrace();
                    System.out.println("an exception occured in AssociateArtifactAction");
                }

            } else
                System.out.println("selection rejected");
        }
    } else {
        System.out.println("No java element selected...");
    }
}

From source file:edu.wpi.cs.jburge.SEURAT.actions.RemoveRationaleAssociation.java

License:Open Source License

/**
 * This is when the action really runs//from w w w. j a  v  a 2 s . c om
 * @param action - not used
 */
public void run(IAction action) {
    IJavaElement navigatorSelection;
    //      ***      System.out.println("removing association");
    if (selection.getFirstElement() instanceof IJavaElement) {
        //         ***         System.out.println("we are a java element");
        navigatorSelection = (IJavaElement) selection.getFirstElement();
        ourRes = null;

        boolean proceed = showQuestion("Do you want to delete all associations to this file?");
        if (!proceed) {
            return;
        }

        //find the associated resource that goes with the element
        try {
            if (navigatorSelection.getElementType() == IJavaElement.COMPILATION_UNIT) {
                ourRes = navigatorSelection.getCorrespondingResource();

            } else {
                ourRes = navigatorSelection.getUnderlyingResource();
                if (ourRes != null) {
                    //                  ***                  System.out.println("this one wasn't null?");
                }
                //find the enclosing class file
                IJavaElement nextE = navigatorSelection.getParent();
                while ((nextE != null) && (nextE.getElementType() != IJavaElement.COMPILATION_UNIT)) {
                    //                  ***                  System.out.println("Name = " + nextE.getElementName());
                    //                  ***                  System.out.println("Type = " + nextE.getElementType());
                    nextE = nextE.getParent();
                }
                try {
                    //                  ***                  System.out.println("getting our resource");
                    //                  ourRes = nextE.getUnderlyingResource();
                    ourRes = nextE.getCorrespondingResource();
                    ourRes = nextE.getResource();
                } catch (JavaModelException ex) {
                    //                  ***                  System.out.println("exception getting resource?");
                }
                System.out.println("Final name = " + nextE.getElementName());
                System.out.println("Final type = " + nextE.getElementType());
                if (ourRes == null) {
                    //                  ***                  System.out.println("see if there's a working copy");
                    IJavaElement original = nextE.getPrimaryElement();
                    //see if we can get the element from the working copy
                    //                  IJavaElement original = ((IWorkingCopy) ((ICompilationUnit) nextE).getWorkingCopy()).getOriginalElement();
                    ourRes = original.getCorrespondingResource();
                }
            }
            //                  ourRes = navigatorSelection.getUnderlyingResource();
            if (ourRes == null) {
                //               ***               System.out.println("why would our resource be null?");
            }
            //            ***            System.out.println("FullPath = " + ourRes.getFullPath().toString());
            //            ***            System.out.println("now checking file extension?");
            if (ourRes.getFullPath().getFileExtension().compareTo("java") == 0) {
                //               ***               System.out.println("creating our file?");
                IJavaElement myJavaElement = JavaCore.create((IFile) ourRes);
                //               ***                  System.out.println("created an element?");
                if (myJavaElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                    //                  ***                  System.out.println("Compilation Unit");
                    ICompilationUnit myCompilationUnit = (ICompilationUnit) myJavaElement;

                    IType[] myTypes = myCompilationUnit.getTypes();
                    boolean found = false;
                    int i = 0;
                    while ((!found) && i < myTypes.length) {
                        //selected item was the class itself
                        if (navigatorSelection.getElementType() == IJavaElement.COMPILATION_UNIT) {
                            //                        ***                     System.out.println("found the class");
                            if (myTypes[i].isClass()) {
                                found = true;
                            }
                        } else if (navigatorSelection.getElementType() == IJavaElement.FIELD) {
                            //                        ***                     System.out.println("looking for types");
                            IField[] myFields = myTypes[i].getFields();
                            for (int j = 0; j < myFields.length; j++) {
                                if (myFields[j].getElementName()
                                        .compareTo(navigatorSelection.getElementName()) == 0) {
                                    //                              ***                           System.out.println("found a type");
                                    found = true;
                                }
                            }

                        } else if (navigatorSelection.getElementType() == IJavaElement.METHOD) {
                            //                        ***                     System.out.println("looking for a method");
                            IMethod[] myMethods = myTypes[i].getMethods();
                            for (int j = 0; j < myMethods.length; j++) {
                                if (myMethods[j].getElementName()
                                        .compareTo(navigatorSelection.getElementName()) == 0) {
                                    //                              ***                           System.out.println("found a method");
                                    found = true;
                                }
                            }
                        }
                        //don't forget to increment!
                        i++;
                    } //end while

                } else {
                    //                  ***                  System.out.println("not a compilation unit?");
                    //                  ***                  System.out.println(myJavaElement.getElementType());
                }
                //ok... now what type is our selected item? 
                //               ***               System.out.println("got the resource?");
                if (ourRes == null) {
                    //                  ***                  System.out.println("null resource???");
                }
            } else {
                //               ***                  System.out.println("not a java file?");
            }
            //            from the newsgroup - in a runnable?                  
            ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
                public void run(IProgressMonitor monitor) {
                    try {
                        //                     ***                           System.out.println("removing our markers, etc.");
                        //                     ourResource.setPersistentProperty()
                        SEURATResourcePropertiesManager.addPersistentProperty(ourRes, "Rat", "false");
                        SEURATDecoratorManager.addSuccessResources(ourRes);
                        ourRes.deleteMarkers("SEURAT.ratmarker", true, IResource.DEPTH_INFINITE);
                        RationaleDB d = RationaleDB.getHandle();
                        d.removeAssociation(ourRes.getName());
                    } catch (CoreException e) {
                        e.printStackTrace();
                    }
                }
            }, null);

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("an exception occured in AssociateArtifactAction");
        }
    }

}

From source file:edu.wpi.cs.jburge.SEURAT.actions.RestoreAssociations.java

License:Open Source License

/**
 * This is where the action takes place when the restore is invoked from the SEURAT pull-down menu.
 *//*from  ww  w  .  j av  a  2 s  .c  o m*/
public void run() {
    //find all our resources
    RationaleDB d = RationaleDB.getHandle();
    Vector<Association> ourResources = d.getAssociations();
    Iterator<Association> resI = ourResources.iterator();
    try {

        while (resI.hasNext()) {
            cstart = 0;
            ourAssoc = (Association) resI.next();
            String ourArtifact = ourAssoc.getArtifact();

            //System.out.println(ourArtifact);
            //System.out.println(ourAssoc.getResource());
            try {
                // We create the java element from its artifact that is stored in the DB
                // and then search through the resource to find out where the marker needs to be placed.
                IJavaElement ourEle = JavaCore.create(ourArtifact);
                //System.out.println(ourEle.getElementName() + " " + ourEle.getElementType());

                if (ourEle.getElementType() == IJavaElement.COMPILATION_UNIT) {
                    ourRes = ourEle.getCorrespondingResource();
                } else {
                    ourRes = ourEle.getUnderlyingResource();
                    if (ourRes != null) {
                        //                     ***                        System.out.println("this one wasn't null?");
                    }
                    //find the enclosing class file
                    IJavaElement nextE = ourEle.getParent();
                    while ((nextE != null) && (nextE.getElementType() != IJavaElement.COMPILATION_UNIT)) {
                        //                     ***                        System.out.println("Name = " + nextE.getElementName());
                        //                     ***                     System.out.println("Type = " + nextE.getElementType());
                        nextE = nextE.getParent();
                    }
                    try {
                        //                     ***                     System.out.println("getting our resource");
                        //                  ourRes = nextE.getUnderlyingResource();
                        ourRes = nextE.getCorrespondingResource();
                        ourRes = nextE.getResource();
                    } catch (JavaModelException ex) {
                        System.out.println("exception getting resource?");
                    }
                    //                  ***                     System.out.println("Final name = " + nextE.getElementName());
                    //                  ***                     System.out.println("Final type = " + nextE.getElementType());
                    if (ourRes == null) {
                        //                     ***                        System.out.println("see if there's a working copy");
                        IJavaElement original = nextE.getPrimaryElement();
                        //see if we can get the element from the working copy
                        //                     IJavaElement original = ((IWorkingCopy) ((ICompilationUnit) nextE).getWorkingCopy()).getOriginalElement();
                        ourRes = original.getCorrespondingResource();
                    }
                }
                //                  ourRes = navigatorSelection.getUnderlyingResource();
                if (ourRes == null) {
                    //                  ***                     System.out.println("why would our resource be null?");
                }
                //               ***                  System.out.println("FullPath = " + ourRes.getFullPath().toString());
                //               ***                  System.out.println("now checking file extension?");
                if (ourRes.getFullPath().getFileExtension().compareTo("java") == 0) {
                    //                  ***                     System.out.println("creating our file?");
                    IJavaElement myJavaElement = JavaCore.create((IFile) ourRes);
                    //                  ***                  System.out.println("created an element?");
                    if (myJavaElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                        //                     ***                     System.out.println("Compilation Unit");
                        ICompilationUnit myCompilationUnit = (ICompilationUnit) myJavaElement;

                        IType[] myTypes = myCompilationUnit.getTypes();
                        boolean found = false;
                        int i = 0;
                        while ((!found) && i < myTypes.length) {
                            //selected item was the class itself
                            if (ourEle.getElementType() == IJavaElement.COMPILATION_UNIT) {
                                //                           ***                            System.out.println("found the class");
                                if (myTypes[i].isClass()) {
                                    found = true;
                                    cstart = myTypes[i].getNameRange().getOffset();
                                }
                            } else if (ourEle.getElementType() == IJavaElement.FIELD) {
                                //                           ***                            System.out.println("looking for types");
                                IField[] myFields = myTypes[i].getFields();
                                for (int j = 0; j < myFields.length; j++) {
                                    if (myFields[j].getElementName().compareTo(ourEle.getElementName()) == 0) {
                                        //                                 ***                               System.out.println("found a type");
                                        found = true;
                                        cstart = myFields[j].getNameRange().getOffset();
                                    }
                                }

                            } else if (ourEle.getElementType() == IJavaElement.METHOD) {
                                //                           ***                            System.out.println("looking for a method");
                                IMethod[] myMethods = myTypes[i].getMethods();
                                for (int j = 0; j < myMethods.length; j++) {
                                    if (myMethods[j].getElementName().compareTo(ourEle.getElementName()) == 0) {
                                        //                                 ***                         System.out.println("found a method");
                                        found = true;
                                        cstart = myMethods[j].getNameRange().getOffset();
                                    }
                                }
                            }
                            //don't forget to increment!
                            i++;
                        } //end while

                    } else {
                        //                     ***                      System.out.println("not a compilation unit?");
                        System.out.println(myJavaElement.getElementType());
                    }
                    //ok... now what type is our selected item? 
                    System.out.println("got the resource?");
                    if (ourRes == null) {
                        //                     ***                     System.out.println("null resource???");
                    }
                } else {
                    //                  ***                     System.out.println("not a java file?");
                }
                //               from the newsgroup - in a runnable?                  
                ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
                    public void run(IProgressMonitor monitor) {
                        try {
                            //                        ***                  System.out.println("line number = " + new Integer(lineNumber).toString());
                            IMarker ratM = ourRes.createMarker("SEURAT.ratmarker");
                            String markD = ourAssoc.getMsg();
                            ratM.setAttribute(IMarker.MESSAGE, markD);
                            ratM.setAttribute(IMarker.CHAR_START, cstart);
                            ratM.setAttribute(IMarker.CHAR_END, cstart + 1);
                            ratM.setAttribute(IMarker.SEVERITY, 0);
                            System.out.println(cstart);
                            Alternative ourAlt = (Alternative) RationaleDB
                                    .getRationaleElement(ourAssoc.getAlt(), RationaleElementType.ALTERNATIVE);
                            ratM.setAttribute("alternative", ourAlt.getName());
                            SEURATResourcePropertiesManager.addPersistentProperty(ourRes, "Rat", "true");

                        } catch (CoreException e) {
                            e.printStackTrace();
                        }
                    }
                }, null);
                //               ***                  System.out.println("adding persistent property");

                SEURATDecoratorManager.addSuccessResources(ourRes);
                //               ***                  System.out.println("added our property");  
                // Refresh the label decorations... Change it to DemoDecoratorWithImageCaching if image caching should be used
                //               ((TreeParent) obj).setStatus(RationaleErrorLevel.ERROR);
                //              viewer.update((TreeParent) obj, null);
                //for some reason the next line is giving us an exception - ???
                //it doesn't seem to be needed - the decorator appears.
                //         SEURATLightWeightDecorator.getRatDecorator().refresh();
                //               ***                  System.out.println("refresh");

            } catch (Exception e) {
                System.out.println("couldn't create our element " + ourArtifact);
            }

        }
    } catch (Exception ex) {
        System.out.println("exception while trying to add associations");
    }

}

From source file:edu.wpi.cs.jburge.SEURAT.SEURATElementChangedManager.java

License:Open Source License

/**
 * Determines whether a change occurred to an associated artifact, and if it did,
 * handles the change.  It basically works by saving the first element it gets and
 * mapping it to a corresponding element later on (provided that the elements are actually
 * associated with some alternative).  Two exceptions come up: one, if it's a compilation unit,
 * we just use the getMovedToElement() method to take care of the mapping for us (we don't have
 * access to this for single methods due to the confusing/arcane way they decided to code
 * java element changes).  The other exception is also for compilation units- we have to manually check
 * the java elements attached to it such as methods and fields to see if any of those are associated
 * and handle the changes if they are, because we don't get deltas for them.
 * //from w w  w  .ja v  a2s.c o m
 * @param change - the possible change, an IJavaElementDelta
 */
private void handleChange(IJavaElementDelta change) {
    System.out
            .println("HandleChange: " + change.getElement() + " " + change.toString() + " " + change.getKind());
    //System.out.println("Saved Delta: " + savedDelta.getElement() + " " + savedDelta.toString() + " " + savedDelta.getKind());
    IJavaElement movedTo = change.getMovedToElement();
    if (change.getKind() == IJavaElementDelta.ADDED || change.getKind() == IJavaElementDelta.REMOVED) {
        if (change.getKind() == IJavaElementDelta.REMOVED && savedDelta == null && movedTo == null) {
            checkDeltaAndSave(change);
        } else if (change.getKind() == IJavaElementDelta.ADDED && savedDelta == null && movedTo == null) {
            // always save this kind of delta, can't check if in DB without reference to removed delta
            savedDelta = change;
            System.out.println("Saved a delta");
        } else {
            IJavaElement oldElt = null;
            IJavaElement newElt = null;
            if (change.getKind() == IJavaElementDelta.ADDED) {
                // get the saved added delta
                oldElt = savedDelta.getElement();
                newElt = change.getElement();
            } else { // change.getKind() == IJavaElementDelta.REMOVED
                if (movedTo != null) {
                    // process the move
                    checkDeltaAndSave(change); // in this case we're not really saving, just checking
                    newElt = movedTo;
                    oldElt = change.getElement();
                } else {
                    // check the removed delta, then get the saved added delta
                    checkDeltaAndSave(change);
                    if (savedDelta != null) { // sanity check
                        newElt = savedDelta.getElement();
                        oldElt = change.getElement();
                    }
                }
            }
            // Get the saved association and the old artName
            Association ourAssoc = savedAssoc;
            String oldArtName = oldElt.getElementName();
            // Reset the saved delta and association
            savedDelta = null;
            savedAssoc = null;

            // Make sure the association is in the database
            if (ourAssoc != null && ourAssoc.getAlt() != -1) {
                // Find the artifact itself
                IResource newResource = null;
                int cstart = 0;
                IField[] fields = null;
                IMethod[] methods = null;
                try {
                    ICompilationUnit compUnit = null;
                    if (newElt.getElementType() != IJavaElement.COMPILATION_UNIT) {
                        newResource = newElt.getUnderlyingResource();
                        compUnit = (ICompilationUnit) newElt.getAncestor(IJavaElement.COMPILATION_UNIT);
                    } else {
                        newResource = newElt.getCorrespondingResource();
                        compUnit = (ICompilationUnit) newElt;
                    }
                    IType[] myTypes = compUnit.getTypes();
                    boolean found = false;
                    int i = 0;
                    while ((!found) && i < myTypes.length) {
                        //selected item was the class itself
                        if (newElt.getElementType() == IJavaElement.COMPILATION_UNIT) {
                            if (myTypes[i].isClass()) {
                                found = true;
                                cstart = myTypes[i].getNameRange().getOffset();
                                fields = myTypes[i].getFields();
                                methods = myTypes[i].getMethods();
                            }
                        } else if (newElt.getElementType() == IJavaElement.FIELD) {
                            IField[] myFields = myTypes[i].getFields();
                            for (int j = 0; j < myFields.length; j++) {
                                if (myFields[j].getElementName().compareTo(newElt.getElementName()) == 0) {
                                    found = true;
                                    cstart = myFields[j].getNameRange().getOffset();
                                }
                            }
                        } else if (newElt.getElementType() == IJavaElement.METHOD) {
                            IMethod[] myMethods = myTypes[i].getMethods();
                            for (int j = 0; j < myMethods.length; j++) {
                                if (myMethods[j].getElementName().compareTo(newElt.getElementName()) == 0) {
                                    found = true;
                                    cstart = myMethods[j].getNameRange().getOffset();
                                }
                            }
                        }
                        i++;
                    } //end while
                } catch (JavaModelException jme) {
                    System.err.println(jme.toString());
                }
                System.out.println("DEBUG: newresource " + newResource.getName() + " cstart " + cstart);

                // Get new values for association data
                String newRes = newResource.getName();
                String newArtName = newElt.getElementName();
                String newArt = newElt.getHandleIdentifier();

                IResource oldResource = null;
                // Now, the time-consuming part.  If this is a compilation unit, we need to go through
                // all of its fields and methods and if they have associations, update them.
                if (newElt.getElementType() == IJavaElement.COMPILATION_UNIT) {
                    for (int i = 0; i < fields.length; i++) {
                        checkAssocAndUpdate(fields[i], newRes, null);
                    }
                    for (int i = 0; i < methods.length; i++) {
                        String oldSubArtName = methods[i].getElementName();
                        String oldSubArtNameJava = oldSubArtName + ".java";
                        if ((oldSubArtName == oldArtName || oldSubArtNameJava == oldArtName)
                                && oldArtName != newArtName) {
                            // Names of old comp unit and old method are same; this is a constructor, and its name has changed
                            checkAssocAndUpdate(methods[i], newRes, oldSubArtName);
                        } else {
                            checkAssocAndUpdate(methods[i], newRes, null);
                        }
                    }
                }
                // If we're not dealing with a compilation unit, a single method/field was renamed or moved.
                // If it was moved we need to know the old resource to change resource properties (it might not
                // have rationale anymore) so we save that now.
                else {
                    oldResource = oldElt.getResource();
                }

                // Update them
                ourAssoc.setArtifact(newArt);
                ourAssoc.setResource(newRes);
                ourAssoc.setArtName(newArtName);

                System.out.println("oldArt became " + newArt);
                System.out.println("oldRes became " + newRes);
                System.out.println(oldArtName + " became " + newArtName);

                // Send the update to the DB
                ourAssoc.toDatabase(oldArtName);

                // Update the marker- this will sometimes give us "resource tree locked" exceptions.
                // However, in the cases where it does, we're making changes to a compilation unit
                // and the markers will stay where they are.
                try {
                    IMarker ratM = newResource.createMarker("SEURAT.ratmarker");
                    String markD = ourAssoc.getMsg();
                    ratM.setAttribute(IMarker.MESSAGE, markD);
                    ratM.setAttribute(IMarker.CHAR_START, cstart);
                    ratM.setAttribute(IMarker.CHAR_END, cstart + 1);
                    ratM.setAttribute(IMarker.SEVERITY, 0);
                    System.out.println(cstart);
                    Alternative ourAlt = (Alternative) RationaleDB.getRationaleElement(ourAssoc.getAlt(),
                            RationaleElementType.ALTERNATIVE);
                    ratM.setAttribute("alternative", ourAlt.getName());
                } catch (CoreException e) {
                    System.err.println(e.toString());
                }

                // If the element was moved, remove the persistent property from the old resource.
                // This is a hack, because if there is associated rationale remaining in the old resource
                // it still removes the decorator, but the next time restoreAssociations is called it will
                // be back.  I couldn't see a better way to do it short of rewriting the decorator and/or resource properties manager.
                if (oldResource != null) { // it will be null for a compilation unit because we didn't set it
                    SEURATResourcePropertiesManager.addPersistentProperty(oldResource, "Rat", "false");
                    SEURATDecoratorManager.addSuccessResources(oldResource);
                }
                // add property for the new resource in all cases
                SEURATResourcePropertiesManager.addPersistentProperty(newResource, "Rat", "true");
                SEURATDecoratorManager.addSuccessResources(newResource);
            }
        }
    }
}