Java Code Examples for org.eclipse.jdt.core.JavaModelException

The following examples show how to use org.eclipse.jdt.core.JavaModelException. These examples are extracted from open source projects. 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
protected T traverse(IPackageFragment pack, boolean stopOnFirstResult, TraversalState state) throws JavaModelException {
	T result = null;
	state.push(pack);
	IJavaElement[] children = pack.getChildren();
	for (IJavaElement iJavaElement : children) {
		if (iJavaElement instanceof IPackageFragment) {
			result = traverse((IPackageFragment) iJavaElement, stopOnFirstResult, state);
			if (stopOnFirstResult && result!=null)
				return result;
		}
	}
	Object[] resources = pack.getNonJavaResources();
	for (Object object : resources) {
		if (object instanceof IJarEntryResource) {
			result = traverse((IJarEntryResource) object, stopOnFirstResult, state);
			if (stopOnFirstResult && result!=null)
				return result;
		}
	}
	state.pop();
	return result;
}
 
Example 2
protected IPackageFragmentRoot getJavaElement(final IFile file) {
	IJavaProject jp = JavaCore.create(file.getProject());
	if (!jp.exists())
		return null;
	IPackageFragmentRoot[] roots;
	try {
		roots = jp.getPackageFragmentRoots();
		for (IPackageFragmentRoot root : roots) {
			if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
				IResource resource2 = root.getUnderlyingResource();
				if (resource2.contains(file))
					return root;
			}
		}
	} catch (JavaModelException e) {
		if (!e.isDoesNotExist())
			log.error(e.getMessage(), e);
	}
	return null;
}
 
Example 3
@Test
public void testCompletion_import_type() throws JavaModelException{
	ICompilationUnit unit = getWorkingCopy(
			"src/java/Foo.java",
			"import java.sq \n" +
					"public class Foo {\n"+
					"	void foo() {\n"+
					"   java.util.Ma\n"+
					"	}\n"+
			"}\n");

	int[] loc = findCompletionLocation(unit, "java.util.Ma");

	CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight();

	assertNotNull(list);
	assertEquals(1, list.getItems().size());
	CompletionItem item = list.getItems().get(0);
	assertEquals(CompletionItemKind.Interface, item.getKind());
	assertEquals("Map", item.getInsertText());
	assertNotNull(item.getTextEdit());
	assertTextEdit(3, 3, 15, "java.util.Map", item.getTextEdit());
	assertTrue(item.getFilterText().startsWith("java.util.Ma"));
	//Not checking the range end character
}
 
Example 4
private static boolean isMoveStaticMemberAvailable(ASTNode declaration) throws JavaModelException {
	if (declaration instanceof MethodDeclaration) {
		IMethodBinding method = ((MethodDeclaration) declaration).resolveBinding();
		return method != null && RefactoringAvailabilityTesterCore.isMoveStaticAvailable((IMember) method.getJavaElement());
	} else if (declaration instanceof FieldDeclaration) {
		List<IMember> members = new ArrayList<>();
		for (Object fragment : ((FieldDeclaration) declaration).fragments()) {
			IVariableBinding variable = ((VariableDeclarationFragment) fragment).resolveBinding();
			if (variable != null) {
				members.add((IField) variable.getJavaElement());
			}
		}
		return RefactoringAvailabilityTesterCore.isMoveStaticMembersAvailable(members.toArray(new IMember[0]));
	} else if (declaration instanceof AbstractTypeDeclaration) {
		ITypeBinding type = ((AbstractTypeDeclaration) declaration).resolveBinding();
		return type != null && RefactoringAvailabilityTesterCore.isMoveStaticAvailable((IType) type.getJavaElement());
	}

	return false;
}
 
Example 5
@Test
public void testRenameTypeParameter() throws JavaModelException, BadLocationException {
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	String[] codes= {
			"package test1;\n",
			"public class A<T|*> {\n",
			"	private T t;\n",
			"	public T get() { return t; }\n",
			"}\n"
	};

	StringBuilder builder = new StringBuilder();
	Position pos = mergeCode(builder, codes);
	ICompilationUnit cu = pack1.createCompilationUnit("A.java", builder.toString(), false, null);


	Either<Range, PrepareRenameResult> result = prepareRename(cu, pos, "TT");
	assertNotNull(result.getLeft());
	assertTrue(result.getLeft().getStart().getLine() > 0);
}
 
Example 6
private int compareInHierarchy(IType def1, IType def2) {
	if (JavaModelUtil.isSuperType(getHierarchy(def1), def2, def1)) {
		return 1;
	} else if (JavaModelUtil.isSuperType(getHierarchy(def2), def1, def2)) {
		return -1;
	}
	// interfaces after classes
	try {
		int flags1= getTypeFlags(def1);
		int flags2= getTypeFlags(def2);
		if (Flags.isInterface(flags1)) {
			if (!Flags.isInterface(flags2)) {
				return 1;
			}
		} else if (Flags.isInterface(flags2)) {
			return -1;
		}
	} catch (JavaModelException e) {
		// ignore
	}
	String name1= def1.getElementName();
	String name2= def2.getElementName();

	return getComparator().compare(name1, name2);
}
 
Example 7
private String createEqualsMethodContent(EqualsHashCodeGenerationData data, IType objectClass)
        throws JavaModelException {
    StringBuffer content = new StringBuffer();
    String elementName = objectClass.getElementName();
    content.append(MethodContentGenerations.createEqualsContentPrefix(data, objectClass));
    content.append(elementName);
    content.append(" castOther = (");
    content.append(elementName);
    content.append(") other;\n");
    content.append("return new EqualsBuilder()");
    if (data.appendSuper()) {
        content.append(".appendSuper(super.equals(other))");
    }
    IField[] checkedFields = data.getCheckedFields();
    for (int i = 0; i < checkedFields.length; i++) {
        content.append(".append(");
        String fieldName = MethodContentGenerations.getFieldAccessorString(checkedFields[i],
                data.useGettersInsteadOfFields());
        content.append(fieldName);
        content.append(", castOther.");
        content.append(fieldName);
        content.append(")");
    }
    content.append(".isEquals();\n");
    return content.toString();
}
 
Example 8
/**
 * Returns the visibility threshold from a type to a field.
 *
 * @param referencing the referencing type
 * @param referenced the referenced field
 * @param monitor the progress monitor to use
 * @return the visibility keyword corresponding to the threshold, or <code>null</code> for default visibility
 * @throws JavaModelException if the java elements could not be accessed
 */
private ModifierKeyword thresholdTypeToField(final IType referencing, final IField referenced, final IProgressMonitor monitor) throws JavaModelException {
	ModifierKeyword keyword= ModifierKeyword.PUBLIC_KEYWORD;
	final ICompilationUnit referencedUnit= referenced.getCompilationUnit();
	if (referenced.getDeclaringType().equals(referencing))
		keyword= ModifierKeyword.PRIVATE_KEYWORD;
	else {
		final ITypeHierarchy hierarchy= getTypeHierarchy(referencing, new SubProgressMonitor(monitor, 1));
		final IType[] types= hierarchy.getSupertypes(referencing);
		IType superType= null;
		for (int index= 0; index < types.length; index++) {
			superType= types[index];
			if (superType.equals(referenced.getDeclaringType())) {
				keyword= ModifierKeyword.PROTECTED_KEYWORD;
				return keyword;
			}
		}
	}
	final ICompilationUnit typeUnit= referencing.getCompilationUnit();
	if (referencedUnit != null && referencedUnit.equals(typeUnit))
		keyword= ModifierKeyword.PRIVATE_KEYWORD;
	else if (referencedUnit != null && typeUnit != null && referencedUnit.getParent().equals(typeUnit.getParent()))
		keyword= null;
	return keyword;
}
 
Example 9
public Object[] getChildren(Object parent) {
	if (parent instanceof IParent) {
		IParent c= (IParent) parent;
		try {
			return filter(c.getChildren());
		} catch (JavaModelException x) {
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=38341
			// don't log NotExist exceptions as this is a valid case
			// since we might have been posted and the element
			// removed in the meantime.
			if (JavaPlugin.isDebug() || !x.isDoesNotExist())
				JavaPlugin.log(x);
		}
	}
	return NO_CHILDREN;
}
 
Example 10
@Test
public void testGenerateToStringDisabled_enum() throws JavaModelException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("A.java", "package p;\r\n" +
			"\r\n" +
			"public enum A {\r\n" +
			"	MONDAY,\r\n" +
			"	TUESDAY;\r\n" +
			"	private String name;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	CodeActionParams params = CodeActionUtil.constructCodeActionParams(unit, "String name");
	List<Either<Command, CodeAction>> codeActions = server.codeAction(params).join();
	Assert.assertNotNull(codeActions);
	Assert.assertFalse("The operation is not applicable to enums", CodeActionHandlerTest.containsKind(codeActions, JavaCodeActionKind.SOURCE_GENERATE_TO_STRING));
}
 
Example 11
/**
 * Configure this type hierarchy by computing the supertypes only.
 */
protected void buildSupertypes() {
	IType focusType = getType();
	if (focusType == null)
		return;
	// get generic type from focus type
	IGenericType type;
	try {
		type = (IGenericType) ((JavaElement) focusType).getElementInfo();
	} catch (JavaModelException e) {
		// if the focus type is not present, or if cannot get workbench path
		// we cannot create the hierarchy
		return;
	}
	//NB: no need to set focus type on hierarchy resolver since no other type is injected
	//    in the hierarchy resolver, thus there is no need to check that a type is
	//    a sub or super type of the focus type.
	this.hierarchyResolver.resolve(type);

	// Add focus if not already in (case of a type with no explicit super type)
	if (!this.hierarchy.contains(focusType)) {
		this.hierarchy.addRootClass(focusType);
	}
}
 
Example 12
private List<SearchMatch> getImplicitConstructorReferencesInClassCreations(WorkingCopyOwner owner, IProgressMonitor pm, RefactoringStatus status) throws JavaModelException {
	//XXX workaround for jdt core bug 23112
	SearchPattern pattern= SearchPattern.createPattern(fType, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
	IJavaSearchScope scope= RefactoringScopeFactory.create(fType);
	SearchResultGroup[] refs= RefactoringSearchEngine.search(pattern, owner, scope, pm, status);
	List<SearchMatch> result= new ArrayList<SearchMatch>();
	for (int i= 0; i < refs.length; i++) {
		SearchResultGroup group= refs[i];
		ICompilationUnit cu= group.getCompilationUnit();
		if (cu == null)
			continue;
		CompilationUnit cuNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(cu, false);
		SearchMatch[] results= group.getSearchResults();
		for (int j= 0; j < results.length; j++) {
			SearchMatch searchResult= results[j];
			ASTNode node= ASTNodeSearchUtil.getAstNode(searchResult, cuNode);
			if (isImplicitConstructorReferenceNodeInClassCreations(node))
				result.add(searchResult);
		}
	}
	return result;
}
 
Example 13
public static Object[] createPackageListInput(ICompilationUnit cu, String elementNameMatch){
	try{
		IJavaProject project= cu.getJavaProject();
		IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
		List<IPackageFragment> result= new ArrayList<IPackageFragment>();
		HashMap<String, Object> entered =new HashMap<String, Object>();
		for (int i= 0; i < roots.length; i++){
			if (canAddPackageRoot(roots[i])){
				getValidPackages(roots[i], result, entered, elementNameMatch);
			}
		}
		return result.toArray();
	} catch (JavaModelException e){
		JavaPlugin.log(e);
		return new Object[0];
	}
}
 
Example 14
Source Project: xtext-eclipse   Source File: JdtTypeProvider.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private JvmType findObjectTypeInJavaProject(/* @NonNull */ String signature, /* @NonNull */ URI resourceURI, boolean traverseNestedTypes)
		throws JavaModelException {
	IType type = findObjectTypeInJavaProject(resourceURI);
	if (type != null) {
		try {
			return createResourceAndFindType(resourceURI, type, signature, traverseNestedTypes);
		} catch (IOException ioe) {
			return null;
		} catch (WrappedException wrapped) {
			if (wrapped.getCause() instanceof IOException) {
				return null;
			}
			throw wrapped;
		}
	}
	return null;
}
 
Example 15
private void createAbstractMethod(final IMethod sourceMethod, final CompilationUnitRewrite sourceRewriter, final CompilationUnit declaringCuNode, final AbstractTypeDeclaration destination, final TypeVariableMaplet[] mapping, final CompilationUnitRewrite targetRewrite, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException {
	final MethodDeclaration oldMethod= ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, declaringCuNode);
	if (JavaModelUtil.is50OrHigher(sourceMethod.getJavaProject()) && (fSettings.overrideAnnotation || JavaCore.ERROR.equals(sourceMethod.getJavaProject().getOption(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION, true)))) {
		final MarkerAnnotation annotation= sourceRewriter.getAST().newMarkerAnnotation();
		annotation.setTypeName(sourceRewriter.getAST().newSimpleName("Override")); //$NON-NLS-1$
		sourceRewriter.getASTRewrite().getListRewrite(oldMethod, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(annotation, sourceRewriter.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_override_annotation, SET_PULL_UP));
	}
	final MethodDeclaration newMethod= targetRewrite.getAST().newMethodDeclaration();
	newMethod.setBody(null);
	newMethod.setConstructor(false);
	copyExtraDimensions(oldMethod, newMethod);
	newMethod.setJavadoc(null);
	int modifiers= getModifiersWithUpdatedVisibility(sourceMethod, Modifier.ABSTRACT | JdtFlags.clearFlag(Modifier.NATIVE | Modifier.FINAL, sourceMethod.getFlags()), adjustments, monitor, false, status);
	if (oldMethod.isVarargs())
		modifiers&= ~Flags.AccVarargs;
	newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(targetRewrite.getAST(), modifiers));
	newMethod.setName(((SimpleName) ASTNode.copySubtree(targetRewrite.getAST(), oldMethod.getName())));
	copyReturnType(targetRewrite.getASTRewrite(), getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping);
	copyParameters(targetRewrite.getASTRewrite(), getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping);
	copyThrownExceptions(oldMethod, newMethod);
	copyTypeParameters(oldMethod, newMethod);
	ImportRewriteContext context= new ContextSensitiveImportRewriteContext(destination, targetRewrite.getImportRewrite());
	ImportRewriteUtil.addImports(targetRewrite, context, oldMethod, new HashMap<Name, String>(), new HashMap<Name, String>(), false);
	targetRewrite.getASTRewrite().getListRewrite(destination, destination.getBodyDeclarationsProperty()).insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, destination.bodyDeclarations()), targetRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_abstract_method, SET_PULL_UP));
}
 
Example 16
protected static List<ASTNode> getDeclarationNodes(final CompilationUnit cuNode, final List<IMember> members) throws JavaModelException {
	final List<ASTNode> result= new ArrayList<ASTNode>(members.size());
	for (final Iterator<IMember> iterator= members.iterator(); iterator.hasNext();) {
		final IMember member= iterator.next();
		ASTNode node= null;
		if (member instanceof IField) {
			if (Flags.isEnum(member.getFlags()))
				node= ASTNodeSearchUtil.getEnumConstantDeclaration((IField) member, cuNode);
			else
				node= ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) member, cuNode);
		} else if (member instanceof IType)
			node= ASTNodeSearchUtil.getAbstractTypeDeclarationNode((IType) member, cuNode);
		else if (member instanceof IMethod)
			node= ASTNodeSearchUtil.getMethodDeclarationNode((IMethod) member, cuNode);
		if (node != null)
			result.add(node);
	}
	return result;
}
 
Example 17
@Override
protected boolean canHandle(IStructuredSelection selection) {
	if (selection.size() != 1)
		return false;

	try {
		Object element= selection.getFirstElement();
		if (element instanceof IJavaProject) {
			return ClasspathModifier.isSourceFolder((IJavaProject)element);
		} else if (element instanceof IPackageFragmentRoot) {
			IPackageFragmentRoot packageFragmentRoot= ((IPackageFragmentRoot) element);
			if (packageFragmentRoot.getKind() != IPackageFragmentRoot.K_SOURCE)
				return false;

			return packageFragmentRoot.getJavaProject() != null;
		}
	} catch (JavaModelException e) {
	}
	return false;
}
 
Example 18
Source Project: eclipse.jdt.ls   Source File: ReorgPolicyFactory.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean canEnable() throws JavaModelException {
	if (!super.canEnable() || fJavaElements.length == 0) {
		return false;
	}

	for (int i= 0; i < fJavaElements.length; i++) {
		if (fJavaElements[i] instanceof IMember) {
			IMember member= (IMember) fJavaElements[i];
			// we can copy some binary members, but not all
			if (member.isBinary() && member.getSourceRange() == null) {
				return false;
			}
		}
	}

	return true;
}
 
Example 19
/**
 * @see IJavaProject
 */
public IPath getOutputLocation() throws JavaModelException {
	// Do not create marker while getting output location
	JavaModelManager.PerProjectInfo perProjectInfo = getPerProjectInfo();
	IPath outputLocation = perProjectInfo.outputLocation;
	if (outputLocation != null) return outputLocation;

	// force to read classpath - will position output location as well
	getRawClasspath();

	outputLocation = perProjectInfo.outputLocation;
	if (outputLocation == null) {
		return defaultOutputLocation();
	}
	return outputLocation;
}
 
Example 20
private static void addImports(CompilationUnit root, ICompilationUnit unit, String[] favourites, ImportRewrite importRewrite, AST ast, ASTRewrite astRewrite, SimpleName node, boolean isMethod) throws JavaModelException {
	String name = node.getIdentifier();
	String[] imports = SimilarElementsRequestor.getStaticImportFavorites(unit, name, isMethod, favourites);
	if (imports.length > 1) {
		// See https://github.com/redhat-developer/vscode-java/issues/1472
		return;
	}
	for (int i = 0; i < imports.length; i++) {
		String curr = imports[i];
		String qualifiedTypeName = Signature.getQualifier(curr);
		String res = importRewrite.addStaticImport(qualifiedTypeName, name, isMethod, new ContextSensitiveImportRewriteContext(root, node.getStartPosition(), importRewrite));
		int dot = res.lastIndexOf('.');
		if (dot != -1) {
			String usedTypeName = importRewrite.addImport(qualifiedTypeName);
			Name newName = ast.newQualifiedName(ast.newName(usedTypeName), ast.newSimpleName(name));
			astRewrite.replace(node, newName, null);
		}
	}
}
 
Example 21
/**
 * Finds every type in the project whose simple name matches
 * the prefix, informing the requestor of each hit. The requestor
 * is polled for cancellation at regular intervals.
 *
 * <p>The <code>partialMatch</code> argument indicates partial matches
 * should be considered.
 */
private void findAllTypes(String prefix, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
	int count= this.packageFragmentRoots.length;
	for (int i= 0; i < count; i++) {
		if (requestor.isCanceled())
			return;
		IPackageFragmentRoot root= this.packageFragmentRoots[i];
		IJavaElement[] packages= null;
		try {
			packages= root.getChildren();
		} catch (JavaModelException npe) {
			continue; // the root is not present, continue;
		}
		if (packages != null) {
			for (int j= 0, packageCount= packages.length; j < packageCount; j++) {
				if (requestor.isCanceled())
					return;
				seekTypes(prefix, (IPackageFragment) packages[j], partialMatch, acceptFlags, requestor);
			}
		}
	}
}
 
Example 22
public GenerateConstructorUsingFieldsSelectionDialog(Shell parent, ILabelProvider labelProvider, GenerateConstructorUsingFieldsContentProvider contentProvider, CompilationUnitEditor editor, IType type, IMethodBinding[] superConstructors) throws JavaModelException {
	super(parent, labelProvider, contentProvider, editor, type, true);
	fTreeViewerAdapter= new GenerateConstructorUsingFieldsTreeViewerAdapter();

	fSuperConstructors= superConstructors;

	IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings();
	fGenConstructorSettings= dialogSettings.getSection(SETTINGS_SECTION);
	if (fGenConstructorSettings == null) {
		fGenConstructorSettings= dialogSettings.addNewSection(SETTINGS_SECTION);
		fGenConstructorSettings.put(OMIT_SUPER, false);
	}

	final boolean isEnum= type.isEnum();
	fOmitSuper= fGenConstructorSettings.getBoolean(OMIT_SUPER) || isEnum;
	if (isEnum)
		setVisibility(Modifier.PRIVATE);
}
 
Example 23
@Override
public boolean isImplementedInSupertype(final IType objectClass, final String interfaceName)
        throws JavaModelException {

    String simpleName = getSimpleInterfaceName(interfaceName);

    ITypeHierarchy typeHierarchy = objectClass.newSupertypeHierarchy(null);
    IType[] interfaces = typeHierarchy.getAllInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
        if (interfaces[i].getElementName().equals(simpleName)) {
            IType in = interfaces[i];
            IType[] types = typeHierarchy.getImplementingClasses(in);
            for (int j = 0; j < types.length; j++) {
                if (!types[j].getFullyQualifiedName().equals(objectClass.getFullyQualifiedName())) {
                    return true;
                }
            }
            break;
        }
    }
    return false;
}
 
Example 24
@Override
public int category(Object element) {
	if (element instanceof IType) {
		IType type= (IType) element;
		try {
			if (type.isAnonymous() || type.isLambda()) {
				return ANONYM;
			}
		} catch (JavaModelException e1) {
			if (type.getElementName().length() == 0) {
				return ANONYM;
			}
		}
		try {
			int flags= getTypeFlags(type);
			if (Flags.isInterface(flags)) {
				return INTERFACE;
			} else {
				return CLASS;
			}
		} catch (JavaModelException e) {
			// ignore
		}
	}
	return OTHER;
}
 
Example 25
private void collectMatches(Set<Match> matches, IJavaElement element) {
	//TODO: copied from JavaSearchResult:
	Match[] m= getMatches(element);
	if (m.length != 0) {
		for (int i= 0; i < m.length; i++) {
			matches.add(m[i]);
		}
	}
	if (element instanceof IParent) {
		IParent parent= (IParent) element;
		try {
			IJavaElement[] children= parent.getChildren();
			for (int i= 0; i < children.length; i++) {
				collectMatches(matches, children[i]);
			}
		} catch (JavaModelException e) {
			// we will not be tracking these results
		}
	}
}
 
Example 26
Source Project: eclipse.jdt.ls   Source File: ReorgPolicyFactory.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm) throws JavaModelException {
	IPackageFragmentRoot[] roots= getPackageFragmentRoots();
	pm.beginTask("", roots.length); //$NON-NLS-1$
	CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move_source_folder);
	composite.markAsSynthetic();
	IJavaProject destination= getDestinationJavaProject();
	for (int i= 0; i < roots.length; i++) {
		if (destination == null) {
			composite.add(new MovePackageFragmentRootChange(roots[i], (IContainer) getResourceDestination(), null));
		} else {
			composite.add(createChange(roots[i], destination));
		}
		pm.worked(1);
	}
	pm.done();
	return composite;
}
 
Example 27
public JavaLaunchCodeMining(IJavaElement element, String label, String mode, IDocument document,
		ICodeMiningProvider provider) throws JavaModelException, BadLocationException {
	super(element, document, provider, e -> {
		JavaApplicationLaunchShortcut shortcut = new JavaApplicationLaunchShortcut();
		shortcut.launch(new StructuredSelection(element), mode);
	});
	super.setLabel(label);
}
 
Example 28
public void update() {
	boolean enabled= false;
	ISourceReference ref= getSourceReference();
	if (ref != null) {
		ISourceRange range;
		try {
			range= ref.getSourceRange();
			enabled= range != null && range.getLength() > 0;
		} catch (JavaModelException e) {
			// enabled= false;
		}
	}
	setEnabled(enabled);
}
 
Example 29
public void open() {
	try {
		String returnTypeSignature= fMethod.getReturnType();
		int kind= Signature.getTypeSignatureKind(returnTypeSignature);
		if (kind == Signature.ARRAY_TYPE_SIGNATURE) {
			returnTypeSignature= Signature.getElementType(returnTypeSignature);
		} else if (kind == Signature.CLASS_TYPE_SIGNATURE) {
			returnTypeSignature= Signature.getTypeErasure(returnTypeSignature);
		}
		String returnType= Signature.toString(returnTypeSignature);

		String[][] resolvedType= fMethod.getDeclaringType().resolveType(returnType);
		if (resolvedType == null || resolvedType.length == 0) {
			openMethodAndShowErrorInStatusLine();
			return;
		}

		String typeName= JavaModelUtil.concatenateName(resolvedType[0][0], resolvedType[0][1]);
		IType type= fMethod.getJavaProject().findType(typeName, (IProgressMonitor)null);
		if (type != null) {
			fOpenAction.run(new StructuredSelection(type));
			return;
		}
		openMethodAndShowErrorInStatusLine();
	} catch (JavaModelException e) {
		JavaPlugin.log(e);
		return;
	}
}
 
Example 30
Source Project: sarl   Source File: Jdt2Ecore.java    License: Apache License 2.0 5 votes vote down vote up
/** Create a {@link TypeFinder} wrapper for the given Java project.
 *
 * <p>The wrapper invokes {@link IJavaProject#findType(String)} on the given project.
 *
 * @param project the project to wrap.
 * @return the type finder based on the given Java project.
 */
public TypeFinder toTypeFinder(final IJavaProject project) {
	return new TypeFinder() {
		@Override
		public IType findType(String typeName) throws JavaModelException {
			return project.findType(typeName);
		}
	};
}