List of usage examples for org.eclipse.jdt.core IClassFile getType
@Deprecated IType getType();
From source file:com.codenvy.ide.ext.java.server.internal.core.ClassFile.java
License:Open Source License
public IJavaElement getElementAtConsideringSibling(int position) throws JavaModelException { IPackageFragment fragment = (IPackageFragment) getParent(); PackageFragmentRoot root = (PackageFragmentRoot) fragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); SourceMapper mapper = root.getSourceMapper(); if (mapper == null) { return null; } else {//w w w. jav a 2s.c o m int index = this.name.indexOf('$'); int prefixLength = index < 0 ? this.name.length() : index; IType type = null; int start = -1; int end = Integer.MAX_VALUE; IJavaElement[] children = fragment.getChildren(); for (int i = 0; i < children.length; i++) { String childName = children[i].getElementName(); int childIndex = childName.indexOf('$'); int childPrefixLength = childIndex < 0 ? childName.indexOf('.') : childIndex; if (prefixLength == childPrefixLength && this.name.regionMatches(0, childName, 0, prefixLength)) { IClassFile classFile = (IClassFile) children[i]; // ensure this class file's buffer is open so that source ranges are computed classFile.getBuffer(); SourceRange range = mapper.getSourceRange(classFile.getType()); if (range == SourceMapper.UNKNOWN_RANGE) continue; int newStart = range.getOffset(); int newEnd = newStart + range.getLength() - 1; if (newStart > start && newEnd < end && newStart <= position && newEnd >= position) { type = classFile.getType(); start = newStart; end = newEnd; } } } if (type != null) { return findElement(type, position, mapper); } return null; } }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java
License:Open Source License
/** * Creates an IType from the given simple top level type name. *///w ww .j a va 2 s .c o m protected IType createTypeHandle(String simpleTypeName) { Openable openable = this.currentPossibleMatch.openable; if (openable instanceof CompilationUnit) return ((CompilationUnit) openable).getType(simpleTypeName); IType binaryType = ((ClassFile) openable).getType(); String binaryTypeQualifiedName = binaryType.getTypeQualifiedName(); if (simpleTypeName.equals(binaryTypeQualifiedName)) return binaryType; // answer only top-level types, sometimes the classFile is for a member/local type // type name may be null for anonymous (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=164791) String classFileName = simpleTypeName.length() == 0 ? binaryTypeQualifiedName : simpleTypeName; IClassFile classFile = binaryType.getPackageFragment() .getClassFile(classFileName + SuffixConstants.SUFFIX_STRING_class); return classFile.getType(); }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.SuperTypeNamesCollector.java
License:Open Source License
public char[][][] collect() throws JavaModelException { if (this.type != null) { // Collect the paths of the cus that are in the hierarchy of the given type this.result = new char[1][][]; this.resultIndex = 0; JavaProject javaProject = (JavaProject) this.type.getJavaProject(); this.locator.initialize(javaProject, 0); try {//from ww w. jav a 2 s . co m if (this.type.isBinary()) { BinaryTypeBinding binding = this.locator.cacheBinaryType(this.type, null); if (binding != null) collectSuperTypeNames(binding, null); } else { ICompilationUnit unit = this.type.getCompilationUnit(); SourceType sourceType = (SourceType) this.type; boolean isTopLevelOrMember = sourceType.getOuterMostLocalContext() == null; CompilationUnitDeclaration parsedUnit = buildBindings(unit, isTopLevelOrMember); if (parsedUnit != null) { TypeDeclaration typeDecl = new ASTNodeFinder(parsedUnit).findType(this.type); if (typeDecl != null && typeDecl.binding != null) collectSuperTypeNames(typeDecl.binding, null); } } } catch (AbortCompilation e) { // problem with classpath: report inaccurate matches return null; } if (this.result.length > this.resultIndex) System.arraycopy(this.result, 0, this.result = new char[this.resultIndex][][], 0, this.resultIndex); return this.result; } // Collect the paths of the cus that declare a type which matches declaringQualification + declaringSimpleName String[] paths = getPathsOfDeclaringType(); if (paths == null) return null; // Create bindings from source types and binary types and collect super type names of the type declaration // that match the given declaring type Util.sort(paths); // sort by projects JavaProject previousProject = null; this.result = new char[1][][]; this.samePackageSuperTypeName = new char[1][][]; this.resultIndex = 0; for (int i = 0, length = paths.length; i < length; i++) { try { //todo Openable Openable openable = null;//this.locator.handleFactory.createOpenable(paths[i], this.locator.scope); if (openable == null) continue; // outside classpath IJavaProject project = openable.getJavaProject(); if (!project.equals(previousProject)) { previousProject = (JavaProject) project; this.locator.initialize(previousProject, 0); } if (openable instanceof ICompilationUnit) { ICompilationUnit unit = (ICompilationUnit) openable; CompilationUnitDeclaration parsedUnit = buildBindings(unit, true /*only top level and member types are visible to the focus type*/); if (parsedUnit != null) parsedUnit.traverse(new TypeDeclarationVisitor(), parsedUnit.scope); } else if (openable instanceof IClassFile) { IClassFile classFile = (IClassFile) openable; BinaryTypeBinding binding = this.locator.cacheBinaryType(classFile.getType(), null); if (matches(binding)) collectSuperTypeNames(binding, binding.compoundName); } } catch (AbortCompilation e) { // ignore: continue with next element } catch (JavaModelException e) { // ignore: continue with next element } } if (this.result.length > this.resultIndex) System.arraycopy(this.result, 0, this.result = new char[this.resultIndex][][], 0, this.resultIndex); return this.result; }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.TypeNameMatchRequestorWrapper.java
License:Open Source License
private IType createTypeFromPath(String resourcePath, String simpleTypeName, char[][] enclosingTypeNames) throws JavaModelException { // path to a file in a directory // Optimization: cache package fragment root handle and package handles int rootPathLength = -1; if (this.lastPkgFragmentRootPath == null || !(resourcePath.startsWith(this.lastPkgFragmentRootPath) && (rootPathLength = this.lastPkgFragmentRootPath.length()) > 0 && resourcePath.charAt(rootPathLength) == '/')) { PackageFragmentRoot root = (PackageFragmentRoot) ((AbstractJavaSearchScope) this.scope) .packageFragmentRoot(resourcePath, -1/*not a jar*/, null/*no jar path*/); if (root == null) return null; this.lastPkgFragmentRoot = root; this.lastPkgFragmentRootPath = root.internalPath().toString(); this.packageHandles = new HashtableOfArrayToObject(5); }//from w ww . java 2 s. co m // create handle resourcePath = resourcePath.substring(this.lastPkgFragmentRootPath.length() + 1); String[] simpleNames = new Path(resourcePath).segments(); String[] pkgName; int length = simpleNames.length - 1; if (length > 0) { pkgName = new String[length]; System.arraycopy(simpleNames, 0, pkgName, 0, length); } else { pkgName = CharOperation.NO_STRINGS; } IPackageFragment pkgFragment = (IPackageFragment) this.packageHandles.get(pkgName); if (pkgFragment == null) { pkgFragment = ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName); this.packageHandles.put(pkgName, pkgFragment); } String simpleName = simpleNames[length]; if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(simpleName)) { ICompilationUnit unit = pkgFragment.getCompilationUnit(simpleName); int etnLength = enclosingTypeNames == null ? 0 : enclosingTypeNames.length; IType type = (etnLength == 0) ? unit.getType(simpleTypeName) : unit.getType(new String(enclosingTypeNames[0])); if (etnLength > 0) { for (int i = 1; i < etnLength; i++) { type = type.getType(new String(enclosingTypeNames[i])); } type = type.getType(simpleTypeName); } return type; } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(simpleName)) { IClassFile classFile = pkgFragment.getClassFile(simpleName); return classFile.getType(); } return null; }
From source file:com.codenvy.ide.ext.java.server.JavaNavigation.java
License:Open Source License
private JarEntry getJarClass(IClassFile classFile) { JarEntry entry = DtoFactory.getInstance().createDto(JarEntry.class); entry.setType(JarEntryType.CLASS_FILE); entry.setName(classFile.getElementName()); entry.setPath(classFile.getType().getFullyQualifiedName()); return entry; }
From source file:com.codenvy.ide.ext.java.server.JavaNavigation.java
License:Open Source License
private OpenDeclarationDescriptor classFileNavigation(IClassFile classFile, IJavaElement element) throws JavaModelException { OpenDeclarationDescriptor dto = DtoFactory.getInstance().createDto(OpenDeclarationDescriptor.class); dto.setPath(classFile.getType().getFullyQualifiedName()); dto.setLibId(classFile.getAncestor(IPackageFragmentRoot.PACKAGE_FRAGMENT_ROOT).hashCode()); dto.setBinary(true);//from www.j a v a2 s . c o m if (classFile.getSourceRange() != null) { if (element instanceof ISourceReference) { ISourceRange nameRange = ((ISourceReference) element).getNameRange(); dto.setOffset(nameRange.getOffset()); dto.setLength(nameRange.getLength()); } } return dto; }
From source file:com.codenvy.ide.ext.java.server.JavaNavigation.java
License:Open Source License
public String getContent(JavaProject project, int rootId, String path) throws CoreException { IPackageFragmentRoot root = getPackageFragmentRoot(project, rootId); if (root == null) { return null; }/*from www . j a v a2 s .c om*/ if (path.startsWith("/")) { //non java file if (root instanceof JarPackageFragmentRoot) { JarPackageFragmentRoot jarPackageFragmentRoot = (JarPackageFragmentRoot) root; ZipFile jar = null; try { jar = jarPackageFragmentRoot.getJar(); ZipEntry entry = jar.getEntry(path.substring(1)); if (entry != null) { try (InputStream stream = jar.getInputStream(entry)) { return IoUtil.readStream(stream); } catch (IOException e) { LOG.error("Can't read file content: " + entry.getName(), e); } } } finally { if (jar != null) { jarPackageFragmentRoot.closeJar(jar); } } } Object[] resources = root.getNonJavaResources(); for (Object resource : resources) { if (resource instanceof JarEntryFile) { JarEntryFile file = (JarEntryFile) resource; if (file.getFullPath().toOSString().equals(path)) { return readFileContent(file); } } if (resource instanceof JarEntryDirectory) { JarEntryDirectory directory = (JarEntryDirectory) resource; JarEntryFile file = findJarFile(directory, path); if (file != null) { return readFileContent(file); } } } } else { //java class or file IType type = project.findType(path); if (type != null && type.isBinary()) { IClassFile classFile = type.getClassFile(); if (classFile.getSourceRange() != null) { return classFile.getSource(); } else { return sourcesGenerator.generateSource(classFile.getType()); } } } return null; }
From source file:com.drgarbage.bytecodevisualizer.editors.BytecodeDocumentProvider.java
License:Apache License
protected boolean setDocumentContent(IDocument document, IEditorInput editorInput, String encoding) throws CoreException { if (editorInput instanceof IClassFileEditorInput) { /* Some kind of IClassFileEditorInput internal, external or a JAR entry */ IClassFileEditorInput classFileEditorInput = (IClassFileEditorInput) editorInput; IClassFile classFile = classFileEditorInput.getClassFile(); String fileName = classFile.getElementName(); String className = classFile.getType().getFullyQualifiedName(); String retrieveFrom = BytecodeVisualizerPlugin.getDefault().getPreferenceStore() .getString(BytecodeVisualizerPreferenceConstats.RETRIEVE_CLASS_FROM); if (BytecodeVisualizerPreferenceConstats.RETRIEVE_CLASS_FROM_JVM_JDI.equals(retrieveFrom)) { /* Use JDI */ /* referenceType will be the class to display over JDI */ ReferenceType referenceType = null; String debugTargetName = null; if (editorInput instanceof JDIEditorInput) { JDIEditorInput jdiEditorInput = (JDIEditorInput) editorInput; JDIStackFrame stackFrame = jdiEditorInput.getStackFrame(); if (stackFrame != null && !stackFrame.isDisconnected() && !stackFrame.isTerminated()) { String stackType = stackFrame.getDeclaringTypeName(); if (className.equals(stackType)) { /* yes, we have to open the same type * so we assume, we have to open the one * selected on the stack */ referenceType = stackFrame.getUnderlyingMethod().declaringType(); debugTargetName = stackFrame.getDebugTarget().getName(); }/*from ww w .j a v a 2 s . c o m*/ } } if (referenceType == null) { /* we were not able to use JDIEditorInput */ /* try to use one of the running debug targets to lookup the class */ ILaunchManager lm = DebugPlugin.getDefault().getLaunchManager(); IDebugTarget[] dts = lm.getDebugTargets(); if (dts != null && dts.length > 0) { /* There are some running debug sessions */ /* Find those ones, which contain the given class */ ArrayList<IJavaType[]> displayCandidates = new ArrayList<IJavaType[]>(dts.length); for (int i = 0; i < dts.length; i++) { if (dts[i] instanceof IJavaDebugTarget && !((IJavaDebugTarget) dts[i]).isTerminated()) { IJavaDebugTarget jdt = (IJavaDebugTarget) dts[i]; IJavaType[] jts = jdt.getJavaTypes(className); if (jts != null && jts.length > 0) { displayCandidates.add(jts); } } } /* select one IJavaDebugTarget */ IJavaType[] jts = null; if (displayCandidates.size() == 1) { jts = displayCandidates.get(0); } else if (displayCandidates.size() > 1) { /* There are several possible debug targets with * the given class loaded. * Let the user select one debug target from a list. */ SelectDebugTargetDialog d = new SelectDebugTargetDialog(className, displayCandidates); int btn = d.open(); if (btn == SelectDebugTargetDialog.OK) { IJavaType[] sel = d.getSelection(); if (sel != null) { jts = sel; } } else { /* Dialog closed or Filesystem button clicked */ } } if (jts != null && jts.length > 0) { IJavaType jt = null; if (jts.length == 1) { /* there is only one such class - take it */ jt = jts[0]; } else { /* let the user select one */ SelectJavaTypeDialog d = new SelectJavaTypeDialog(className, jts[0].getDebugTarget().getName(), jts); d.open(); IJavaType sel = d.getSelection(); if (sel != null) { jt = sel; } } if (jt != null && jt instanceof JDIReferenceType) { referenceType = (ReferenceType) ((JDIReferenceType) jt).getUnderlyingType(); debugTargetName = jt.getDebugTarget().getName(); } } } } if (referenceType != null) { /* we were able to read the referenceType over JDI */ ClassFileOutlineElement outlineElement = new ClassFileOutlineElement(); JDIClassFileDocument doc = new JDIClassFileDocument(referenceType, debugTargetName, outlineElement); outlineElement.setClassFileDocument(doc); doc.createJDIcontent(); document.set(doc.toString()); classFileDocument = doc; classFileOutlineElement = outlineElement; /* fire update document events */ if (documentUpdateListeners != null) { Iterator<IDocumentUpdateListener> it = documentUpdateListeners.iterator(); while (it.hasNext()) { IDocumentUpdateListener l = it.next(); l.documentUpdated(classFileDocument); } } return true; } } /* If we reached this point it means that JDI is not preferred or that JDI did not work. */ IPath filePath = classFile.getPath(); String ext = filePath.getFileExtension(); if (FileExtensions.JAR.equalsIgnoreCase(ext)) { /* really a jar, check if it is an external or internal resource * FIX: bug#50 "java.util.zip.ZipException: error * in opening zip file" on opening*/ File f = null; IResource res = classFile.getResource(); if (res != null) { f = new File(res.getLocationURI()); } else { f = filePath.toFile(); } try { JarFile jarFile = new JarFile(f); String packageName = classFile.getParent().getElementName(); try { String entryName = null; if (packageName.length() == 0) { /* default package * FIX for BUG#213 */ entryName = fileName; } else { entryName = packageName.replace(JavaLexicalConstants.DOT, JavaLexicalConstants.SLASH) + JavaLexicalConstants.SLASH + fileName; } JarEntry jarEntry = jarFile.getJarEntry(entryName); if (jarEntry != null) { InputStream contentStream = jarFile.getInputStream(jarEntry); setDocumentContent(document, contentStream, encoding); return true; } } finally { jarFile.close(); } } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, CoreConstants.BYTECODE_VISUALIZER_PLUGIN_ID, IStatus.OK, BytecodeVisualizerMessages.Error_could_not_load_a_class, e)); } } /* external or internal file archive */ if (FileExtensions.CLASS.equalsIgnoreCase(ext)) { try { File f = filePath.toFile(); if (f.exists()) {/* external file archive */ InputStream contentStream = new FileInputStream(f); setDocumentContent(document, contentStream, encoding); return true; } else {/* internal file archive */ IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(filePath); InputStream contentStream = file.getContents(); setDocumentContent(document, contentStream, encoding); return true; } } catch (FileNotFoundException e) { throw new CoreException(new Status(IStatus.ERROR, CoreConstants.BYTECODE_VISUALIZER_PLUGIN_ID, IStatus.OK, BytecodeVisualizerMessages.Error_could_not_load_a_class, e)); } } } else if (editorInput instanceof FileStoreEditorInput) { /* external class file */ FileStoreEditorInput fileStoreEditorInput = (FileStoreEditorInput) editorInput; try { File f = new File(fileStoreEditorInput.getURI()); InputStream contentStream = new FileInputStream(f); setDocumentContent(document, contentStream, encoding); } catch (FileNotFoundException e) { throw new CoreException(new Status(IStatus.ERROR, CoreConstants.BYTECODE_VISUALIZER_PLUGIN_ID, IStatus.OK, BytecodeVisualizerMessages.Error_could_not_load_a_class, e)); } return true; } else { /* the super class should be able to handle this kind of editorInput */ return super.setDocumentContent(document, editorInput, encoding); } return false; }
From source file:com.drgarbage.controlflowgraphfactory.actions.GenerateGraphsAction.java
License:Apache License
public void run(IAction action) { if (selection == null || !(selection instanceof TreeSelection)) { return;/* w w w. j a va 2s . c o m*/ } final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); ExportGraphFileFolderSelectionDialog dlg = openSelectFolderdialog(targetPart.getSite().getShell(), root); dlg.open(); Object ret = dlg.getFirstResult(); if (ret == null) { return; } final LocalFile localFile = (LocalFile) ret; graphSpecification = dlg.getGraphSpecification(); TreeSelection treeSel = (TreeSelection) selection; final Object o = treeSel.getFirstElement(); IType type = null; if (o instanceof IType) { type = (IType) o; } try { if (type == null) { final IPackageFragment pack = (IPackageFragment) o; final ExportProgressMonitorDialog monitor0 = new ExportProgressMonitorDialog( targetPart.getSite().getShell()); monitor0.setErrorMsg("An error has occured while processing the package '" + pack.getElementName() + "'." + CoreMessages.ExceptionAdditionalMessage); monitor0.run(false, true, new WorkspaceModifyOperation() { /* (non-Javadoc) * @see org.eclipse.ui.actions.WorkspaceModifyOperation#execute(org.eclipse.core.runtime.IProgressMonitor) */ @Override protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { List<IType> listOfTypes = new ArrayList<IType>(); /* * It is possible that a package fragment contains only compilation units * (in other words, its kind is K_SOURCE), in which case this method returns * an empty collection. */ IClassFile[] classFiles = pack.getClassFiles(); for (IClassFile f : classFiles) { listOfTypes.add(f.getType()); } ICompilationUnit[] compilationUnits = pack.getCompilationUnits(); for (ICompilationUnit u : compilationUnits) { IType unitTypes[] = u.getTypes(); for (IType type : unitTypes) { listOfTypes.add(type); } } final int ticks = classFiles.length; monitor.beginTask(ControlFlowFactoryMessages.ProgressDialogCreateGraphs, ticks); boolean yes_To_All = false; for (IType t : listOfTypes) { monitor.subTask(t.getElementName()); Result res = createGraphsForType(t, localFile, root, false, yes_To_All, true); if (res == Result.NO_TO_ALL) { monitor.done(); return; } else if (res == Result.YES_TO_ALL) { yes_To_All = true; } else if (res == Result.ERROR) { monitor0.setErrorDuringExecution(true); } monitor.worked(1); } monitor.done(); } }); } else { Result res = createGraphsForType(type, localFile, root, true, false, false); if (res == Result.ERROR) { Messages.warning("An error has occured while processing the class file '" + type.getElementName() + "'." + CoreMessages.ExceptionAdditionalMessage); } } } catch (InvocationTargetException e) { StringBuffer buf = new StringBuffer("InvocationTargetException: "); Throwable th = e.getTargetException(); if (th != null) { buf.append(th.toString()); } ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, buf.toString(), e)); Messages.error(buf.toString() + CoreMessages.ExceptionAdditionalMessage); return; } catch (InterruptedException e) { ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e)); Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage); return; } catch (JavaModelException e) { ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e)); Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage); return; } finally { dlg = null; } }
From source file:com.google.inject.tools.ideplugin.eclipse.EclipseJavaElement.java
License:Apache License
private String getType(IJavaElement element, String signature) { try {// www. j a v a2 s. c o m IType type = null; ICompilationUnit compilationUnit = (ICompilationUnit) element .getAncestor(IJavaElement.COMPILATION_UNIT); if (compilationUnit != null) { type = compilationUnit.getAllTypes()[0]; } else { IClassFile classFile = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE); if (classFile != null) { type = classFile.getType(); } } String resolvedSignature = TypeUtil.resolveTypeSignature(type, signature, false); String className = getClassNameFromResolvedSignature(resolvedSignature); return className; } catch (Throwable e) { return null; } }