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

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

Introduction

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

Prototype

int COMPILATION_UNIT

To view the source code for org.eclipse.jdt.core IJavaElement COMPILATION_UNIT.

Click Source Link

Document

Constant representing a Java compilation unit.

Usage

From source file:edu.buffalo.cse.green.editor.DiagramEditor.java

License:Open Source License

/**
 * Refreshes the relationships in the editor
 * /*w ww  .ja  v  a 2 s .c o  m*/
 * @param force - If true, will run the relationship recognizers. If false,
 * will run the relationship recognizers only if they are not disabled in
 * the <code>PlugIn</code> instance. 
 */
private void refreshRelationships(boolean force) {
    List<String> visitedElements = new ArrayList<String>();
    List<String> outdated = new ArrayList<String>();

    if (!force && !PlugIn.isRecognizersEnabled()) {
        return;
    }

    // get a list of all classes and compilation units in the editor
    List<IJavaElement> elements = new ArrayList<IJavaElement>();
    elements.addAll(getRootModel().getElementsOfKind(IJavaElement.COMPILATION_UNIT));
    elements.addAll(getRootModel().getElementsOfKind(IJavaElement.CLASS_FILE));

    // find relationships attached to those elements
    for (IJavaElement element : elements) {
        findRelationships(element);
        visitedElements.add(element.getHandleIdentifier());
    }

    // remove outdated CompilationUnit objects from the map 
    for (String cu : _cuMap.keySet()) {
        if (!(visitedElements.contains(cu))) {
            outdated.add(cu);
        }
    }

    for (String obsolete : outdated) {
        _cuMap.remove(obsolete);
    }

    Set<RelationshipModel> toRemove = new HashSet<RelationshipModel>();
    _relationshipChanges = getRootModel().getRelationshipCache().processChanges();

    // update the relationships as appropriate
    for (RelationshipModel rModel : _relationshipChanges) {
        if (rModel.getRelationships().size() == 0) { // removal
            rModel.removeFromParent();
            toRemove.add(rModel);
        } else {
            rModel.setParent(getRootModel());

            if (rModel.getSourceModel() != null && rModel.getTargetModel() != null) {
                if (!getRootModel().getRelationships().contains(rModel)) {
                    getRootModel().addChild(rModel);
                    toRemove.add(rModel);
                }
            }
        }
    }

    // update the cardinality labels of all updated relationships 
    for (RelationshipModel model : toRemove) {
        model.updateCardinality();
    }

    _relationshipChanges.removeAll(toRemove);
}

From source file:edu.buffalo.cse.green.editor.model.commands.DeleteTypeCommand.java

License:Open Source License

/**
 * @see edu.buffalo.cse.green.editor.model.commands.DeleteCommand#doDelete()
 *///from  www.  ja  v  a 2  s  . com
public void doDelete() {
    RootModel root = _typeModel.getRootModel();

    //Remove relationships first
    List<RelationshipModel> rels = root.getRelationships();

    //No iterators here due to CME's (ConcurrentModificationException)
    //Removal of relationships causes modifications to the rels list.
    for (int i = 0; i < rels.size(); i++) {
        IType t = _typeModel.getType();
        RelationshipModel r = rels.get(i);
        if (r.getSourceType() == t || r.getTargetType() == t) {
            DeleteCommand drc = r.getDeleteCommand(DiagramEditor.findProjectEditor(root.getProject()));
            drc.suppressMessage(true);
            drc.execute();
        }
    }

    _typeModel.removeChildren(); // remove fields/methods
    _typeModel.removeFromParent();
    try {
        IType type = _typeModel.getType();
        ICompilationUnit cu = (ICompilationUnit) type.getAncestor(IJavaElement.COMPILATION_UNIT);

        if (type.equals(cu.findPrimaryType())) {
            cu.delete(true, PlugIn.getEmptyProgressMonitor());
        } else {
            type.delete(true, PlugIn.getEmptyProgressMonitor());
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    root.updateRelationships();
}

From source file:edu.buffalo.cse.green.relationships.RelationshipGenerator.java

License:Open Source License

/**
 * @see edu.buffalo.cse.green.relationships.RelationshipVisitor#run(org.eclipse.jdt.core.dom.CompilationUnit, edu.buffalo.cse.green.relationships.RelationshipCache)
 *//*  w  ww .  ja  v a  2  s. c  o  m*/
protected void run(CompilationUnit cu, RelationshipCache cache) {
    try {
        if (_sourceType.isBinary()) {
            GreenException.illegalOperation(GreenException.GRERR_REL_SOURCE_BINARY);
        }

        ICompilationUnit iCU = (ICompilationUnit) getSourceType().getAncestor(IJavaElement.COMPILATION_UNIT);

        cu.recordModifications();
        cu.accept(this);

        IDocument sourceDoc = new IModifiableBuffer(iCU.getBuffer());
        TextEdit textEdit = cu.rewrite(sourceDoc, null);
        textEdit.apply(sourceDoc);

        if (!iCU.isConsistent()) {
            iCU.save(PlugIn.getEmptyProgressMonitor(), true);
        }

        organizeImports(_sourceType);
    } catch (BadLocationException e) {
        e.printStackTrace();
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
}

From source file:edu.buffalo.cse.green.relationships.RelationshipRemover.java

License:Open Source License

/**
 * @see edu.buffalo.cse.green.relationships.RelationshipVisitor#run(org.eclipse.jdt.core.dom.CompilationUnit, edu.buffalo.cse.green.relationships.RelationshipCache)
 *//*from  ww w  .j  av  a2s. co  m*/
public final void run(CompilationUnit cu, RelationshipCache cache) {
    if (_rModel == null) {
        throw new IllegalStateException("The relationship to remove hasn't been set");
    }

    try {
        ICompilationUnit iCU = (ICompilationUnit) getSourceType().getAncestor(IJavaElement.COMPILATION_UNIT);

        cu.recordModifications();

        for (Relationship relationship : _rModel.getRelationships()) {
            _relationship = relationship;
            init();
            cu.accept(this);
            finish();
        }

        IDocument sourceDoc = new IModifiableBuffer(iCU.getBuffer());
        TextEdit textEdit = cu.rewrite(sourceDoc, null);
        textEdit.apply(sourceDoc);

        //         // put this outside of if block
        //         iCU.save(PlugIn.getEmptyProgressMonitor(), false);
        //         
        //         if (!iCU.isConsistent()) {
        //            iCU.discardWorkingCopy();
        //            iCU.save(PlugIn.getEmptyProgressMonitor(), false);
        //         }
        //         
        iCU.save(PlugIn.getEmptyProgressMonitor(), true);
        //find active workbench and save it
        IWorkbenchPage page = DiagramEditor.getActiveEditor().getSite().getPage();

        //Iterates through the editor references and finds the source editor and saves it
        String sourceCUName = getSourceType().getCompilationUnit().getResource().getName();
        for (int i = 0; i < page.getEditorReferences().length; i++) {
            if (sourceCUName.equals(page.getEditorReferences()[i].getEditor(true).getEditorInput().getName())) {
                page.saveEditor(page.getEditorReferences()[i].getEditor(false), false);
            }
        }
        organizeImports(getSourceType());
        DiagramEditor.getActiveEditor().refresh();
        _rModel.getSourceModel().forceRefresh();
    } catch (BadLocationException e) {
        e.printStackTrace();
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
}

From source file:edu.buffalo.cse.green.relationships.RelationshipVisitor.java

License:Open Source License

/**
 * @param element - The member element.//from  w  w w  .j a  va2s.c  om
 * @return A <code>CompilationUnit</code> representing the structure of the
 * source code of the element.
 */
public static CompilationUnit getCompilationUnit(IMember element) {
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setResolveBindings(true);

    if (element.isBinary()) {
        parser.setSource((IClassFile) element.getAncestor(IJavaElement.CLASS_FILE));
    } else {
        parser.setSource((ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT));
    }

    return (CompilationUnit) parser.createAST(null);
}

From source file:edu.buffalo.cse.green.relationships.RelationshipVisitor.java

License:Open Source License

/**
 * @param element - The element.//from www.  ja  v a  2  s .  co  m
 * @return The <code>CompilationUnit</code> representing the given element.
 */
public CompilationUnit getCompilationUnit(IType element) {
    if (element.isBinary()) {
        return getCompilationUnit((IClassFile) element.getAncestor(IJavaElement.CLASS_FILE));
    } else {
        return getCompilationUnit((ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT));
    }
}

From source file:edu.clarkson.serl.critic.loader.SootClassLoader.java

License:Open Source License

/**
 * The method traverses all of the project types in depth-first order 
 * including inner and anonymous types and loads them in Soot. 
 * /*  w  ww . j  av a 2 s .com*/
 * 
 * @param monitor The progress monitor.
 * @throws Exception Propagated from JDT APIs.
 */
public void process(IProgressMonitor subMonitor) throws Exception {
    IJavaProject project = CriticPlugin.getIJavaProject();
    IPackageFragmentRoot[] packageFragmentRoots = project.getPackageFragmentRoots();
    subMonitor.beginTask("Loading " + project.getElementName() + " ...", 2);

    SubProgressMonitor monitor = new SubProgressMonitor(subMonitor, 1);
    monitor.beginTask("Loading packages ... ", packageFragmentRoots.length + 1);

    for (IPackageFragmentRoot pkgFragRoot : packageFragmentRoots) {
        if (pkgFragRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
            IJavaElement[] pkgFrags = (IJavaElement[]) pkgFragRoot.getChildren();
            for (IJavaElement pkgFrag : pkgFrags) {
                if (monitor.isCanceled())
                    return;

                monitor.subTask("Loading classes in " + pkgFrag.getElementName());

                if (pkgFrag.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
                    IPackageFragment pkgFragment = (IPackageFragment) pkgFrag;
                    IJavaElement[] children = pkgFragment.getChildren();
                    for (IJavaElement anElement : children) {
                        if (monitor.isCanceled())
                            return;

                        // Make sure its a java file
                        if (anElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                            this.dfsDomTree(anElement, monitor);
                        }
                    }
                }
            }
        }
        monitor.worked(1);
    }

    // Load the necessary classes after all of the classes have been loaded.
    Scene.v().loadNecessaryClasses();
    monitor.done();

    // Create an instance of Interpreter before we process anything further
    Interpreter.instance();

    monitor = new SubProgressMonitor(subMonitor, 1);
    monitor.beginTask("Configuring entry points ... ", this.getAllSootClasses().size());

    for (SootClass c : this.getAllSootClasses()) {
        ExtensionManager manager = ExtensionManager.instance();
        // Configure entry methods for extension plugin
        for (SootMethod method : c.getMethods()) {
            if (monitor.isCanceled())
                return;

            manager.checkEntryMethod(method, monitor);
            monitor.worked(1);
        }
    }
    monitor.done();
}

From source file:edu.clarkson.serl.critic.loader.SootClassLoader.java

License:Open Source License

protected void dfsDomTree(IJavaElement element, IProgressMonitor monitor) throws Exception {
    if (monitor.isCanceled()) {
        return;/* w w  w . j  a v  a  2s. com*/
    }

    if (element.isReadOnly())
        return;

    int elementType = element.getElementType();
    if (elementType == IJavaElement.COMPILATION_UNIT) {
        ICompilationUnit cu = (ICompilationUnit) element;
        IType[] allTypes = cu.getTypes();
        for (IType aType : allTypes) {
            dfsDomTree(aType, monitor);
        }
    } else if (elementType == IJavaElement.TYPE) {
        IType aType = (IType) element;

        if (aType.isClass()) {
            // Load a type in Soot
            load(aType.getFullyQualifiedName());
        }

        // Go inside the methods to look for Anonymous Inner Class
        for (IMethod m : aType.getMethods()) {
            IJavaElement[] elems = m.getChildren();
            for (IJavaElement elem : elems) {
                if (elem.getElementType() == IJavaElement.TYPE) {
                    dfsDomTree(elem, monitor);
                }
            }
        }

        // For inner classes
        IType[] allTypes = aType.getTypes();
        for (IType childType : allTypes) {
            dfsDomTree(childType, monitor);
        }
    }

}

From source file:edu.cmu.cs.crystal.internal.WorkspaceUtilities.java

License:Open Source License

/**
 * A recursive traversal of the IJavaModel starting from the given
 * element to collect all ICompilationUnits.
 * Each compilation unit corresponds to each java file.
 *  //  w  w w.j a v a  2 s. c  om
 * @param javaElement a node in the IJavaModel that will be traversed
 * @return a list of compilation units or <code>null</code> if no comp units are found
 */
public static List<ICompilationUnit> collectCompilationUnits(IJavaElement javaElement) {
    List<ICompilationUnit> list = null, temp = null;
    // We are traversing the JavaModel for COMPILATION_UNITs
    if (javaElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
        list = new ArrayList<ICompilationUnit>();
        list.add((ICompilationUnit) javaElement);
        return list;
    }

    // Non COMPILATION_UNITs will have to be further traversed
    if (javaElement instanceof IParent) {
        IParent parent = (IParent) javaElement;

        // Do not traverse PACKAGE_FRAGMENT_ROOTs that are ReadOnly
        // this ignores libraries and .class files
        if (javaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT && javaElement.isReadOnly()) {
            return null;
        }

        // Traverse
        try {
            if (parent.hasChildren()) {
                IJavaElement[] children = parent.getChildren();
                for (int i = 0; i < children.length; i++) {
                    temp = collectCompilationUnits(children[i]);
                    if (temp != null)
                        if (list == null)
                            list = temp;
                        else
                            list.addAll(temp);
                }
            }
        } catch (JavaModelException jme) {
            log.log(Level.SEVERE, "Problem traversing Java model element: " + parent, jme);
        }
    } else {
        log.warning("Encountered a model element that's not a comp unit or parent: " + javaElement);
    }

    return list;
}

From source file:edu.uci.lighthouse.core.listeners.JavaFileChangedReporter.java

License:Open Source License

/**
 * Visits all nodes of the java element delta. It fires the events open and
 * close.// w ww.  j a  va 2 s .co m
 */
private void traverseDeltaTree(IJavaElementDelta delta) {
    if (delta.getElement().getElementType() == IJavaElement.COMPILATION_UNIT) {
        ICompilationUnit icu = (ICompilationUnit) delta.getElement();
        IFile iFile = (IFile) icu.getResource();
        if (iFile.exists()) {
            try {
                boolean hasErrors = IMarker.SEVERITY_ERROR == icu.getResource()
                        .findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);

                if ((delta.getFlags() & IJavaElementDelta.F_PRIMARY_WORKING_COPY) != 0) {
                    if (icu.isWorkingCopy()) {
                        fireOpen(iFile, hasErrors);
                    } else {
                        fireClose(iFile, hasErrors);
                    }
                }
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
    } else {
        for (IJavaElementDelta child : delta.getAffectedChildren()) {
            traverseDeltaTree(child);
        }
    }
}