org.eclipse.jdt.core.IPackageFragment Java Examples

The following examples show how to use org.eclipse.jdt.core.IPackageFragment. 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 Project: gwt-eclipse-plugin   Author: gwt-plugins   File: ModuleUtils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Scans the package fragments (including jars if includeJars is true) invoking the visitor
 * callback.
 *
 * Stops if the callback returns a non-null result, and passes that result back to the caller.
 */
private static <T> T visitFragments(IJavaProject project, boolean includeJars, IPackageFragmentVisitor<T> visitor) {
  try {
    for (IPackageFragmentRoot pckgRoot : project.getPackageFragmentRoots()) {
      if (pckgRoot.isArchive() && !includeJars) {
        continue;
      }

      for (IJavaElement elem : pckgRoot.getChildren()) {
        T result = visitor.visit((IPackageFragment) elem);
        if (result != null) {
          return result;
        }
      }
    }
  } catch (JavaModelException e) {
    GWTPluginLog.logError(e);
  }

  return null;
}
 
Example #2
Source Project: eclipse.jdt.ls   Author: eclipse   File: ReorgQuickFixTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testUnusedImportsInDefaultPackage() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("import java.util.Vector;\n");
	buf.append("public class E {\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("\n");
	buf.append("public class E {\n");
	buf.append("}\n");
	Expected e1 = new Expected("Remove unused import", buf.toString());

	buf = new StringBuilder();
	buf.append("public class E {\n");
	buf.append("}\n");
	Expected e2 = new Expected("Organize imports", buf.toString());

	assertCodeActions(cu, e1, e2);
}
 
Example #3
Source Project: eclipse.jdt.ls   Author: eclipse   File: UnresolvedMethodsQuickFixTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testConstructorInvocation() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E {\n");
	buf.append("    public E(int i) {\n");
	buf.append("        this(i, true);\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E {\n");
	buf.append("    public E(int i) {\n");
	buf.append("        this(i, true);\n");
	buf.append("    }\n");
	buf.append("\n");
	buf.append("    public E(int i, boolean b) {\n");
	buf.append("    }\n");
	buf.append("}\n");
	Expected e1 = new Expected("Create constructor 'E(int, boolean)'", buf.toString());

	assertCodeActionExists(cu, e1);
}
 
Example #4
Source Project: eclipse.jdt.ls   Author: eclipse   File: ModifierCorrectionsQuickFixTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testInvalidMemberClassModifiers() throws Exception {
	IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public interface E {\n");
	buf.append("    private class Inner {\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public interface E {\n");
	buf.append("    class Inner {\n");
	buf.append("    }\n");
	buf.append("}\n");
	Expected e1 = new Expected(proposal, buf.toString());

	assertCodeActions(cu, e1);
}
 
Example #5
private static ResourceTraversal[] getPackageFragmentTraversals(IPackageFragment pack) throws CoreException {
	ArrayList<ResourceTraversal> res= new ArrayList<ResourceTraversal>();
	IContainer container= (IContainer)pack.getResource();
	
	if (container != null) {
		res.add(new ResourceTraversal(new IResource[] { container }, IResource.DEPTH_ONE, 0));
		if (pack.exists()) { // folder may not exist any more, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=269167
			Object[] nonJavaResources= pack.getNonJavaResources();
			for (int i= 0; i < nonJavaResources.length; i++) {
				Object resource= nonJavaResources[i];
				if (resource instanceof IFolder) {
					res.add(new ResourceTraversal(new IResource[] { (IResource)resource }, IResource.DEPTH_INFINITE, 0));
				}
			}
		}
	}

	return res.toArray(new ResourceTraversal[res.size()]);
}
 
Example #6
Source Project: dsl-devkit   Author: dsldevkit   File: NewCheckCatalogWizardPage.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public IStatus typeNameChanged() {
  super.typeNameChanged();
  IStatus status = validator.checkCatalogName(getCatalogName());

  if (!previousPageIsProjectPage()) {

    IPackageFragment packageFragment = getPackageFragment();

    if (packageFragment != null && catalogExists(packageFragment.getResource())) {
      return new Status(IStatus.ERROR, status.getPlugin(), NLS.bind(com.avaloq.tools.ddk.check.validation.Messages.CheckJavaValidator_CATALOG_NAME_STATUS, com.avaloq.tools.ddk.check.validation.Messages.CheckJavaValidator_EXISTS));
    }
  }
  if (!status.matches(IStatus.ERROR)) {
    projectInfo.setCatalogName(getCatalogName());
  }
  return status;
}
 
Example #7
Source Project: bonita-studio   Author: bonitasoft   File: PackageFileStore.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void deleteRecursivelyEmptyPackages(final IJavaProject project, IPackageFragment packageFragment) throws JavaModelException {
    if (packageFragment != null) {
        packageFragment.delete(true, new NullProgressMonitor());//delete the first one, we have only one package per Type
        packageFragment = retrieveParentPackageFragment(project, packageFragment);
        while (!packageFragment.hasChildren()) {
            //I don't find another way than passing through IResource, directly using IJavaElement seems not possible.
            final IPackageFragment parent = retrieveParentPackageFragment(project, packageFragment);
            packageFragment.delete(true, new NullProgressMonitor());
            if (parent instanceof IPackageFragment && !parent.isDefaultPackage()) {
                packageFragment = parent;
            } else {
                return;
            }
        }
    }
}
 
Example #8
Source Project: eclipse.jdt.ls   Author: eclipse   File: ReorgPolicyFactory.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean canUpdateQualifiedNames() {
	if (!canEnableQualifiedNameUpdating()) {
		return false;
	}

	IPackageFragment pack= getDestinationAsPackageFragment();
	if (pack == null) {
		return false;
	}

	if (pack.isDefaultPackage()) {
		return false;
	}

	IJavaElement destination= getJavaElementDestination();
	if (destination instanceof IPackageFragmentRoot && getCus().length > 0) {
		return false;
	}

	return true;
}
 
Example #9
/**
 * Adds all of the openables defined within this package fragment to the
 * list.
 */
private void injectAllOpenablesForPackageFragment(
	IPackageFragment packFrag,
	ArrayList openables) {

	try {
		IPackageFragmentRoot root = (IPackageFragmentRoot) packFrag.getParent();
		int kind = root.getKind();
		if (kind != 0) {
			boolean isSourcePackageFragment = (kind == IPackageFragmentRoot.K_SOURCE);
			if (isSourcePackageFragment) {
				ICompilationUnit[] cus = packFrag.getCompilationUnits();
				for (int i = 0, length = cus.length; i < length; i++) {
					openables.add(cus[i]);
				}
			} else {
				IClassFile[] classFiles = packFrag.getClassFiles();
				for (int i = 0, length = classFiles.length; i < length; i++) {
					openables.add(classFiles[i]);
				}
			}
		}
	} catch (JavaModelException e) {
		// ignore
	}
}
 
Example #10
Source Project: txtUML   Author: ELTE-Soft   File: ClassDiagramExporter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private List<Class<?>> loadAllLinksFromModel(String modelName, ElementExporter elementExporter)
		throws NotFoundException, JavaModelException, IOException {
	IJavaProject javaProject = ProjectUtils.findJavaProject(elementExporter.getSourceProjectName());

	// Sneaky.<JavaModelException> Throw();
	// TODO check if explicit type parameters can be omitted > Neon.2
	Stream<ICompilationUnit> stream = Stream.of(PackageUtils.findPackageFragments(javaProject, modelName))
			.flatMap(Sneaky.<IPackageFragment, Stream<ICompilationUnit>, JavaModelException>unchecked(
					pf -> Stream.of(pf.getCompilationUnits())));

	CompilationUnit[] units = SharedUtils.parseICompilationUnitStream(stream, javaProject);

	Iterator<Class<?>> it = elementExporter.getNodes().keySet().iterator();
	if (it.hasNext()) {
		List<Class<?>> allLinks = new ArrayList<>();
		ClassLoader loader = it.next().getClassLoader();
		Stream.of(units).forEach(cu -> cu.accept(new AssociationVisitor(allLinks, loader)));

		return allLinks;
	} else {
		// No exported nodes found.
		throw new NotFoundException();
	}
}
 
Example #11
Source Project: txtUML   Author: ELTE-Soft   File: ElementTypeTeller.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Checks a package if it belong to an existing model. Searches for a
 * package-info.java compilation unit in the package or one of the ancestor
 * packages and checks if it has the {@link Model} annotation.
 */
public static boolean isModelPackage(IPackageFragment pack) {
	try {
		IJavaProject javaProject = pack.getJavaProject();
		String packageName = pack.getElementName();
		for (IPackageFragmentRoot pfRoot : javaProject.getPackageFragmentRoots()) {
			if (!pfRoot.isExternal()) {
				if (isModelPackage(pfRoot, packageName)) {
					return true;
				}
			}
		}
	} catch (JavaModelException e) {
		// TODO: use PluginLogWrapper
		e.printStackTrace();
	}
	return false;
}
 
Example #12
Source Project: eclipse.jdt.ls   Author: eclipse   File: SignatureHelpHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSignatureHelp_singleMethod() throws JavaModelException {
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E {\n");
	buf.append("   /** This is a method */\n");
	buf.append("   public int foo(String s) { }\n");
	buf.append("   public int bar(String s) { this.foo() }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	SignatureHelp help = getSignatureHelp(cu, 4, 39);
	assertNotNull(help);
	assertEquals(1, help.getSignatures().size());
	assertEquals("foo(String s) : int", help.getSignatures().get(0).getLabel());
	assertTrue(help.getSignatures().get(0).getDocumentation().getLeft().length() > 0);
	assertEquals((Integer) 0, help.getActiveParameter());
}
 
Example #13
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: FileTransferDropAdapter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected int determineOperation(Object target, int operation, TransferData transferType, int operations) {

	boolean isPackageFragment= target instanceof IPackageFragment;
	boolean isJavaProject= target instanceof IJavaProject;
	boolean isPackageFragmentRoot= target instanceof IPackageFragmentRoot;
	boolean isContainer= target instanceof IContainer;

	if (!(isPackageFragment || isJavaProject || isPackageFragmentRoot || isContainer))
		return DND.DROP_NONE;

	if (isContainer) {
		IContainer container= (IContainer)target;
		if (container.isAccessible() && !Resources.isReadOnly(container))
			return DND.DROP_COPY;
	} else {
		IJavaElement element= (IJavaElement)target;
		if (!element.isReadOnly())
			return DND.DROP_COPY;
	}

	return DND.DROP_NONE;
}
 
Example #14
Source Project: xtext-eclipse   Author: eclipse   File: CreateJavaTypeQuickfixes.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected void setPackageName(NewTypeWizardPage page, URI contextUri, String packageName) {
	IJavaProject javaProject = getJavaProject(contextUri);
	String path = contextUri.trimSegments(1).toPlatformString(true);
	try {
		if(javaProject != null) {
			IPackageFragment contextPackageFragment = javaProject.findPackageFragment(new Path(path));
			if (contextPackageFragment != null) {
				IPackageFragmentRoot root = (IPackageFragmentRoot) contextPackageFragment
						.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
				IPackageFragment packageFragment;
				if(!isEmpty(packageName)) {
					packageFragment = root.getPackageFragment(packageName);
				} else {
					packageFragment = contextPackageFragment;
				}
				page.setPackageFragment(packageFragment, true);
				page.setPackageFragmentRoot(root, true);
			}
		}
	} catch (JavaModelException e) {
		LOG.error("Could not find package for " + path, e);
	}
}
 
Example #15
private List<IAdaptable> getFoldersAndElements(IResource[] resources) {
	List<IAdaptable> list= new ArrayList<IAdaptable>();
	for (int i= 0; i < resources.length; i++) {
		IResource resource= resources[i];

		if (resource instanceof IFolder) {
			IFolder folder= (IFolder) resource;
			IJavaElement element= JavaCore.create(folder);

			if (element instanceof IPackageFragment) {
				list.add(element);
			} else {
				list.add(folder);
			}
		}
	}
	return list;
}
 
Example #16
Source Project: eclipse.jdt.ls   Author: eclipse   File: SignatureHelpHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSignatureHelp_assertEquals() throws Exception {
	importProjects("maven/classpathtest");
	project = WorkspaceHelper.getProject("classpathtest");
	IJavaProject javaProject = JavaCore.create(project);
	sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src/test/java"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("import static org.junit.Assert.assertEquals;\n");
	buf.append("public class E {\n");
	buf.append("	public static void main(String[] args) {\n");
	buf.append("		 long num = 1;\n");
	buf.append("		 assertEquals(num,num)\n");
	buf.append("	}\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	testAssertEquals(cu, 5, 16);
	testAssertEquals(cu, 5, 17);
	testAssertEquals(cu, 5, 18);
	testAssertEquals(cu, 5, 19);
	testAssertEquals(cu, 5, 20);
	testAssertEquals(cu, 5, 21);
	testAssertEquals(cu, 5, 22);
}
 
Example #17
Source Project: eclipse.jdt.ls   Author: eclipse   File: TypeMismatchQuickFixTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testTypeMismatchWithEnumConstant() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("pack", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package pack;\n");
	buf.append("public enum E {\n");
	buf.append("    ONE;\n");
	buf.append("    int m(int i) {\n");
	buf.append("            return ONE;\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package pack;\n");
	buf.append("public enum E {\n");
	buf.append("    ONE;\n");
	buf.append("    E m(int i) {\n");
	buf.append("            return ONE;\n");
	buf.append("    }\n");
	buf.append("}\n");
	Expected e1 = new Expected("Change method return type to 'E'", buf.toString());
	assertCodeActions(cu, e1);
}
 
Example #18
private Object[] getPackageContents(IPackageFragment fragment) throws JavaModelException {
	ISourceReference[] sourceRefs;
	if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
		sourceRefs= fragment.getCompilationUnits();
	}
	else {
		IClassFile[] classFiles= fragment.getClassFiles();
		List<IClassFile> topLevelClassFile= new ArrayList<IClassFile>();
		for (int i= 0; i < classFiles.length; i++) {
			IType type= classFiles[i].getType();
			if (type != null && type.getDeclaringType() == null && !type.isAnonymous() && !type.isLocal())
				topLevelClassFile.add(classFiles[i]);
		}
		sourceRefs= topLevelClassFile.toArray(new ISourceReference[topLevelClassFile.size()]);
	}

	Object[] result= new Object[0];
	for (int i= 0; i < sourceRefs.length; i++)
		result= concatenate(result, removeImportAndPackageDeclarations(getChildren(sourceRefs[i])));
	return concatenate(result, fragment.getNonJavaResources());
}
 
Example #19
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: OpenAction.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private Object getPackageFragmentObjectToOpen(IPackageFragment packageFragment) throws JavaModelException {
	ITypeRoot typeRoot= null;
	IPackageFragmentRoot root= (IPackageFragmentRoot) packageFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
	if (root.getKind() == IPackageFragmentRoot.K_BINARY)
		typeRoot= (packageFragment).getClassFile(JavaModelUtil.PACKAGE_INFO_CLASS);
	else
		typeRoot= (packageFragment).getCompilationUnit(JavaModelUtil.PACKAGE_INFO_JAVA);
	if (typeRoot.exists())
		return typeRoot;
	
	Object[] nonJavaResources= (packageFragment).getNonJavaResources();
	for (Object nonJavaResource : nonJavaResources) {
		if (nonJavaResource instanceof IFile) {
			IFile file= (IFile) nonJavaResource;
			if (file.exists() && JavaModelUtil.PACKAGE_HTML.equals(file.getName())) {
				return file;
			}
		}
	}
	return packageFragment;
}
 
Example #20
Source Project: eclipse.jdt.ls   Author: eclipse   File: UnresolvedVariablesQuickFixTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testVarWithMethodName1() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E {\n");
	buf.append("    int foo(String str) {\n");
	buf.append("        for (int i = 0; i > str.length; i++) {\n");
	buf.append("        }\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E {\n");
	buf.append("    int foo(String str) {\n");
	buf.append("        for (int i = 0; i > str.length(); i++) {\n");
	buf.append("        }\n");
	buf.append("    }\n");
	buf.append("}\n");
	Expected e1 = new Expected("Change to 'length()'", buf.toString());

	assertCodeActions(cu, e1);
}
 
Example #21
Source Project: eclipse.jdt.ls   Author: eclipse   File: PrepareRenameHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testRenameTypeWithResourceChanges() throws JavaModelException, BadLocationException {
	when(clientPreferences.isResourceOperationSupported()).thenReturn(true);

	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	String[] codes = { "package test1;\n",
			           "public class E|* {\n",
			           "   public E() {\n",
			           "   }\n",
			           "   public int bar() {\n", "   }\n",
			           "   public int foo() {\n",
			           "		this.bar();\n",
			           "   }\n",
			           "}\n" };
	StringBuilder builder = new StringBuilder();
	Position pos = mergeCode(builder, codes);
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", builder.toString(), false, null);

	Either<Range, PrepareRenameResult> result = prepareRename(cu, pos, "Newname");
	assertNotNull(result.getLeft());
	assertTrue(result.getLeft().getStart().getLine() > 0);
}
 
Example #22
Source Project: eclipse.jdt.ls   Author: eclipse   File: DocumentLifeCycleHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testReconcile() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E123 {\n");
	buf.append("    public void testing() {\n");
	buf.append("        int someIntegerChanged = 5;\n");
	buf.append("        int i = someInteger + 5\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu1 = pack1.createCompilationUnit("E123.java", buf.toString(), false, null);
	openDocument(cu1, cu1.getSource(), 1);
	assertEquals(true, cu1.isWorkingCopy());
	assertEquals(false, cu1.hasUnsavedChanges());
	List<PublishDiagnosticsParams> diagnosticsParams = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticsParams.size());
	PublishDiagnosticsParams diagnosticsParam = diagnosticsParams.get(0);
	List<Diagnostic> diagnostics = diagnosticsParam.getDiagnostics();
	assertEquals(2, diagnostics.size());
	diagnosticsParams.clear();
	closeDocument(cu1);
}
 
Example #23
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: EmptyPackageFilter.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean select(Viewer viewer, Object parent, Object element) {
	if (element instanceof IPackageFragment) {
		IPackageFragment pkg= (IPackageFragment)element;
		try {
			return pkg.hasChildren() || hasUnfilteredResources(viewer, pkg);
		} catch (JavaModelException e) {
			return false;
		}
	}
	return true;
}
 
Example #24
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: ResourceUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the classpath-relative path (with slashes, not dots) of the file
 * with the given filename.
 */
public static IPath getClasspathRelativePath(IPackageFragment pckg,
    String filename) {
  if (pckg.isDefaultPackage()) {
    return new Path(filename);
  }
  return new Path(pckg.getElementName().replace('.', '/')).append(filename);
}
 
Example #25
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: MoveCuUpdateCreator.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static SearchResultGroup[] getReferences(ICompilationUnit unit, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
	final SearchPattern pattern= RefactoringSearchEngine.createOrPattern(unit.getTypes(), IJavaSearchConstants.REFERENCES);
	if (pattern != null) {
		String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getFileName(unit));
		ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription);
		Collector requestor= new Collector(((IPackageFragment) unit.getParent()), binaryRefs);
		IJavaSearchScope scope= RefactoringScopeFactory.create(unit, true, false);

		SearchResultGroup[] result= RefactoringSearchEngine.search(pattern, scope, requestor, new SubProgressMonitor(pm, 1), status);
		binaryRefs.addErrorIfNecessary(status);
		return result;
	}
	return new SearchResultGroup[] {};
}
 
Example #26
private void setDefaults(IPackageFragment fragment, ICompilationUnit cu) {
	IJavaElement element= fragment;
	if (element == null) {
		element= cu;
	}

	fSourceFolderSelection.setRoot(searchSourcePackageFragmentRoot(element));
	fPackageSelection.setPackageFragment(searchPackageFragment(element));
}
 
Example #27
Source Project: eclipse.jdt.ls   Author: eclipse   File: JavaDocLocations.java    License: 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 #28
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: JavaModelUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Finds a type container by container name. The returned element will be of type
 * <code>IType</code> or a <code>IPackageFragment</code>. <code>null</code> is returned if the
 * type container could not be found.
 * 
 * @param jproject The Java project defining the context to search
 * @param typeContainerName A dot separated name of the type container
 * @return returns the container
 * @throws JavaModelException thrown when the project can not be accessed
 * @see #getTypeContainerName(IType)
 */
public static IJavaElement findTypeContainer(IJavaProject jproject, String typeContainerName) throws JavaModelException {
	// try to find it as type
	IJavaElement result= jproject.findType(typeContainerName);
	if (result == null) {
		// find it as package
		IPath path= new Path(typeContainerName.replace('.', '/'));
		result= jproject.findElement(path);
		if (!(result instanceof IPackageFragment)) {
			result= null;
		}

	}
	return result;
}
 
Example #29
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: ModuleUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Find modules in package
 *
 * @param pckg
 * @param modules
 * @param includeJars
 * @throws JavaModelException
 */
protected static void testNonJavaResourcesForModules(IPackageFragment pckg, Map<String, IModule> modules,
    boolean includeJars) throws JavaModelException {
  for (Object resource : pckg.getNonJavaResources()) {
    IModule module = create(resource, includeJars);
    if (module != null) {
      String moduleName = module.getQualifiedName();
      if (!modules.containsKey(moduleName)) {
        modules.put(moduleName, module);
      }
    }
  }
}
 
Example #30
Source Project: eclipse.jdt.ls   Author: eclipse   File: UnresolvedMethodsQuickFixTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testStaticMethodInInterface3() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class XX {\n");
	buf.append("    interface I {\n");
	buf.append("        int i= n();\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("XX.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class XX {\n");
	buf.append("    interface I {\n");
	buf.append("        int i= n();\n");
	buf.append("\n");
	buf.append("        static int n() {\n");
	buf.append("            return 0;\n");
	buf.append("        }\n");
	buf.append("    }\n");
	buf.append("}\n");
	Expected e1 = new Expected("Create method 'n()'", buf.toString());

	buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class XX {\n");
	buf.append("    interface I {\n");
	buf.append("        int i= n();\n");
	buf.append("    }\n");
	buf.append("\n");
	buf.append("    protected static int n() {\n");
	buf.append("        return 0;\n");
	buf.append("    }\n");
	buf.append("}\n");
	Expected e2 = new Expected("Create method 'n()' in type 'XX'", buf.toString());

	assertCodeActions(cu, e1, e2);
}