Java Code Examples for org.eclipse.jdt.core.IType#getPackageFragment()

The following examples show how to use org.eclipse.jdt.core.IType#getPackageFragment() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypeContextChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static List<TypeNameMatch> findTypeInfos(String typeName, IType contextType, IProgressMonitor pm) throws JavaModelException {
	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaProject[]{contextType.getJavaProject()}, true);
	IPackageFragment currPackage= contextType.getPackageFragment();
	ArrayList<TypeNameMatch> collectedInfos= new ArrayList<TypeNameMatch>();
	TypeNameMatchCollector requestor= new TypeNameMatchCollector(collectedInfos);
	int matchMode= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
	new SearchEngine().searchAllTypeNames(null, matchMode, typeName.toCharArray(), matchMode, IJavaSearchConstants.TYPE, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, pm);

	List<TypeNameMatch> result= new ArrayList<TypeNameMatch>();
	for (Iterator<TypeNameMatch> iter= collectedInfos.iterator(); iter.hasNext();) {
		TypeNameMatch curr= iter.next();
		IType type= curr.getType();
		if (type != null) {
			boolean visible=true;
			try {
				visible= JavaModelUtil.isVisible(type, currPackage);
			} catch (JavaModelException e) {
				//Assume visibile if not available
			}
			if (visible) {
				result.add(curr);
			}
		}
	}
	return result;
}
 
Example 2
Source File: SourceFileStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void doDelete() {
    final IJavaProject project = getRepository().getJavaProject();
    try {
        final IType type = project.findType(qualifiedClassName);
        if (type != null) {
            final IPackageFragment packageFragment = type.getPackageFragment();
            final ICompilationUnit compilationUnit = type.getCompilationUnit();
            if (compilationUnit != null) {
                closeRelatedEditorIfOpened(compilationUnit);//the editor need to be closed here, otherwise the PackageFragment are not refreshed correctly
                compilationUnit.delete(true, new NullProgressMonitor());
                deleteRecursivelyEmptyPackages(project, packageFragment);
            }
        } else {
            super.doDelete();
        }
    } catch (final JavaModelException e1) {
        BonitaStudioLog.error(e1);
        super.doDelete();
    } catch (final CoreException e) {
        BonitaStudioLog.error(e);
    }
}
 
Example 3
Source File: JavaDocLocations.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void appendTypePath(IType type, StringBuffer buf) {
	IPackageFragment pack = type.getPackageFragment();
	String packPath = pack.getElementName().replace('.', '/');
	String typePath = type.getTypeQualifiedName('.');
	if (packPath.length() > 0) {
		buf.append(packPath);
		buf.append('/');
	}
	buf.append(typePath);
	buf.append(".html"); //$NON-NLS-1$
}
 
Example 4
Source File: ChangeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static ICompilationUnit getNewCompilationUnit(IType type, String newName) {
	ICompilationUnit cu = type.getCompilationUnit();
	if (isPrimaryType(type)) {
		IPackageFragment parent = type.getPackageFragment();
		String renamedCUName = JavaModelUtil.getRenamedCUName(cu, newName);
		return parent.getCompilationUnit(renamedCUName);
	} else {
		return cu;
	}
}
 
Example 5
Source File: JavaQueryParticipantTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public void testElementSearch() throws CoreException {
  IType cu1Type = getTestType1();
  IJavaElement element;

  // Search for type references
  element = cu1Type;
  Match[] expected = new Match[] {
      createWindowsTestMatch(665, 41), createWindowsTestMatch(735, 41),
      createWindowsTestMatch(840, 41), createWindowsTestMatch(947, 41),
      createWindowsTestMatch(1125, 41), createWindowsTestMatch(1207, 41),
      createWindowsTestMatch(1297, 41), createWindowsTestMatch(1419, 41),
      createWindowsTestMatch(1545, 41), createWindowsTestMatch(1619, 41)};
  assertSearchMatches(expected, createQuery(element));

  // Search for field references
  element = cu1Type.getField("keith");
  assertSearchMatch(createWindowsTestMatch(990, 5), createQuery(element));

  // Search for method references
  element = cu1Type.getMethod("getNumber", NO_PARAMS);
  assertSearchMatch(createWindowsTestMatch(1588, 9), createQuery(element));

  // Search for constructor references
  element = cu1Type.getType("InnerSub").getMethod("InnerSub",
      new String[] {"QString;"});
  assertSearchMatch(createWindowsTestMatch(892, 3), createQuery(element));

  // Search for package references (unsupported)
  element = cu1Type.getPackageFragment();
  assertSearchMatches(NO_MATCHES, createQuery(element));
}
 
Example 6
Source File: JavaDocLocations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void appendTypePath(IType type, StringBuffer buf) {
	IPackageFragment pack= type.getPackageFragment();
	String packPath= pack.getElementName().replace('.', '/');
	String typePath= type.getTypeQualifiedName('.');
	if (packPath.length() > 0) {
		buf.append(packPath);
		buf.append('/');
	}
	buf.append(typePath);
	buf.append(".html"); //$NON-NLS-1$
}
 
Example 7
Source File: LevelTreeContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Object getParent(Object child) {
	Object possibleParent= internalGetParent(child);
	if (possibleParent instanceof IJavaElement) {
		IJavaElement javaElement= (IJavaElement) possibleParent;
		for (int j= fCurrentLevel; j < MAX_LEVEL + 1; j++) {
			for (int i= 0; i < JAVA_ELEMENT_TYPES[j].length; i++) {
				if (javaElement.getElementType() == JAVA_ELEMENT_TYPES[j][i]) {
					return null;
				}
			}
		}
	} else if (possibleParent instanceof IResource) {
		IResource resource= (IResource) possibleParent;
		for (int j= fCurrentLevel; j < MAX_LEVEL + 1; j++) {
			for (int i= 0; i < RESOURCE_TYPES[j].length; i++) {
				if (resource.getType() == RESOURCE_TYPES[j][i]) {
					return null;
				}
			}
		}
	}
	if (fCurrentLevel != LEVEL_FILE && child instanceof IType) {
		IType type= (IType) child;
		if (possibleParent instanceof ICompilationUnit
				|| possibleParent instanceof IClassFile)
			possibleParent= type.getPackageFragment();
	}
	return possibleParent;
}
 
Example 8
Source File: BinaryTypeConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Convert a binary type into an AST type declaration and put it in the given compilation unit.
 */
public TypeDeclaration buildTypeDeclaration(IType type, CompilationUnitDeclaration compilationUnit)  throws JavaModelException {
	PackageFragment pkg = (PackageFragment) type.getPackageFragment();
	char[][] packageName = Util.toCharArrays(pkg.names);

	if (packageName.length > 0) {
		compilationUnit.currentPackage = new ImportReference(packageName, new long[]{0}, false, ClassFileConstants.AccDefault);
	}

	/* convert type */
	TypeDeclaration typeDeclaration = convert(type, null, null);

	IType alreadyComputedMember = type;
	IType parent = type.getDeclaringType();
	TypeDeclaration previousDeclaration = typeDeclaration;
	while(parent != null) {
		TypeDeclaration declaration = convert(parent, alreadyComputedMember, previousDeclaration);

		alreadyComputedMember = parent;
		previousDeclaration = declaration;
		parent = parent.getDeclaringType();
	}

	compilationUnit.types = new TypeDeclaration[]{previousDeclaration};

	return typeDeclaration;
}
 
Example 9
Source File: Jdt2Ecore.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies if the target feature is visible from the type.
 *
 * <p>The type finder could be obtained with {@link #toTypeFinder(IJavaProject)}.
 *
 * @param typeFinder the type finder to be used for finding the type definitions.
 * @param fromType the type from which the feature visibility is tested.
 * @param target the feature to test for the visibility.
 * @return <code>true</code> if the given type can see the target feature.
 * @throws JavaModelException if the Java model is invalid.
 * @see #toTypeFinder(IJavaProject)
 */
public boolean isVisible(TypeFinder typeFinder, IType fromType, IMember target) throws JavaModelException {
	final int flags = target.getFlags();
	if (Flags.isPublic(flags)) {
		return true;
	}
	final String fromTypeName = fromType.getFullyQualifiedName();
	final String memberType = target.getDeclaringType().getFullyQualifiedName();
	if (Flags.isPrivate(flags)) {
		return target.getDeclaringType().getFullyQualifiedName().equals(fromTypeName);
	}
	if (Flags.isProtected(flags)) {
		IType t = fromType;
		while (t != null) {
			if (memberType.equals(t.getFullyQualifiedName())) {
				return true;
			}
			final String typeName = t.getSuperclassName();
			if (Strings.isNullOrEmpty(typeName)) {
				t = null;
			} else {
				t = typeFinder.findType(typeName);
			}
		}
	}
	final IPackageFragment f1 = target.getDeclaringType().getPackageFragment();
	final IPackageFragment f2 = fromType.getPackageFragment();
	if (f1.isDefaultPackage()) {
		return f2.isDefaultPackage();
	}
	return f1.getElementName().equals(f2.getElementName());
}
 
Example 10
Source File: CreateAsyncInterfaceProposal.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
public static List<IJavaCompletionProposal> createProposals(IInvocationContext context, IProblemLocation problem)
    throws JavaModelException {
  String syncTypeName = problem.getProblemArguments()[0];
  IJavaProject javaProject = context.getCompilationUnit().getJavaProject();
  IType syncType = JavaModelSearch.findType(javaProject, syncTypeName);
  if (syncType == null || !syncType.isInterface()) {
    return Collections.emptyList();
  }

  CompilationUnit cu = context.getASTRoot();
  ASTNode coveredNode = problem.getCoveredNode(cu);
  TypeDeclaration syncTypeDecl = (TypeDeclaration) coveredNode.getParent();
  assert (cu.getAST().hasResolvedBindings());

  ITypeBinding syncTypeBinding = syncTypeDecl.resolveBinding();
  assert (syncTypeBinding != null);

  String asyncName = RemoteServiceUtilities.computeAsyncTypeName(problem.getProblemArguments()[0]);
  AST ast = context.getASTRoot().getAST();
  Name name = ast.newName(asyncName);

  /*
   * HACK: NewCUUsingWizardProposal wants a name that has a parent expression so we create an
   * assignment so that the name has a valid parent
   */
  ast.newAssignment().setLeftHandSide(name);

  IJavaElement typeContainer = syncType.getParent();
  if (typeContainer.getElementType() == IJavaElement.COMPILATION_UNIT) {
    typeContainer = syncType.getPackageFragment();
  }

  // Add a create async interface proposal
  CreateAsyncInterfaceProposal createAsyncInterfaceProposal = new CreateAsyncInterfaceProposal(
      context.getCompilationUnit(), name, K_INTERFACE, typeContainer, 2, syncTypeBinding);

  // Add the stock create interface proposal
  NewCompilationUnitUsingWizardProposal fallbackProposal = new NewCompilationUnitUsingWizardProposal(
      context.getCompilationUnit(), name, K_INTERFACE, context.getCompilationUnit().getParent(), 1);

  return Arrays.<IJavaCompletionProposal>asList(createAsyncInterfaceProposal, fallbackProposal);
}
 
Example 11
Source File: SourceMapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Locates and returns source code for the given (binary) type, in this
 * SourceMapper's ZIP file, or returns <code>null</code> if source
 * code cannot be found.
 * The given simpleSourceFileName is the .java file name (without the enclosing
 * folder) used to create the given type (e.g. "A.java" for x/y/A$Inner.class)
 */
public char[] findSource(IType type, String simpleSourceFileName) {
	long time = 0;
	if (VERBOSE) {
		time = System.currentTimeMillis();
	}
	PackageFragment pkgFrag = (PackageFragment) type.getPackageFragment();
	String name = org.eclipse.jdt.internal.core.util.Util.concatWith(pkgFrag.names, simpleSourceFileName, '/');

	char[] source = null;

	JavaModelManager javaModelManager = JavaModelManager.getJavaModelManager();
	try {
		javaModelManager.cacheZipFiles(this); // Cache any zip files we open during this operation

		if (this.rootPath != null) {
			source = getSourceForRootPath(this.rootPath, name);
		}

		if (source == null) {
			computeAllRootPaths(type);
			if (this.rootPaths != null) {
				loop: for (Iterator iterator = this.rootPaths.iterator(); iterator.hasNext(); ) {
					String currentRootPath = (String) iterator.next();
					if (!currentRootPath.equals(this.rootPath)) {
						source = getSourceForRootPath(currentRootPath, name);
						if (source != null) {
							// remember right root path
							this.rootPath = currentRootPath;
							break loop;
						}
					}
				}
			}
		}
	} finally {
		javaModelManager.flushZipFiles(this); // clean up cached zip files.
	}
	if (VERBOSE) {
		System.out.println("spent " + (System.currentTimeMillis() - time) + "ms for " + type.getElementName()); //$NON-NLS-1$ //$NON-NLS-2$
	}
	return source;
}