Java 类org.eclipse.jdt.core.IType 实例源码

项目:gemoc-studio-modeldebugging    文件:PlainK3ExecutionEngine.java   
/**
 * search the bundle that contains the Main class. The search is done in the
 * workspace scope (ie. if it is defined in the current workspace it will
 * find it
 * 
 * @return the name of the bundle containing the Main class or null if not
 *         found
 */
private IType getITypeMainByWorkspaceScope(String className) {
    SearchPattern pattern = SearchPattern.createPattern(className, IJavaSearchConstants.CLASS,
            IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);
    IJavaSearchScope scope = SearchEngine.createWorkspaceScope();

    final List<IType> binaryType = new ArrayList<IType>();

    SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            binaryType.add((IType) match.getElement());
        }
    };
    SearchEngine engine = new SearchEngine();

    try {
        engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
                requestor, null);
    } catch (CoreException e1) {
        throw new RuntimeException("Error while searching the bundle: " + e1.getMessage());
        // return new Status(IStatus.ERROR, Activator.PLUGIN_ID, );
    }

    return binaryType.isEmpty() ? null : binaryType.get(0);
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param project
 * @param itype
 * @return
 * @throws JavaModelException
 */
private static IPath findPathInGeneratedAnnotation(IProject project, IType itype) throws JavaModelException {
    ICompilationUnit cu = itype.getCompilationUnit();
    List<IAnnotationBinding> annotations = resolveAnnotation(cu, Generated.class).getAnnotations();
    if ((annotations != null) && (annotations.size() > 0)) {
        IAnnotationBinding ab = annotations.get(0);
        IMemberValuePairBinding[] attributes = ab.getAllMemberValuePairs();
        for (int i = 0; i < attributes.length; i++) {
            IMemberValuePairBinding attribut = attributes[i];
            if (attribut.getName().equalsIgnoreCase("value")) {
                Object[] o = (Object[]) attribut.getValue();
                if (o != null && o.length > 0 && String.valueOf(o[0]).trim().length() > 0) {
                    try {
                        IPath p = ResourceManager.find(project, String.valueOf(o[0]).trim());
                        return p;
                    } catch (Exception e) {
                        ResourceManager.logException(e);
                        return null;
                    }
                }
            }
        }
    }
    return null;
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param project
 * @param itype
 * @return
 * @throws JavaModelException
 */
public static IPath findPathInModelAnnotation(IProject project, IType itype) throws JavaModelException {
    ICompilationUnit cu = itype.getCompilationUnit();
    List<IAnnotationBinding> annotations = resolveAnnotation(cu, Model.class).getAnnotations();
    if ((annotations != null) && (annotations.size() > 0)) {
        IAnnotationBinding ab = annotations.get(0);
        IMemberValuePairBinding[] attributes = ab.getAllMemberValuePairs();
        for (int i = 0; i < attributes.length; i++) {
            IMemberValuePairBinding attribut = attributes[i];
            if (attribut.getName().equalsIgnoreCase("value")) {
                Object[] o = (Object[]) attribut.getValue();
                if (o != null && o.length > 0 && String.valueOf(o[0]).trim().length() > 0) {
                    try {
                        IPath p = ResourceManager.find(project, String.valueOf(o[0]).trim());
                        return p;
                    } catch (Exception e) {
                        ResourceManager.logException(e);
                        return null;
                    }
                }
            }
        }
    }
    return null;
}
项目:gw4e.project    文件:JDTManager.java   
private static IType getClassesWithAnnotation(ICompilationUnit compilationUnit, Class annotationClass,
        String attributName, boolean valued) throws JavaModelException {
    List<IAnnotationBinding> annotations = resolveAnnotation(compilationUnit, annotationClass).getAnnotations();
    if ((annotations != null) && (annotations.size() > 0)) {
        IAnnotationBinding ab = annotations.get(0);
        IMemberValuePairBinding[] attributes = ab.getAllMemberValuePairs();
        for (int i = 0; i < attributes.length; i++) {
            IMemberValuePairBinding attribut = attributes[i];
            if (attribut.getName().equalsIgnoreCase(attributName)) {
                if (valued) {
                    if (String.valueOf(attribut.getValue()).trim().length() > 0) {
                        return compilationUnit.findPrimaryType();
                    }
                } else {
                    if (String.valueOf(attribut.getValue()).trim().length() == 0) {
                        return compilationUnit.findPrimaryType();
                    }
                }
            }
        }
    }
    return null;
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param projectName
 * @return
 * @throws JavaModelException
 */
private static List<IType> findClassesWithAnnotation(String projectName, Class annotationClass, String attributName,
        boolean valued) throws JavaModelException {
    List<IType> classList = new ArrayList<IType>();
    IProject project = ResourceManager.getProject(projectName);
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragment[] packages = javaProject.getPackageFragments();
    for (IPackageFragment packageFragment : packages) {
        for (final ICompilationUnit compilationUnit : packageFragment.getCompilationUnits()) {
            if (compilationUnit.exists()) {
                IType type = getClassesWithAnnotation(compilationUnit, annotationClass, attributName, valued);
                if (type != null)
                    classList.add(type);
            }
        }
    }
    return classList;
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param testInterface
 * @return
 * @throws JavaModelException
 */
public static boolean isGraphWalkerExecutionContextClass(ICompilationUnit unit) throws JavaModelException {
    IType[] types = unit.getAllTypes();

    if (types == null || types.length == 0) {
        ResourceManager.logInfo(unit.getJavaProject().getProject().getName(),
                "getAllTypes return null" + unit.getPath());
        return false;
    }
    IType execContextType = unit.getJavaProject().findType(ExecutionContext.class.getName());

    for (int i = 0; i < types.length; i++) {
        IType type = types[i];
        String typeNname = type.getFullyQualifiedName();
        String compilationUnitName = JDTManager.getJavaFullyQualifiedName(unit);
        if (typeNname.equals(compilationUnitName)) {
            try {
                ITypeHierarchy th = types[0].newTypeHierarchy(new NullProgressMonitor());
                return th.contains(execContextType);
            } catch (Exception e) {
                ResourceManager.logException(e);
            }
        }
    }
    return false;
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param projectName
 * @return
 */
public static List<IType> getOrphanGraphWalkerClasses(IType type, boolean hint) {
    try {
        IProject project = ResourceManager.getResource(type.getPath().toString()).getProject();
        String projectName = project.getName();

        List<IType> all = findClassesWithAnnotation(projectName, GraphWalker.class, "value", true);
        if (hint) {
            all = GraphWalkerFacade.getSharedContexts(project, type, all);
            all.remove(type);
        }

        Collections.sort(all, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                IType type1 = (IType) o1;
                IType type2 = (IType) o2;
                return type1.getFullyQualifiedName().compareTo(type2.getFullyQualifiedName());
            }
        });
        return all;
    } catch (Exception e) {
        ResourceManager.logException(e);
        return new ArrayList<IType>();
    }
}
项目:gw4e.project    文件:JDTHelper.java   
public static boolean containsMethod (String path, String[] requiredMethods) throws JavaModelException {
    IResource resource = ResourceManager.getResource(path);
    IFile file = (IFile) resource;
    ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
    IType[] types = cu.getAllTypes();
    List<String> list = new ArrayList<String>();
    for (int i = 0; i < types.length; i++) {
        IMethod[] methods = types[i].getMethods();
        for (int j = 0; j < methods.length; j++) {
            list.add(methods[j].getElementName());
        }
    } 
    for (int i = 0; i < requiredMethods.length; i++) {
        String method = requiredMethods[i];
        if (!list.contains(method)) return false;
    }     
    return true;
}
项目:Hydrograph    文件:ClassDetails.java   
public ClassDetails(IClassFile classFile, String jarFileName, String packageName, boolean isUserDefined) {
    LOGGER.debug("Extracting methods from "+classFile.getElementName());

    try {
        this.javaDoc=getJavaDoc(classFile); 
        intialize(classFile,jarFileName,packageName, isUserDefined);
        for (IJavaElement iJavaElement : classFile.getChildren()) {
            if (iJavaElement instanceof IType) {
                IType iType = (IType) iJavaElement;
                for (IMethod iMethod : iType.getMethods()) {
                    addMethodsToClass(iMethod);
                }
            }
        }
    } catch (JavaModelException e) {
        LOGGER.error("Error occurred while fetching methods from class"+cName);
    }
}
项目:Hydrograph    文件:ELTOpenFileEditorListener.java   
private void openInbuiltOperationClass(String operationName, PropertyDialogButtonBar propertyDialogButtonBar) {
    String operationClassName = null;
    Operations operations = XMLConfigUtil.INSTANCE.getComponent(FilterOperationClassUtility.INSTANCE.getComponentName())
            .getOperations();
    List<TypeInfo> typeInfos = operations.getStdOperation();
    for (int i = 0; i < typeInfos.size(); i++) {
        if (typeInfos.get(i).getName().equalsIgnoreCase(operationName)) {
            operationClassName = typeInfos.get(i).getClazz();
            break;
        }
    }
    propertyDialogButtonBar.enableApplyButton(true);
    javaProject = FilterOperationClassUtility.getIJavaProject();
    if (javaProject != null) {
        try {
            IType findType = javaProject.findType(operationClassName);
            JavaUI.openInEditor(findType);
        } catch (JavaModelException | PartInitException e) {
            Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID,Messages.CLASS_NOT_EXIST,null);
            StatusManager.getManager().handle(status, StatusManager.BLOCK);
            logger.error(e.getMessage(), e);
        }
    } else {
        WidgetUtility.errorMessage(Messages.SAVE_JOB_MESSAGE);
    }
}
项目:vertigo-chroma-kspplugin    文件:ServiceManager.java   
/**
 * Parse un fichier candidat de service métier.
 * 
 * @param document Document du service métier.
 * @param javaProject Projet Java du service.
 * @return Le service, <code>null</code> sinon.
 */
private ServiceFile createServiceFile(IFile file, IJavaProject javaProject) {
    /* Charge l'AST du fichier Java. */
    ICompilationUnit compilationUnit = JdtUtils.getCompilationUnit(file, javaProject);
    if (compilationUnit == null) {
        return null;
    }
    List<ServiceImplementation> serviceImplementations = new ArrayList<>();
    try {
        /* Parcourt les types du fichier Java. */
        for (IType type : compilationUnit.getAllTypes()) {
            handleType(type, file, serviceImplementations);
        }
    } catch (JavaModelException e) {
        ErrorUtils.handle(e);
    }

    /* Créé le fichier de service. */
    return new ServiceFile(serviceImplementations);
}
项目:vertigo-chroma-kspplugin    文件:ServiceManager.java   
private void handleType(IType type, IFile file, List<ServiceImplementation> serviceImplementations) throws JavaModelException {
    /* Parcourt les méthodes. */
    for (IMethod method : type.getMethods()) {
        /* Filtre pour ne garder que les méthodes publiques d'instance */
        if (method.isConstructor() || Flags.isStatic(method.getFlags()) || Flags.isPrivate(method.getFlags())) {
            continue;
        }

        /* Créé le ServiceImplementation. */
        String javaName = method.getElementName();
        ISourceRange nameRange = method.getNameRange();
        FileRegion fileRegion = new FileRegion(file, nameRange.getOffset(), nameRange.getLength());
        ServiceImplementation serviceImplementation = new ServiceImplementation(fileRegion, javaName);
        serviceImplementations.add(serviceImplementation);
    }
}
项目:vertigo-chroma-kspplugin    文件:WsRouteManager.java   
/**
 * Parse un fichier candidat de webservice.
 * 
 * @param file Fichier du webservice.
 * @param javaProject Projet Java du fichier.
 * @return Le webservice, <code>null</code> sinon.
 */
private WsFile createWsFile(IFile file, IJavaProject javaProject) {
    /* Charge l'AST du fichier Java. */
    ICompilationUnit compilationUnit = JdtUtils.getCompilationUnit(file, javaProject);
    if (compilationUnit == null) {
        return null;
    }
    List<WsRoute> wsRoutes = new ArrayList<>();
    try {
        /* Parcourt les types du fichier Java. */
        for (IType type : compilationUnit.getAllTypes()) {
            handleType(type, file, wsRoutes);
        }
    } catch (JavaModelException e) {
        ErrorUtils.handle(e);
    }

    /* Créé le fichier de webservice. */
    return new WsFile(file, wsRoutes);
}
项目:vertigo-chroma-kspplugin    文件:DaoManager.java   
/**
 * Parse un fichier candidat de DAO/PAO.
 * 
 * @param file Fichier.
 * @param javaProject Projet Java du fichier.
 * @return Le DAO, <code>null</code> sinon.
 */
private DaoFile createDaoFile(IFile file, IJavaProject javaProject) {
    /* Charge l'AST du fichier Java. */
    ICompilationUnit compilationUnit = JdtUtils.getCompilationUnit(file, javaProject);
    if (compilationUnit == null) {
        return null;
    }
    List<DaoImplementation> daoImplementations = new ArrayList<>();
    try {
        /* Parcourt les types du fichier Java. */
        for (IType type : compilationUnit.getAllTypes()) {
            handleType(type, file, daoImplementations);
        }
    } catch (JavaModelException e) {
        ErrorUtils.handle(e);
    }

    /* Créé le fichier de DAO/PAO. */
    String daoName = StringUtils.removeExtension(compilationUnit.getElementName());
    return new DaoFile(daoName, file, daoImplementations);
}
项目:vertigo-chroma-kspplugin    文件:DaoManager.java   
private void handleType(IType type, IFile file, List<DaoImplementation> daoImplementations) throws JavaModelException {
    /* Parcourt les méthodes. */
    for (IMethod method : type.getMethods()) {
        /* Filtre pour ne garder que les méthodes publiques d'instance */
        if (method.isConstructor() || Flags.isStatic(method.getFlags()) || Flags.isPrivate(method.getFlags())) {
            continue;
        }

        /* Créé le DaoImplementation. */
        String javaName = method.getElementName();
        ISourceRange nameRange = method.getNameRange();
        FileRegion fileRegion = new FileRegion(file, nameRange.getOffset(), nameRange.getLength());
        DaoImplementation daoImplementation = new DaoImplementation(fileRegion, javaName);
        daoImplementations.add(daoImplementation);
    }
}
项目:vertigo-chroma-kspplugin    文件:JdtUtils.java   
/**
 * Indique si le type donné est un DtObject Kasper 3.
 * 
 * @param type Type JDT.
 * @return <code>true</code> si le type est un DtObject.
 */
public static boolean isKasper3DtoType(IType type) {
    try {
        /* Vérifie que c'est une classe publique. */
        if (!type.isClass() || !Flags.isPublic(type.getFlags())) {
            return false;
        }
        /* Vérifie que la classe hérite de SuperDtObject */
        if (type.getSuperclassName() == null) {
            return false;
        }
        return "SuperDtObject".equals(type.getSuperclassName()) || "kasper.model.SuperDtObject".equals(type.getSuperclassName());

    } catch (JavaModelException e) {
        ErrorUtils.handle(e);
    }
    return false;
}
项目:vertigo-chroma-kspplugin    文件:JdtUtils.java   
/**
 * Indique si le type donné est un DtObject Kasper 4 ou 5.
 * 
 * @param type Type JDT.
 * @return <code>true</code> si le type est un DtObject.
 */
public static boolean isKasper345DtoType(IType type) {
    try {
        /* Vérifie que c'est une classe publique. */
        if (!type.isClass() || !Flags.isPublic(type.getFlags())) {
            return false;
        }
        /* Vérifie que la classe hérite d'un abstract de même nom préfixé ou suffixé par Abstract */
        String superclassName = type.getSuperclassName();
        if (superclassName == null) {
            return false;
        }
        String prefixedName = "Abstract" + type.getElementName();
        String suffixedName = type.getElementName() + "Abstract";

        return superclassName.equals(prefixedName) || superclassName.equals(suffixedName);

    } catch (JavaModelException e) {
        ErrorUtils.handle(e);
    }
    return false;
}
项目:vertigo-chroma-kspplugin    文件:JdtUtils.java   
/**
 * Indique si le type donné est une sous-classe direct d'un type parmi une liste.
 * 
 * @param type Type JDT.
 * @param parentClasses Liste des classes parentes candidates.
 * @return <code>true</code> si le type est une sous-classe.
 */
public static boolean isSubclass(IType type, List<String> parentClasses) {
    if (parentClasses == null || parentClasses.isEmpty()) {
        return false;
    }
    try {
        /* Vérifie que c'est une classe publique. */
        if (!type.isClass() || !Flags.isPublic(type.getFlags())) {
            return false;
        }
        /* Vérifie que la classe hérite d'une classe (autre que Object) */
        String superclassName = type.getSuperclassName();
        if (superclassName == null) {
            return false;
        }

        /* Vérifie que la classe parente est parmi les candidates. */
        return parentClasses.contains(superclassName);

    } catch (JavaModelException e) {
        ErrorUtils.handle(e);
    }
    return false;
}
项目:vertigo-chroma-kspplugin    文件:CanonicalJavaNameHyperLinkDetector.java   
private IType findJavaType(String currentWord) {

        IProject currentEditorProject = UiUtils.getCurrentEditorProject();

        /* Cas d'un nom qualifié complet. */
        IType javaTypeFromFullyQualifiedName = JdtUtils.getJavaType(currentWord, currentEditorProject);
        if (javaTypeFromFullyQualifiedName != null) {
            return javaTypeFromFullyQualifiedName;
        }

        /* Cas d'un nom simple. */
        JavaClassFile javaClassFromSimpleName = JavaClassManager.getInstance().findJavaClassFile(currentWord);
        if (javaClassFromSimpleName != null) {
            IType javaTypeFromSimpleName = JdtUtils.getJavaType(javaClassFromSimpleName.getFullyQualifiedName(), currentEditorProject);
            if (javaTypeFromSimpleName != null) {
                return javaTypeFromSimpleName;
            }
        }

        return null;
    }
项目:java-builders-generator    文件:GenerateBuildersHandler.java   
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {

    final IEditorPart editorPart = HandlerUtil.getActiveEditor(event);
    final ICompilationUnit icu = JavaUI.getWorkingCopyManager().getWorkingCopy(editorPart.getEditorInput());

    try {
        final IType type = icu.getTypes()[0];
        final List<Field> fields = new ArrayList<>();
        for (final IField field : type.getFields()) {
            final String fieldName = field.getElementName();
            final String fieldType = Signature.getSignatureSimpleName(field.getTypeSignature());
            fields.add(new Field(fieldName, fieldType));
        }

        new WizardDialog(HandlerUtil.getActiveShell(event), new BuilderGeneratorWizard(icu, fields)).open();

    }
    catch (final JavaModelException e) {
        e.printStackTrace();
    }

    return null;
}
项目:pandionj    文件:StaticInvocationWidget.java   
private void addRefCombovalues(Combo combo, String paramType) {
    if(!PrimitiveType.isPrimitiveSig(paramType)) {
        combo.add("null");
        IType owner = (IType) method.getParent();
        try {
            IField[] fields = owner.getFields();
            for(IField f : fields)
                if(Flags.isStatic(f.getFlags()) && f.getTypeSignature().equals(paramType))
                    combo.add(f.getElementName());


        } catch (JavaModelException e1) {
            e1.printStackTrace();
        }
    }
}
项目:pandionj    文件:ITypeWidgetExtension.java   
@Override
        public IFigure createFigure(IObjectModel e) {
            Label label = new Label();
            label.setForegroundColor(PandionJConstants.Colors.OBJECT_HEADER_FONT);
            FontManager.setFont(label, PandionJConstants.OBJECT_HEADER_FONT_SIZE);
            IType type = e.getType();
            if(type != null) {
                IMethod method = type.getMethod("toString", new String[0]);
                if(!method.exists()) {
                    label.setText(":" + type.getElementName());
                    return label;
                }
            }
            invokeToString(e, label);
            label.setToolTip(new Label("returned by toString()"));
            e.getRuntimeModel().registerDisplayObserver((event) -> {
                if(event.type == IRuntimeModel.Event.Type.STEP ||event.type == IRuntimeModel.Event.Type.EVALUATION) {
                    invokeToString(e, label);
//                  label.setText(e.getStringValue());
                }
            });
            return label;
        }
项目:pandionj    文件:InvokeWidget.java   
public void setMethod(IMethod method, InvocationAction a) {
    String key = null;
    try {
        IType type = (IType) method.getParent();
        key = type.getFullyQualifiedName() + "|" + method.getElementName() + method.getSignature();
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    if(key != null) {
        StaticInvocationWidget2 inv = invWidgetsMap.get(key);
        if(inv == null) {
            inv = new StaticInvocationWidget2(this, null, method, a);
            invWidgetsMap.put(key, inv);
        }
        inv.refreshItems();
        layout.topControl = inv;
        layout();
    }
}
项目:pandionj    文件:InvocationWidget.java   
public void setMethod(IMethod method, InvocationAction a) {
    String key = null;
    try {
        IType type = (IType) method.getParent();
        key = type.getFullyQualifiedName() + "|" + method.getElementName() + method.getSignature();
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    if(key != null) {
        StaticInvocationWidget2 inv = invWidgetsMap.get(key);
        if(inv == null) {
            inv = new StaticInvocationWidget2(this, null, method, a);
            invWidgetsMap.put(key, inv);
        }
        inv.refreshItems();
        layout.topControl = inv;
        layout();
    }
}
项目:pandionj    文件:InvocationArea.java   
public void setMethod(IFile file, IMethod method, InvocationAction a) {
    String key = null;
    try {
        IType type = (IType) method.getParent();
        key = type.getFullyQualifiedName() + "|" + method.getElementName() + method.getSignature();
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    if(key != null) {
        StaticInvocationWidget inv = invWidgetsMap.get(key);
        if(inv == null) {
            inv = new StaticInvocationWidget(this, file, method, a);
            invWidgetsMap.put(key, inv);
        }
        inv.refreshItems(file);
        layout.topControl = inv;
        layout();
    }
}
项目:gemoc-studio-modeldebugging    文件:PlainK3ExecutionEngine.java   
/**
 * Return a bundle containing 'aspectClassName'.
 * 
 * Return null if not found.
 */
private Bundle findBundle(final IExecutionContext executionContext, String aspectClassName) {

    // Look using JavaWorkspaceScope as this is safer and will look in
    // dependencies
    IType mainIType = getITypeMainByWorkspaceScope(aspectClassName);

    Bundle bundle = null;
    String bundleName = null;
    if (mainIType != null) {
        IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) mainIType.getPackageFragment()
                .getParent();

        bundleName = packageFragmentRoot.getPath().removeLastSegments(1).lastSegment().toString();
        if (bundleName != null) {

            // We try to look into an already loaded bundle
            bundle = Platform.getBundle(bundleName);
        }
    } else {
        // the main isn't visible directly from the workspace, try another
        // method
        bundle = _executionContext.getMelangeBundle();
    }

    return bundle;
}
项目:codelens-eclipse    文件:JavaCodeLensProvider.java   
private void collectCodeLenses(ITypeRoot unit, IJavaElement[] elements, List<ICodeLens> lenses,
        IProgressMonitor monitor) throws JavaModelException {
    for (IJavaElement element : elements) {
        if (monitor.isCanceled()) {
            return;
        }
        if (element.getElementType() == IJavaElement.TYPE) {
            collectCodeLenses(unit, ((IType) element).getChildren(), lenses, monitor);
        } else if (element.getElementType() != IJavaElement.METHOD || JDTUtils.isHiddenGeneratedElement(element)) {
            continue;
        }

        // if (preferenceManager.getPreferences().isReferencesCodeLensEnabled()) {
        ICodeLens lens = getCodeLens(REFERENCES_TYPE, element, unit);
        lenses.add(lens);
        // }
        // if (preferenceManager.getPreferences().isImplementationsCodeLensEnabled() &&
        // element instanceof IType) {
        if (element instanceof IType) {
            IType type = (IType) element;
            if (type.isInterface() || Flags.isAbstract(type.getFlags())) {
                lens = getCodeLens(IMPLEMENTATION_TYPE, element, unit);
                lenses.add(lens);
            }
        }
    }
}
项目:codelens-eclipse    文件:JavaCodeLensProvider.java   
private List<Location> findImplementations(IType type, IProgressMonitor monitor) throws JavaModelException {
    IType[] results = type.newTypeHierarchy(monitor).getAllSubtypes(type);
    final List<Location> result = new ArrayList<>();
    for (IType t : results) {
        ICompilationUnit compilationUnit = (ICompilationUnit) t.getAncestor(IJavaElement.COMPILATION_UNIT);
        if (compilationUnit == null) {
            continue;
        }
        Location location = null; // JDTUtils.toLocation(t);
        result.add(location);
    }
    return result;
}
项目:gw4e.project    文件:GW4ELaunchConfigurationTab.java   
private void createTestContainerSelectionGroup (Composite parent) {
    Label fTestLabel = new Label(parent, SWT.NONE);
    GridData gd = new GridData( );
    gd.horizontalAlignment = SWT.RIGHT;
    gd.horizontalIndent = 25;
    gd.verticalAlignment=SWT.TOP;
    fTestLabel.setLayoutData(gd);
    fTestLabel.setText(MessageUtil.getString("mainTestExecutionContext"));

    fMainTestExecutionComboViewer = new ComboViewer(parent,SWT.DROP_DOWN);
    Combo combo = fMainTestExecutionComboViewer.getCombo();
    combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    fMainTestExecutionComboViewer.setContentProvider(new   IStructuredContentProvider(){
        @Override
        public Object[] getElements(Object inputElement) {
            String projectName= (String) inputElement;
            loadMainExecutionContextTests(projectName);
            return mainExecutionContexts;
        }
    });
    ILabelProvider labelProvider = new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_QUALIFIED);
    fMainTestExecutionComboViewer.setLabelProvider(labelProvider);
    fMainTestExecutionComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
                fAdditionalTestViewer.setInput(null);
                IStructuredSelection selection = (IStructuredSelection) event.getSelection();
                if (selection.size() > 0){
                      resetDoHint();
                      IType type =  (IType) selection.getFirstElement();
                      fAdditionalTestViewer.setInput(type);
                      validatePage();
                }
        }
    });
    combo.setData(GW4E_LAUNCH_CONFIGURATION_CONTROL_ID,GW4E_LAUNCH_TEST_CONFIGURATION_MAIN_TEST);
}
项目:gw4e.project    文件:GW4ELaunchConfigurationTab.java   
private void hint ( ) {
    this.doHint=!this.doHint;
    IStructuredSelection selection = (IStructuredSelection)fMainTestExecutionComboViewer.getSelection();
    if (selection==null) return;
    IType type = (IType)selection.getFirstElement();
    if (type==null) return;
    fAdditionalTestViewer.setInput(type);
}
项目:gw4e.project    文件:GW4ELaunchConfigurationTab.java   
private void loadMainExecutionContextTests(String projectName) {
    List<IType> all=null;;
    try {
        if (projectName==null || projectName.trim().length() == 0) return;
        all = JDTManager.getStartableGraphWalkerClasses(projectName);
    } catch (Exception e) {
        ResourceManager.logException(e);
        mainExecutionContexts = new IType  [0]; 
    }
    mainExecutionContexts = new IType[all.size()];
    all.toArray(mainExecutionContexts);

}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param project
 * @return
 * @throws CoreException
 * @throws FileNotFoundException
 */
public static ICompilationUnit[] getExistingGeneratedTestInterfaces(IProject project, boolean main)
        throws CoreException, FileNotFoundException {
    IPath folder = project.getFullPath()
            .append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), main));
    List<ICompilationUnit> units = new ArrayList<ICompilationUnit>();
    IResource interfaceFolder = ResourceManager.toResource(folder);
    if (interfaceFolder != null) {
        interfaceFolder.accept(new IResourceVisitor() {
            @Override
            public boolean visit(IResource resource) throws CoreException {
                IJavaElement element = JavaCore.create(resource);
                if (element != null && element instanceof ICompilationUnit) {
                    try {
                        ICompilationUnit cu = (ICompilationUnit) element;
                        IType interf = cu.findPrimaryType();
                        if (interf != null && interf.isInterface()) {
                            units.add(cu);
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                return true;
            }
        });
    }
    ICompilationUnit[] ret = new ICompilationUnit[units.size()];
    units.toArray(ret);
    return ret;
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param project
 * @param itype
 * @return
 * @throws JavaModelException
 */
private static IPath findPathInStaticField(IProject project, IType itype) throws JavaModelException {
    List<IPath> wrapper = new ArrayList<IPath>();
    ICompilationUnit cu = itype.getCompilationUnit();
    CompilationUnit ast = parse(cu);
    ast.accept(new ASTVisitor() {
        public boolean visit(VariableDeclarationFragment node) {
            SimpleName simpleName = node.getName();
            IBinding bding = simpleName.resolveBinding();
            if (bding instanceof IVariableBinding) {
                IVariableBinding binding = (IVariableBinding) bding;
                String type = binding.getType().getBinaryName(); //
                String name = simpleName.getFullyQualifiedName();
                if ("MODEL_PATH".equals(name) && "java.nio.file.Path".equals(type)) {
                    Expression expression = node.getInitializer();
                    if (expression instanceof MethodInvocation) {
                        MethodInvocation mi = (MethodInvocation) expression;
                        if ("get".equals(mi.resolveMethodBinding().getName())
                                && "java.nio.file.Path".equals(mi.resolveTypeBinding().getBinaryName())) {
                            StringLiteral sl = (StringLiteral) mi.arguments().get(0);
                            String argument = sl.getLiteralValue();
                            try {
                                IPath p = ResourceManager.find(project, argument);
                                wrapper.add(p);
                            } catch (CoreException e) {
                                ResourceManager.logException(e);
                            }
                        }
                    }
                }
            }
            return true;
        }
    });
    if (wrapper.size() > 0)
        return wrapper.get(0);
    return null;
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param projectName
 * @return
 * @throws JavaModelException
 */
public static List<IType> getStartableGraphWalkerClasses(String projectName) {
    try {

        return findClassesWithAnnotation(projectName, GraphWalker.class, "start", true);
    } catch (Exception e) {
        ResourceManager.logException(e);
        return new ArrayList<IType>();
    }
}
项目:gw4e.project    文件:TestConvertor.java   
private List<ICompilationUnit> findTests(IProgressMonitor monitor) throws JavaModelException {
    List<ICompilationUnit> units =  new ArrayList<ICompilationUnit>();
    ITypeHierarchy th = testInterface.findPrimaryType().newTypeHierarchy(testInterface.getJavaProject(),monitor);
    IType[] types = th.getImplementingClasses(testInterface.findPrimaryType());
    for (int i = 0; i < types.length; i++) {
        units.add(types[i].getCompilationUnit());
    }
    return units;
}
项目:gw4e.project    文件:JDTManagerTest.java   
@Test
public void testGetFullyQualifiedName() throws Exception {
    IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true);
    IType type = project.findType("SimpleImpl");
    String s = JDTManager.getFullyQualifiedName(type);
    assertEquals("SimpleImpl.java", s);
}
项目:gw4e.project    文件:JDTManagerTest.java   
@Test
public void testGetGraphModelPath() throws Exception {
    IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true);
    IType type = project.findType("SimpleImpl");
    IPath path = JDTManager.getGraphModelPath(project.getProject(),type);
    assertEquals("/" + PROJECT_NAME +"/src/test/resources/Simple.json", path.toString());
}
项目:gw4e.project    文件:JDTManagerTest.java   
@Test
public void testFindSetPathGeneratorInvocation() throws Exception {
    IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true);
    IFile impl = (IFile) ResourceManager
            .getResource(project.getProject().getFullPath().append("src/test/java/SimpleImpl.java").toString());
    ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(impl);
    IType type = compilationUnit.getAllTypes()[0];
    Map<String, List<String>> map = JDTManager.findSetPathGeneratorInvocation(project.getProject(), type);
    List<String> list = map.get("SimpleImpl");
    assertTrue (list.size()==1);
    String value = list.get(0);
    assertEquals("new RandomPath(new EdgeCoverage(100))", value);
}
项目:gw4e.project    文件:JDTManagerTest.java   
@Test
public void testFindGeneratorFactoryParseInvocation() throws Exception {
    IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true);
    IFile impl = (IFile) ResourceManager
            .getResource(project.getProject().getFullPath().append("src/test/java/SimpleImpl.java").toString());

    IOHelper.appendParseGeneratorCall (impl);
    IType type = project.findType("SimpleImpl");
    Set<String> invocations = JDTManager.findGeneratorFactoryParseInvocation(project.getProject(), type);
    assertEquals (1,invocations.size());
    String value = invocations.iterator().next();
    assertEquals("random(edge_coverage(100))", value);
}
项目:gw4e.project    文件:JDTManagerTest.java   
@Test
public void testGetStartableGraphWalkerClasses() throws Exception {
    IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true);
    List<IType> types = JDTManager.getStartableGraphWalkerClasses(project.getProject().getName());
    assertTrue (types.size()==1);
    IType type = project.findType("SimpleImpl");
    assertEquals(type,types.get(0));
}