Search in sources :

Example 16 with IJavaProject

use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.

the class NewDefiningMethodProposal method addNewParameters.

/* (non-Javadoc)
	 * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#addNewParameters(org.eclipse.jdt.core
	 * .dom.rewrite.ASTRewrite, java.util.List, java.util.List)
	 */
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params) throws CoreException {
    AST ast = rewrite.getAST();
    ImportRewrite importRewrite = getImportRewrite();
    ITypeBinding[] bindings = fMethod.getParameterTypes();
    IJavaProject project = getCompilationUnit().getJavaProject();
    String[][] paramNames = StubUtility.suggestArgumentNamesWithProposals(project, fParamNames);
    for (int i = 0; i < bindings.length; i++) {
        ITypeBinding curr = bindings[i];
        String[] proposedNames = paramNames[i];
        SingleVariableDeclaration newParam = ast.newSingleVariableDeclaration();
        newParam.setType(importRewrite.addImport(curr, ast));
        newParam.setName(ast.newSimpleName(proposedNames[0]));
        params.add(newParam);
        //$NON-NLS-1$
        String groupId = "arg_name_" + i;
        addLinkedPosition(rewrite.track(newParam.getName()), false, groupId);
        for (int k = 0; k < proposedNames.length; k++) {
            addLinkedPositionProposal(groupId, proposedNames[k], null);
        }
    }
}
Also used : AST(org.eclipse.jdt.core.dom.AST) IJavaProject(org.eclipse.jdt.core.IJavaProject) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding)

Example 17 with IJavaProject

use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.

the class NewMethodCorrectionProposal method evaluateParameterName.

private String evaluateParameterName(List<String> takenNames, Expression argNode, Type type, String key) {
    IJavaProject project = getCompilationUnit().getJavaProject();
    String[] names = StubUtility.getVariableNameSuggestions(NamingConventions.VK_PARAMETER, project, type, argNode, takenNames);
    for (int i = 0; i < names.length; i++) {
        addLinkedPositionProposal(key, names[i], null);
    }
    String favourite = names[0];
    takenNames.add(favourite);
    return favourite;
}
Also used : IJavaProject(org.eclipse.jdt.core.IJavaProject)

Example 18 with IJavaProject

use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.

the class CheCompilationUnitResolver method resolve.

public static CompilationUnitDeclaration resolve(org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit, IJavaProject javaProject, List classpaths, NodeSearcher nodeSearcher, Map options, WorkingCopyOwner owner, int flags, IProgressMonitor monitor) throws JavaModelException {
    CompilationUnitDeclaration unit = null;
    INameEnvironmentWithProgress environment = null;
    CancelableProblemFactory problemFactory = null;
    CheCompilationUnitResolver resolver = null;
    try {
        if (javaProject == null) {
            FileSystem.Classpath[] allEntries = new FileSystem.Classpath[classpaths.size()];
            classpaths.toArray(allEntries);
            environment = new NameEnvironmentWithProgress(allEntries, null, monitor);
        } else {
            environment = new CancelableNameEnvironment((JavaProject) javaProject, owner, monitor);
        }
        problemFactory = new CancelableProblemFactory(monitor);
        CompilerOptions compilerOptions = CompilationUnitResolver.getCompilerOptions(options, (flags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
        boolean ignoreMethodBodies = (flags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0;
        compilerOptions.ignoreMethodBodies = ignoreMethodBodies;
        resolver = new CheCompilationUnitResolver(environment, CompilationUnitResolver.getHandlingPolicy(), compilerOptions, CompilationUnitResolver.getRequestor(), problemFactory, monitor, javaProject != null);
        boolean analyzeAndGenerateCode = !ignoreMethodBodies;
        unit = resolver.resolve(// no existing compilation unit declaration
        null, sourceUnit, nodeSearcher, // method verification
        true, // analyze code
        analyzeAndGenerateCode, // generate code
        analyzeAndGenerateCode);
        if (resolver.hasCompilationAborted) {
            // the bindings could not be resolved due to missing types in name environment
            // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=86541
            CompilationUnitDeclaration unitDeclaration = CompilationUnitResolver.parse(sourceUnit, nodeSearcher, options, flags);
            if (unit != null) {
                final int problemCount = unit.compilationResult.problemCount;
                if (problemCount != 0) {
                    unitDeclaration.compilationResult.problems = new CategorizedProblem[problemCount];
                    System.arraycopy(unit.compilationResult.problems, 0, unitDeclaration.compilationResult.problems, 0, problemCount);
                    unitDeclaration.compilationResult.problemCount = problemCount;
                }
            } else if (resolver.abortProblem != null) {
                unitDeclaration.compilationResult.problemCount = 1;
                unitDeclaration.compilationResult.problems = new CategorizedProblem[] { resolver.abortProblem };
            }
            return unitDeclaration;
        }
        if (NameLookup.VERBOSE && environment instanceof CancelableNameEnvironment) {
            CancelableNameEnvironment cancelableNameEnvironment = (CancelableNameEnvironment) environment;
            //$NON-NLS-1$ //$NON-NLS-2$
            System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + cancelableNameEnvironment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms");
            //$NON-NLS-1$ //$NON-NLS-2$
            System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + cancelableNameEnvironment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms");
        }
        return unit;
    } finally {
        if (environment != null) {
            // don't hold a reference to this external object
            environment.setMonitor(null);
        }
        if (problemFactory != null) {
            // don't hold a reference to this external object
            problemFactory.monitor = null;
        }
    }
}
Also used : JavaProject(org.eclipse.jdt.internal.core.JavaProject) IJavaProject(org.eclipse.jdt.core.IJavaProject) INameEnvironmentWithProgress(org.eclipse.jdt.internal.core.INameEnvironmentWithProgress) INameEnvironmentWithProgress(org.eclipse.jdt.internal.core.INameEnvironmentWithProgress) CategorizedProblem(org.eclipse.jdt.core.compiler.CategorizedProblem) CancelableProblemFactory(org.eclipse.jdt.internal.core.CancelableProblemFactory) CompilationUnitDeclaration(org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) CancelableNameEnvironment(org.eclipse.jdt.internal.core.CancelableNameEnvironment)

Example 19 with IJavaProject

use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.

the class IntroduceParameterObjectDescriptor method validateDescriptor.

/**
	 * {@inheritDoc}
	 */
public RefactoringStatus validateDescriptor() {
    RefactoringStatus result = super.validateDescriptor();
    if (!result.isOK())
        return result;
    if (fMethod == null) {
        //$NON-NLS-1$
        result.addFatalError("The method must not be null");
        return result;
    }
    IJavaProject javaProject = fMethod.getJavaProject();
    if (javaProject == null) {
        //$NON-NLS-1$
        result.addFatalError("Can not derive Java project from method");
        return result;
    }
    String sourceLevel = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
    String complianceLevel = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
    if (fParameters != null) {
        if (fParameters.length - 1 != fMethod.getNumberOfParameters()) {
            //$NON-NLS-1$
            result.addFatalError("The number of parameters does not match the number of parameters of the method");
        }
        boolean hasParameterObject = false;
        for (int i = 0; i < fParameters.length; i++) {
            Parameter parameter = fParameters[i];
            if (parameter.isCreateField()) {
                String fieldName = parameter.getFieldName();
                if (fieldName == null)
                    result.addError("The parameter " + parameter.getIndex() + " is marked for field creation but does not have a field" + //$NON-NLS-1$ //$NON-NLS-2$
                    " name");
                else {
                    result.merge(RefactoringStatus.create(JavaConventions.validateFieldName(fieldName, sourceLevel, complianceLevel)));
                }
            }
            if (parameter == PARAMETER_OBJECT) {
                if (hasParameterObject)
                    //$NON-NLS-1$
                    result.addError("Can not have more than one parameter object");
                else
                    hasParameterObject = true;
            }
        }
    }
    if (fClassName != null) {
        result.merge(RefactoringStatus.create(JavaConventions.validateIdentifier(fClassName, sourceLevel, complianceLevel)));
    }
    if (fParameterName != null) {
        result.merge(RefactoringStatus.create(JavaConventions.validateIdentifier(fParameterName, sourceLevel, complianceLevel)));
    }
    if (fPackageName != null && !"".equals(fPackageName)) {
        //$NON-NLS-1$
        result.merge(RefactoringStatus.create(JavaConventions.validatePackageName(fPackageName, sourceLevel, complianceLevel)));
    }
    return result;
}
Also used : IJavaProject(org.eclipse.jdt.core.IJavaProject) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus)

Example 20 with IJavaProject

use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.

the class ClasspathEntry method validateClasspathEntry.

//	/**
//	 * Returns a Java model status describing the problem related to this classpath entry if any,
//	 * a status object with code <code>IStatus.OK</code> if the entry is fine (that is, if the
//	 * given classpath entry denotes a valid element to be referenced onto a classpath).
//	 *
//	 * @param project the given java project
//	 * @param entry the given classpath entry
//	 * @param checkSourceAttachment a flag to determine if source attachment should be checked
//	 * @param referredByContainer flag indicating whether the given entry is referred by a classpath container
//	 * @return a java model status describing the problem related to this classpath entry if any, a status object with code <code>IStatus
// .OK</code> if the entry is fine
//	 */
//	public static IJavaModelStatus validateClasspathEntry(IJavaProject project, IClasspathEntry entry, boolean checkSourceAttachment,
// boolean referredByContainer){
//		if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
//			JavaModelManager.getJavaModelManager().removeFromInvalidArchiveCache(entry.getPath());
//		}
//		IJavaModelStatus status = validateClasspathEntry(project, entry, null, checkSourceAttachment, referredByContainer);
//		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=171136 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=300136
//		// Ignore class path errors from optional entries.
//		int statusCode = status.getCode();
//		if ( (statusCode == IJavaModelStatusConstants.INVALID_CLASSPATH ||
//				statusCode == IJavaModelStatusConstants.CP_CONTAINER_PATH_UNBOUND ||
//				statusCode == IJavaModelStatusConstants.CP_VARIABLE_PATH_UNBOUND ||
//				statusCode == IJavaModelStatusConstants.INVALID_PATH) &&
//				((ClasspathEntry) entry).isOptional())
//			return JavaModelStatus.VERIFIED_OK;
//		return status;
//	}
private static IJavaModelStatus validateClasspathEntry(IJavaProject project, IClasspathEntry entry, IClasspathContainer entryContainer, boolean checkSourceAttachment, boolean referredByContainer) {
    IPath path = entry.getPath();
    // Build some common strings for status message
    String projectName = project.getElementName();
    String entryPathMsg = projectName.equals(path.segment(0)) ? path.removeFirstSegments(1).makeRelative().toString() : path.toString();
    switch(entry.getEntryKind()) {
        // container entry check
        case IClasspathEntry.CPE_CONTAINER:
            if (path.segmentCount() >= 1) {
                try {
                    IJavaModelStatus status = null;
                    // Validate extra attributes
                    IClasspathAttribute[] extraAttributes = entry.getExtraAttributes();
                    if (extraAttributes != null) {
                        int length = extraAttributes.length;
                        HashSet set = new HashSet(length);
                        for (int i = 0; i < length; i++) {
                            String attName = extraAttributes[i].getName();
                            if (!set.add(attName)) {
                                status = new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION, Messages.bind(Messages.classpath_duplicateEntryExtraAttribute, new String[] { attName, entryPathMsg, projectName }));
                                break;
                            }
                        }
                    }
                    IClasspathContainer container = JavaModelManager.getJavaModelManager().getClasspathContainer(path, project);
                    // container retrieval is performing validation check on container entry kinds.
                    if (container == null) {
                        if (status != null)
                            return status;
                        return new JavaModelStatus(IJavaModelStatusConstants.CP_CONTAINER_PATH_UNBOUND, project, path);
                    } else if (container == JavaModelManager.CONTAINER_INITIALIZATION_IN_PROGRESS) {
                        // don't create a marker if initialization is in progress (case of cp initialization batching)
                        return JavaModelStatus.VERIFIED_OK;
                    }
                    IClasspathEntry[] containerEntries = container.getClasspathEntries();
                    if (containerEntries != null) {
                        for (int i = 0, length = containerEntries.length; i < length; i++) {
                            IClasspathEntry containerEntry = containerEntries[i];
                            int kind = containerEntry == null ? 0 : containerEntry.getEntryKind();
                            if (containerEntry == null || kind == IClasspathEntry.CPE_SOURCE || kind == IClasspathEntry.CPE_VARIABLE || kind == IClasspathEntry.CPE_CONTAINER) {
                                return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CP_CONTAINER_ENTRY, project, path);
                            }
                            IJavaModelStatus containerEntryStatus = validateClasspathEntry(project, containerEntry, container, checkSourceAttachment, true);
                            if (!containerEntryStatus.isOK()) {
                                return containerEntryStatus;
                            }
                        }
                    }
                } catch (JavaModelException e) {
                    return new JavaModelStatus(e);
                }
            } else {
                return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_illegalContainerPath, new String[] { entryPathMsg, projectName }));
            }
            break;
        // variable entry check
        case IClasspathEntry.CPE_VARIABLE:
            if (path.segmentCount() >= 1) {
                try {
                    entry = JavaCore.getResolvedClasspathEntry(entry);
                } catch (AssertionFailedException e) {
                    // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=55992
                    return new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage());
                }
                if (entry == null) {
                    return new JavaModelStatus(IJavaModelStatusConstants.CP_VARIABLE_PATH_UNBOUND, project, path);
                }
                // get validation status
                IJavaModelStatus status = validateClasspathEntry(project, entry, null, checkSourceAttachment, false);
                if (!status.isOK())
                    return status;
                // return deprecation status if any
                String variableName = path.segment(0);
                String deprecatedMessage = JavaCore.getClasspathVariableDeprecationMessage(variableName);
                if (deprecatedMessage != null) {
                    return new JavaModelStatus(IStatus.WARNING, IJavaModelStatusConstants.DEPRECATED_VARIABLE, project, path, deprecatedMessage);
                }
                return status;
            } else {
                return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_illegalVariablePath, new String[] { entryPathMsg, projectName }));
            }
        // library entry check
        case IClasspathEntry.CPE_LIBRARY:
            path = ClasspathEntry.resolveDotDot(project.getProject().getLocation(), path);
            // do not validate entries from Class-Path: in manifest
            // (these entries are considered optional since the user cannot act on them)
            // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=252392
            String containerInfo = null;
            if (entryContainer != null) {
                if (entryContainer instanceof UserLibraryClasspathContainer) {
                    containerInfo = Messages.bind(Messages.classpath_userLibraryInfo, new String[] { entryContainer.getDescription() });
                } else {
                    containerInfo = Messages.bind(Messages.classpath_containerInfo, new String[] { entryContainer.getDescription() });
                }
            }
            IJavaModelStatus status = validateLibraryEntry(path, project, containerInfo, checkSourceAttachment ? entry.getSourceAttachmentPath() : null, entryPathMsg);
            // https://bugs.eclipse.org/bugs/show_bug.cgi?id=171136, ignore class path errors from optional entries
            if (status.getCode() == IJavaModelStatusConstants.INVALID_CLASSPATH && ((ClasspathEntry) entry).isOptional())
                status = JavaModelStatus.VERIFIED_OK;
            if (!status.isOK())
                return status;
            break;
        // project entry check
        case IClasspathEntry.CPE_PROJECT:
            if (path.isAbsolute() && path.segmentCount() == 1) {
                IProject prereqProjectRsc = workspaceRoot.getProject(path.segment(0));
                IJavaProject prereqProject = JavaCore.create(prereqProjectRsc);
                try {
                    if (!prereqProjectRsc.exists() || !prereqProjectRsc.hasNature(JavaCore.NATURE_ID)) {
                        return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_unboundProject, new String[] { path.segment(0), projectName }));
                    }
                    if (!prereqProjectRsc.isOpen()) {
                        return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_closedProject, new String[] { path.segment(0) }));
                    }
                    if (!JavaCore.IGNORE.equals(project.getOption(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL, true))) {
                        long projectTargetJDK = CompilerOptions.versionToJdkLevel(project.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true));
                        long prereqProjectTargetJDK = CompilerOptions.versionToJdkLevel(prereqProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true));
                        if (prereqProjectTargetJDK > projectTargetJDK) {
                            return new JavaModelStatus(IJavaModelStatusConstants.INCOMPATIBLE_JDK_LEVEL, project, path, Messages.bind(Messages.classpath_incompatibleLibraryJDKLevel, new String[] { project.getElementName(), CompilerOptions.versionFromJdkLevel(projectTargetJDK), path.makeRelative().toString(), CompilerOptions.versionFromJdkLevel(prereqProjectTargetJDK) }));
                        }
                    }
                } catch (CoreException e) {
                    return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_unboundProject, new String[] { path.segment(0), projectName }));
                }
            } else {
                return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_illegalProjectPath, new String[] { path.toString(), projectName }));
            }
            break;
        // project source folder
        case IClasspathEntry.CPE_SOURCE:
            if (((entry.getInclusionPatterns() != null && entry.getInclusionPatterns().length > 0) || (entry.getExclusionPatterns() != null && entry.getExclusionPatterns().length > 0)) && JavaCore.DISABLED.equals(project.getOption(JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, true))) {
                return new JavaModelStatus(IJavaModelStatusConstants.DISABLED_CP_EXCLUSION_PATTERNS, project, path);
            }
            if (entry.getOutputLocation() != null && JavaCore.DISABLED.equals(project.getOption(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, true))) {
                return new JavaModelStatus(IJavaModelStatusConstants.DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS, project, path);
            }
            if (path.isAbsolute() && !path.isEmpty()) {
                IPath projectPath = project.getProject().getFullPath();
                if (!projectPath.isPrefixOf(path) || JavaModel.getTarget(path, true) == null) {
                    return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_unboundSourceFolder, new String[] { entryPathMsg, projectName }));
                }
            } else {
                return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_illegalSourceFolderPath, new String[] { entryPathMsg, projectName }));
            }
            break;
    }
    // Validate extra attributes
    IClasspathAttribute[] extraAttributes = entry.getExtraAttributes();
    if (extraAttributes != null) {
        int length = extraAttributes.length;
        HashSet set = new HashSet(length);
        for (int i = 0; i < length; i++) {
            String attName = extraAttributes[i].getName();
            if (!set.add(attName)) {
                return new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION, Messages.bind(Messages.classpath_duplicateEntryExtraAttribute, new String[] { attName, entryPathMsg, projectName }));
            }
        }
    }
    return JavaModelStatus.VERIFIED_OK;
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) IPath(org.eclipse.core.runtime.IPath) IClasspathEntry(org.eclipse.jdt.core.IClasspathEntry) IJavaModelStatus(org.eclipse.jdt.core.IJavaModelStatus) IProject(org.eclipse.core.resources.IProject) IClasspathAttribute(org.eclipse.jdt.core.IClasspathAttribute) IJavaProject(org.eclipse.jdt.core.IJavaProject) CoreException(org.eclipse.core.runtime.CoreException) IJavaModelStatus(org.eclipse.jdt.core.IJavaModelStatus) IClasspathContainer(org.eclipse.jdt.core.IClasspathContainer) HashSet(java.util.HashSet)

Aggregations

IJavaProject (org.eclipse.jdt.core.IJavaProject)733 IProject (org.eclipse.core.resources.IProject)177 IFile (org.eclipse.core.resources.IFile)149 Test (org.junit.Test)142 CoreException (org.eclipse.core.runtime.CoreException)125 JavaModelException (org.eclipse.jdt.core.JavaModelException)124 IClasspathEntry (org.eclipse.jdt.core.IClasspathEntry)122 IPath (org.eclipse.core.runtime.IPath)110 IPackageFragmentRoot (org.eclipse.jdt.core.IPackageFragmentRoot)102 ArrayList (java.util.ArrayList)87 IFolder (org.eclipse.core.resources.IFolder)78 IResource (org.eclipse.core.resources.IResource)75 IJavaElement (org.eclipse.jdt.core.IJavaElement)62 IType (org.eclipse.jdt.core.IType)62 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)60 Path (org.eclipse.core.runtime.Path)57 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)55 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)41 StringInputStream (org.eclipse.xtext.util.StringInputStream)39 HashMap (java.util.HashMap)38