List of usage examples for org.eclipse.jdt.core IType getResource
IResource getResource();
From source file:ca.ecliptical.pde.internal.ds.DSAnnotationCompilationParticipant.java
License:Open Source License
@Override public void buildFinished(IJavaProject project) { ProjectContext projectContext = processingContext.remove(project); if (projectContext != null) { ProjectState state = projectContext.getState(); // check if unprocessed CUs still exist; if not, their mapped files are now abandoned Map<String, Collection<String>> cuMap = state.getMappings(); HashSet<String> abandoned = new HashSet<String>(projectContext.getAbandoned()); for (String cuKey : projectContext.getUnprocessed()) { boolean exists = false; try { IType cuType = project.findType(cuKey); IResource file;/*w w w . j a v a 2s .c o m*/ if (cuType != null && (file = cuType.getResource()) != null && file.exists()) exists = true; } catch (JavaModelException e) { Activator.getDefault().getLog().log(e.getStatus()); } if (!exists) { if (debug.isDebugging()) debug.trace(String.format("Mapped CU %s no longer exists.", cuKey)); //$NON-NLS-1$ Collection<String> dsKeys = cuMap.remove(cuKey); if (dsKeys != null) abandoned.addAll(dsKeys); } } // remove CUs with no mapped DS models HashSet<String> retained = new HashSet<String>(); for (Iterator<Map.Entry<String, Collection<String>>> i = cuMap.entrySet().iterator(); i.hasNext();) { Map.Entry<String, Collection<String>> entry = i.next(); Collection<String> dsKeys = entry.getValue(); if (dsKeys.isEmpty()) i.remove(); else retained.addAll(dsKeys); } // retain abandoned files that are still mapped elsewhere abandoned.removeAll(retained); if (projectContext.isChanged()) { try { saveState(project.getProject(), state); } catch (IOException e) { Activator.getDefault().getLog() .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error saving file mappings.", e)); //$NON-NLS-1$ } } // delete all abandoned files ArrayList<IStatus> deleteStatuses = new ArrayList<IStatus>(2); for (String dsKey : abandoned) { IPath path = Path.fromPortableString(dsKey); if (debug.isDebugging()) debug.trace(String.format("Deleting %s", path)); //$NON-NLS-1$ IFile file = PDEProject.getBundleRelativeFile(project.getProject(), path); if (file.exists()) { try { file.delete(true, null); } catch (CoreException e) { deleteStatuses.add(e.getStatus()); } } } if (!deleteStatuses.isEmpty()) Activator.getDefault().getLog() .log(new MultiStatus(Activator.PLUGIN_ID, 0, deleteStatuses.toArray(new IStatus[deleteStatuses.size()]), "Error deleting generated files.", null)); //$NON-NLS-1$ writeManifest(project.getProject(), retained, abandoned); writeBuildProperties(project.getProject(), retained, abandoned); } if (debug.isDebugging()) debug.trace(String.format("Build finished for project: %s", project.getElementName())); //$NON-NLS-1$ }
From source file:com.aliyun.odps.eclipse.launch.shortcut.ODPSApplicationShortcut.java
License:Apache License
@Override protected ILaunchConfiguration findLaunchConfiguration(IType type, ILaunchConfigurationType configType) { // Find an existing or create a launch configuration (Standard way) ILaunchConfiguration iConf = super.findLaunchConfiguration(type, configType); ILaunchConfigurationWorkingCopy iConfWC; try {//from w w w . j ava 2s . co m /* * Tune the default launch configuration: setup run-time classpath manually */ if (iConf == null) { iConf = createConfiguration(type); } iConfWC = iConf.getWorkingCopy(); } catch (CoreException e) { e.printStackTrace(); // FIXME Error dialog return null; } // Configure ODPS launch setting IResource resource = type.getResource(); if (!(resource instanceof IFile)) { return null; } ShotcutConfigWizard wizard = new ShotcutConfigWizard((IFile) resource, iConfWC, type.getFullyQualifiedName()); WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), wizard); dialog.create(); dialog.setBlockOnOpen(true); if (dialog.open() != WizardDialog.OK) { return null; } try { iConfWC.doSave(); } catch (CoreException e) { e.printStackTrace(); // FIXME Error dialog return null; } return iConf; }
From source file:com.aliyun.odps.eclipse.launch.shortcut.udf.UDFLaunchShortcuts.java
License:Apache License
@Override protected ILaunchConfiguration findLaunchConfiguration(IType type, ILaunchConfigurationType configType) { // Find an existing or create a launch configuration (Standard way) ILaunchConfiguration iConf = super.findLaunchConfiguration(type, configType); ILaunchConfigurationWorkingCopy iConfWC; try {// www . ja v a2 s.c o m /* * Tune the default launch configuration: setup run-time classpath manually */ if (iConf == null) { iConf = createConfiguration(type); } iConfWC = iConf.getWorkingCopy(); } catch (CoreException e) { e.printStackTrace(); // FIXME Error dialog return null; } // Configure ODPS launch setting IResource resource = type.getResource(); if (!(resource instanceof IFile)) { return null; } UDFShotcutConfigWizard wizard = new UDFShotcutConfigWizard((IFile) resource, iConfWC, type.getFullyQualifiedName()); WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), wizard); dialog.create(); dialog.setBlockOnOpen(true); if (dialog.open() != WizardDialog.OK) { return null; } try { iConfWC.doSave(); } catch (CoreException e) { e.printStackTrace(); // FIXME Error dialog return null; } return iConf; }
From source file:com.android.ide.eclipse.adt.internal.editors.layout.LayoutContentAssist.java
License:Open Source License
@Override protected boolean computeAttributeValues(List<ICompletionProposal> proposals, int offset, String parentTagName, String attributeName, Node node, String wordPrefix, boolean skipEndTag, int replaceLength) { super.computeAttributeValues(proposals, offset, parentTagName, attributeName, node, wordPrefix, skipEndTag, replaceLength);//from w ww. j av a 2 s. c o m boolean projectOnly = false; List<String> superClasses = null; if (VIEW_FRAGMENT.equals(parentTagName) && (attributeName.endsWith(ATTR_NAME) || attributeName.equals(ATTR_CLASS))) { // Insert fragment class matches superClasses = Arrays.asList(CLASS_V4_FRAGMENT, CLASS_FRAGMENT); } else if (VIEW_TAG.equals(parentTagName) && attributeName.endsWith(ATTR_CLASS)) { // Insert custom view matches superClasses = Collections.singletonList(CLASS_VIEW); projectOnly = true; } else if (attributeName.endsWith(ATTR_CONTEXT)) { // Insert activity matches superClasses = Collections.singletonList(CLASS_ACTIVITY); } if (superClasses != null) { IProject project = mEditor.getProject(); if (project == null) { return false; } try { IJavaProject javaProject = BaseProjectHelper.getJavaProject(project); IType type = javaProject.findType(superClasses.get(0)); Set<IType> elements = new HashSet<IType>(); if (type != null) { ITypeHierarchy hierarchy = type.newTypeHierarchy(new NullProgressMonitor()); IType[] allSubtypes = hierarchy.getAllSubtypes(type); for (IType subType : allSubtypes) { if (!projectOnly || subType.getResource() != null) { elements.add(subType); } } } assert superClasses.size() <= 2; // If more, need to do additional work below if (superClasses.size() == 2) { type = javaProject.findType(superClasses.get(1)); if (type != null) { ITypeHierarchy hierarchy = type.newTypeHierarchy(new NullProgressMonitor()); IType[] allSubtypes = hierarchy.getAllSubtypes(type); for (IType subType : allSubtypes) { if (!projectOnly || subType.getResource() != null) { elements.add(subType); } } } } List<IType> sorted = new ArrayList<IType>(elements); Collections.sort(sorted, new Comparator<IType>() { @Override public int compare(IType type1, IType type2) { String fqcn1 = type1.getFullyQualifiedName(); String fqcn2 = type2.getFullyQualifiedName(); int category1 = fqcn1.startsWith(ANDROID_PKG_PREFIX) ? 1 : -1; int category2 = fqcn2.startsWith(ANDROID_PKG_PREFIX) ? 1 : -1; if (category1 != category2) { return category1 - category2; } return fqcn1.compareTo(fqcn2); } }); addMatchingProposals(proposals, sorted.toArray(), offset, node, wordPrefix, (char) 0, false /* isAttribute */, false /* isNew */, false /* skipEndTag */, replaceLength); return true; } catch (CoreException e) { AdtPlugin.log(e, null); } } return false; }
From source file:com.android.ide.eclipse.adt.internal.editors.manifest.model.UiClassAttributeNode.java
License:Open Source License
@Override public String[] getPossibleValues(String prefix) { // Compute a list of existing classes for content assist completion IProject project = getProject();/*from w w w . jav a2s . co m*/ if (project == null || mReferenceClass == null) { return null; } try { IJavaProject javaProject = BaseProjectHelper.getJavaProject(project); IType type = javaProject.findType(mReferenceClass); // Use sets because query sometimes repeats the same class Set<String> libraryTypes = new HashSet<String>(80); Set<String> localTypes = new HashSet<String>(30); if (type != null) { ITypeHierarchy hierarchy = type.newTypeHierarchy(new NullProgressMonitor()); IType[] allSubtypes = hierarchy.getAllSubtypes(type); for (IType subType : allSubtypes) { int flags = subType.getFlags(); if (Flags.isPublic(flags) && !Flags.isAbstract(flags)) { String fqcn = subType.getFullyQualifiedName(); if (subType.getResource() != null) { localTypes.add(fqcn); } else { libraryTypes.add(fqcn); } } } } List<String> local = new ArrayList<String>(localTypes); List<String> library = new ArrayList<String>(libraryTypes); Collections.sort(local); Collections.sort(library); List<String> combined = new ArrayList<String>(local.size() + library.size()); combined.addAll(local); combined.addAll(library); return combined.toArray(new String[combined.size()]); } catch (Exception e) { AdtPlugin.log(e, null); } return null; }
From source file:com.android.ide.eclipse.adt.internal.refactorings.core.AndroidTypeMoveParticipantTest.java
License:Open Source License
protected void moveType(@NonNull Object[] testData, @NonNull String typeFqcn, @NonNull String destination, boolean updateReferences, @NonNull String expected) throws Exception { IProject project = createProject(testData); IFolder destinationFolder = project.getFolder(destination); IJavaProject javaProject = BaseProjectHelper.getJavaProject(project); assertNotNull(javaProject);/* w w w . j a va 2s . c o m*/ IType type = javaProject.findType(typeFqcn); assertNotNull(typeFqcn, type); assertTrue(typeFqcn, type.exists()); IResource resource = type.getResource(); assertNotNull(typeFqcn, resource); assertTrue(typeFqcn, resource.exists()); IResource[] resources = new IResource[] { resource }; IJavaElement[] elements = new IJavaElement[] { type }; IMovePolicy policy = ReorgPolicyFactory.createMovePolicy(resources, elements); JavaMoveProcessor processor = new JavaMoveProcessor(policy); processor.setUpdateReferences(updateReferences); processor.setUpdateQualifiedNames(true); assertTrue(policy.canEnable()); processor.setDestination(ReorgDestinationFactory.createDestination(destinationFolder)); Shell parent = AdtPlugin.getShell(); assertNotNull(parent); processor.setCreateTargetQueries(new CreateTargetQueries(parent)); processor.setReorgQueries(new ReorgQueries(parent)); MoveRefactoring refactoring = new MoveRefactoring(processor); checkRefactoring(refactoring, expected); }
From source file:com.android.ide.eclipse.adt.SourceRevealer.java
License:Open Source License
/** * Reveal the source for given fully qualified method name.<br> * * The method should take care of the following scenarios:<ol> * <li> A search, either by filename/line number, or for fqmn might provide only 1 result. * In such a case, just open that result. Give preference to the file name/line # search * since that is the most accurate (gets to the line number). </li> * <li> The search might not provide any results. e.g, the method name may be of the form * "com.x.y$1.methodName". Searches for methods within anonymous classes will fail. In * such a case, if the fileName:lineNumber argument is available, a search for that * should be made instead. </li> * <li> The search might provide multiple results. In such a case, the fileName/lineNumber * values should be utilized to narrow down the results.</li> * </ol>//w ww . j a v a 2 s. co m * * @param fqmn fully qualified method name * @param fileName file name in which the method is present, null if not known * @param lineNumber line number in the file which should be given focus, -1 if not known. * Line numbers begin at 1, not 0. * @param perspective perspective to switch to before the source is revealed, null to not * switch perspectives */ @Override public boolean revealMethod(String fqmn, String fileName, int lineNumber, String perspective) { // Search by filename:linenumber. If there is just one result for it, that would // be the correct match that is accurate to the line List<SearchMatch> fileMatches = Collections.emptyList(); if (fileName != null && lineNumber >= 0) { fileMatches = searchForFile(fileName); if (fileMatches.size() == 1) { return revealLineMatch(fileMatches, fileName, lineNumber, perspective); } } List<SearchMatch> methodMatches = searchForMethod(fqmn); // if there is a unique method name match: // 1. if there are > 1 file name matches, try to see if they can be narrowed down // 2. if not, display the method match if (methodMatches.size() == 1) { if (fileMatches.size() > 0) { List<SearchMatch> filteredMatches = filterMatchByResource(fileMatches, methodMatches.get(0).getResource()); if (filteredMatches.size() == 1) { return revealLineMatch(filteredMatches, fileName, lineNumber, perspective); } } else if (fileName != null && lineNumber > 0) { // Couldn't find file match, but we have a filename and line number: attempt // to use this to pinpoint the location within the method IMethod method = (IMethod) methodMatches.get(0).getElement(); IJavaElement element = method; while (element != null) { if (element instanceof ICompilationUnit) { ICompilationUnit unit = ((ICompilationUnit) element).getPrimary(); IResource resource = unit.getResource(); if (resource instanceof IFile) { IFile file = (IFile) resource; try { // See if the line number looks like it's inside the given method ISourceRange sourceRange = method.getSourceRange(); IRegion region = AdtUtils.getRegionOfLine(file, lineNumber - 1); // When fields are initialized with code, this logically belongs // to the constructor, but the line numbers are outside of the // constructor. In this case we'll trust the line number rather // than the method range. boolean isConstructor = fqmn.endsWith(CONSTRUCTOR_NAME); if (isConstructor || region != null && region.getOffset() >= sourceRange.getOffset() && region.getOffset() < sourceRange.getOffset() + sourceRange.getLength()) { // Yes: use the line number instead if (perspective != null) { SourceRevealer.switchToPerspective(perspective); } return displayFile(file, lineNumber); } } catch (JavaModelException e) { AdtPlugin.log(e, null); } } } element = element.getParent(); } } return displayMethod((IMethod) methodMatches.get(0).getElement(), perspective); } // no matches for search by method, so search by filename if (methodMatches.size() == 0) { if (fileMatches.size() > 0) { return revealLineMatch(fileMatches, fileName, lineNumber, perspective); } else { // Last ditch effort: attempt to look up the class corresponding to the fqn // and jump to the line there if (fileMatches.isEmpty() && fqmn.indexOf('.') != -1) { String className = fqmn.substring(0, fqmn.lastIndexOf('.')); for (IJavaProject project : BaseProjectHelper.getAndroidProjects(null)) { IType type; try { type = project.findType(className); if (type != null && type.exists()) { IResource resource = type.getResource(); if (resource instanceof IFile) { if (perspective != null) { SourceRevealer.switchToPerspective(perspective); } return displayFile((IFile) resource, lineNumber); } } } catch (JavaModelException e) { AdtPlugin.log(e, null); } } } return false; } } // multiple matches for search by method, narrow down by filename if (fileName != null) { return revealLineMatch(filterMatchByFileName(methodMatches, fileName), fileName, lineNumber, perspective); } // prompt the user SearchMatch match = getMatchToDisplay(methodMatches, fqmn); if (match == null) { return false; } else { return displayMethod((IMethod) match.getElement(), perspective); } }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.FieldLocator.java
License:Open Source License
protected void reportDeclaration(FieldBinding fieldBinding, MatchLocator locator, SimpleSet knownFields) throws CoreException { // ignore length field if (fieldBinding == ArrayBinding.ArrayLength) return;/*from w ww .j a va2 s. c o m*/ ReferenceBinding declaringClass = fieldBinding.declaringClass; IType type = locator.lookupType(declaringClass); if (type == null) return; // case of a secondary type char[] bindingName = fieldBinding.name; IField field = type.getField(new String(bindingName)); if (knownFields.addIfNotIncluded(field) == null) return; IResource resource = type.getResource(); boolean isBinary = type.isBinary(); IBinaryType info = null; if (isBinary) { if (resource == null) resource = type.getJavaProject().getProject(); info = locator.getBinaryInfo((org.eclipse.jdt.internal.core.ClassFile) type.getClassFile(), resource); locator.reportBinaryMemberDeclaration(resource, field, fieldBinding, info, SearchMatch.A_ACCURATE); } else { if (declaringClass instanceof ParameterizedTypeBinding) declaringClass = ((ParameterizedTypeBinding) declaringClass).genericType(); ClassScope scope = ((SourceTypeBinding) declaringClass).scope; if (scope != null) { TypeDeclaration typeDecl = scope.referenceContext; FieldDeclaration fieldDecl = null; FieldDeclaration[] fieldDecls = typeDecl.fields; int length = fieldDecls == null ? 0 : fieldDecls.length; for (int i = 0; i < length; i++) { if (CharOperation.equals(bindingName, fieldDecls[i].name)) { fieldDecl = fieldDecls[i]; break; } } if (fieldDecl != null) { int offset = fieldDecl.sourceStart; this.match = new FieldDeclarationMatch(((JavaElement) field).resolved(fieldBinding), SearchMatch.A_ACCURATE, offset, fieldDecl.sourceEnd - offset + 1, locator.getParticipant(), resource); locator.report(this.match); } } } }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MethodLocator.java
License:Open Source License
protected void reportDeclaration(MethodBinding methodBinding, MatchLocator locator, SimpleSet knownMethods) throws CoreException { ReferenceBinding declaringClass = methodBinding.declaringClass; IType type = locator.lookupType(declaringClass); if (type == null) return; // case of a secondary type // Report match for binary if (type.isBinary()) { IMethod method = null;/* w w w. j av a 2 s. c o m*/ TypeBinding[] parameters = methodBinding.original().parameters; int parameterLength = parameters.length; char[][] parameterTypes = new char[parameterLength][]; for (int i = 0; i < parameterLength; i++) { char[] typeName = parameters[i].qualifiedSourceName(); for (int j = 0, dim = parameters[i].dimensions(); j < dim; j++) { typeName = CharOperation.concat(typeName, new char[] { '[', ']' }); } parameterTypes[i] = typeName; } method = locator.createBinaryMethodHandle(type, methodBinding.selector, parameterTypes); if (method == null || knownMethods.addIfNotIncluded(method) == null) return; IResource resource = type.getResource(); if (resource == null) resource = type.getJavaProject().getProject(); IBinaryType info = locator.getBinaryInfo((org.eclipse.jdt.internal.core.ClassFile) type.getClassFile(), resource); locator.reportBinaryMemberDeclaration(resource, method, methodBinding, info, SearchMatch.A_ACCURATE); return; } // When source is available, report match if method is found in the declaring type IResource resource = type.getResource(); if (declaringClass instanceof ParameterizedTypeBinding) declaringClass = ((ParameterizedTypeBinding) declaringClass).genericType(); ClassScope scope = ((SourceTypeBinding) declaringClass).scope; if (scope != null) { TypeDeclaration typeDecl = scope.referenceContext; AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(methodBinding.original()); if (methodDecl != null) { // Create method handle from method declaration String methodName = new String(methodBinding.selector); Argument[] arguments = methodDecl.arguments; int length = arguments == null ? 0 : arguments.length; String[] parameterTypes = new String[length]; for (int i = 0; i < length; i++) { char[][] typeName = arguments[i].type.getParameterizedTypeName(); parameterTypes[i] = Signature.createTypeSignature(CharOperation.concatWith(typeName, '.'), false); } IMethod method = type.getMethod(methodName, parameterTypes); if (method == null || knownMethods.addIfNotIncluded(method) == null) return; // Create and report corresponding match int offset = methodDecl.sourceStart; this.match = new MethodDeclarationMatch(method, SearchMatch.A_ACCURATE, offset, methodDecl.sourceEnd - offset + 1, locator.getParticipant(), resource); locator.report(this.match); } } }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.TypeReferenceLocator.java
License:Open Source License
protected void reportDeclaration(ReferenceBinding typeBinding, int maxType, MatchLocator locator, SimpleSet knownTypes) throws CoreException { IType type = locator.lookupType(typeBinding); if (type == null) return; // case of a secondary type IResource resource = type.getResource(); boolean isBinary = type.isBinary(); IBinaryType info = null;/* w ww . j a v a 2 s. c o m*/ if (isBinary) { if (resource == null) resource = type.getJavaProject().getProject(); info = locator.getBinaryInfo((org.eclipse.jdt.internal.core.ClassFile) type.getClassFile(), resource); } while (maxType >= 0 && type != null) { if (!knownTypes.includes(type)) { if (isBinary) { locator.reportBinaryMemberDeclaration(resource, type, typeBinding, info, SearchMatch.A_ACCURATE); } else { if (typeBinding instanceof ParameterizedTypeBinding) typeBinding = ((ParameterizedTypeBinding) typeBinding).genericType(); ClassScope scope = ((SourceTypeBinding) typeBinding).scope; if (scope != null) { TypeDeclaration typeDecl = scope.referenceContext; int offset = typeDecl.sourceStart; this.match = new TypeDeclarationMatch(((JavaElement) type).resolved(typeBinding), SearchMatch.A_ACCURATE, offset, typeDecl.sourceEnd - offset + 1, locator.getParticipant(), resource); locator.report(this.match); } } knownTypes.add(type); } typeBinding = typeBinding.enclosingType(); IJavaElement parent = type.getParent(); if (parent instanceof IType) { type = (IType) parent; } else { type = null; } maxType--; } }