Example usage for org.eclipse.jdt.core IJavaProject exists

List of usage examples for org.eclipse.jdt.core IJavaProject exists

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject exists.

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

Usage

From source file:org.jetbrains.kotlin.core.builder.KotlinPsiManager.java

License:Apache License

public boolean isKotlinSourceFile(@NotNull IResource resource, @NotNull IJavaProject javaProject)
        throws JavaModelException {
    if (!(resource instanceof IFile)
            || !JetFileType.INSTANCE.getDefaultExtension().equals(resource.getFileExtension())) {
        return false;
    }/*w w w. j  av a 2 s  . c  om*/

    if (!javaProject.exists()) {
        return false;
    }

    IClasspathEntry[] classpathEntries = javaProject.getRawClasspath();
    String resourceRoot = resource.getFullPath().segment(1);
    for (IClasspathEntry classpathEntry : classpathEntries) {
        if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            if (resourceRoot.equals(classpathEntry.getPath().segment(1))) {
                return true;
            }
        }
    }

    return false;
}

From source file:org.jnario.spec.ui.wizards.NewSpecWizardPageOne.java

License:Open Source License

/**
 * The method is called when the container has changed to validate if the project
 * is suited for the JUnit test class. Clients can override to modify or remove that validation.
 *
 * @return the status of the validation//from  w  w  w .  ja v  a2  s  .  c  om
 */
protected IStatus validateIfJUnitProject() {
    JUnitStatus status = new JUnitStatus();
    IPackageFragmentRoot root = getPackageFragmentRoot();
    if (root != null) {
        try {
            IJavaProject project = root.getJavaProject();
            if (project.exists()) {
                if (!JUnitStubUtility.is50OrHigher(project)) {
                    status.setError(WizardMessages.NewTestCaseWizardPageOne_error_java5required);
                    return status;
                }
                if (project.findType(JUnitCorePlugin.JUNIT4_ANNOTATION_NAME) == null) {
                    status.setWarning(WizardMessages.NewTestCaseWizardPageOne__error_junit4NotOnbuildpath);
                    return status;
                }
            }
        } catch (JavaModelException e) {
        }
    }
    return status;
}

From source file:org.key_project.sed.key.example.ui.test.testcase.swtbot.SWTBotSEDExampleNewWizardTest.java

License:Open Source License

/**
 * Tests something in the example project.
 * @param projectName The example project name.
 * @param steps The test steps to execute.
 * @throws Exception Occurred Exception.
 *//*from   ww w. j  ava 2 s  .  com*/
protected void doExampleTest(String projectName, IExampleTestSteps steps) throws Exception {
    IPerspectiveDescriptor originalPerspective = TestUtilsUtil.getActivePerspective();
    try {
        SWTWorkbenchBot bot = new SWTWorkbenchBot();
        // Open Java perspective
        TestUtilsUtil.openJavaPerspective();
        // Open new example wizard
        TestUtilsUtil.menuClick(bot, "File", "New", "Example...");
        SWTBotShell shell = bot.shell("New Example");
        //  Open Banking Example wizard
        TestUtilsUtil.selectInTree(shell.bot().tree(), "Symbolic Execution Debugger (SED)", "SED Examples");
        TestUtilsUtil.clickDirectly(shell.bot(), "Next >");
        // Define project name
        SWTBotText text = shell.bot().text(0);
        text.setText(projectName);
        // Finish wizard
        TestUtilsUtil.clickDirectly(shell.bot(), "Finish");
        shell.bot().waitUntil(Conditions.shellCloses(shell));
        // Test created project
        IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
        assertTrue(project.exists());
        assertTrue(project.isOpen());
        IJavaProject javaProject = JavaCore.create(project);
        assertNotNull(javaProject);
        assertTrue(javaProject.exists());
        // Unify line breaks
        TestUtilsUtil.unifyLineBreaks(project, "java");
        // Test opened editor
        SWTBotEditor editor = bot.activeEditor();
        assertEquals(project.getFile(new Path("Readme.txt")),
                editor.getReference().getEditorInput().getAdapter(IFile.class));
        editor.close();
        // Do test
        steps.doTest(javaProject);
    } finally {
        // Restore perspective
        TestUtilsUtil.openPerspective(originalPerspective);
    }
}

From source file:org.key_project.sed.key.ui.dialogs.AddKeYWatchpointDialog.java

License:Open Source License

/**
 * <p>/*w ww .ja v a 2  s. c  o  m*/
 * Opens the dialog to select a Java type ({@link IType}).
 * </p>
 * <p>
 * The implementation is oriented at {@link JavaMainTab#handleSearchButtonSelected()}.
 * </p>
 */
public void browseType() {
    try {
        IJavaProject selectedProject = getJavaProject();
        IJavaElement[] elements;
        if (selectedProject != null && selectedProject.exists()) {
            elements = new IJavaElement[] { selectedProject };
        } else {
            elements = JDTUtil.getAllJavaProjects();
        }
        if (elements == null) {
            elements = new IJavaElement[] {};
        }
        IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(elements, IJavaSearchScope.SOURCES
                | IJavaSearchScope.REFERENCED_PROJECTS | IJavaSearchScope.APPLICATION_LIBRARIES);
        FilteredTypesSelectionDialog resourceSelectionDialog = new FilteredTypesSelectionDialog(
                WorkbenchUtil.getActiveShell(), false, null, searchScope,
                IJavaSearchConstants.CLASS_AND_INTERFACE);
        resourceSelectionDialog.setInitialPattern(typeText.getText());
        resourceSelectionDialog.setTitle("Select class for KeY Watchpoint");
        if (resourceSelectionDialog.open() == FilteredTypesSelectionDialog.OK) {
            Object[] results = resourceSelectionDialog.getResult();
            if (results != null && results.length >= 1 && results[0] instanceof IType) {
                IType type = (IType) results[0];
                projectName = type.getJavaProject().getElementName();
                typeText.setText(type.getFullyQualifiedName());
            }
        }
    } catch (Exception e) {
        LogUtil.getLogger().logError(e);
        LogUtil.getLogger().openErrorDialog(getShell(), e);
    }
}

From source file:org.key_project.sed.key.ui.launch.MainLaunchConfigurationComposite.java

License:Open Source License

/**
 * <p>//from ww w .j a  va 2s .  c  o m
 * Opens the dialog to select a Java type ({@link IType}).
 * </p>
 * <p>
 * The implementation is oriented at {@link JavaMainTab#handleSearchButtonSelected()}.
 * </p>
 */
public void browseType() {
    try {
        // Search all Java types
        IJavaProject selectedProject = getJavaProject();
        IJavaElement[] elements;
        if (selectedProject != null && selectedProject.exists()) {
            elements = new IJavaElement[] { selectedProject };
        } else {
            elements = JDTUtil.getAllJavaProjects();
        }
        if (elements == null) {
            elements = new IJavaElement[] {};
        }
        IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(elements, IJavaSearchScope.SOURCES);
        AllTypesSearchEngine engine = new AllTypesSearchEngine();
        IType[] types = engine.searchTypes(getLaunchConfigurationDialog(), searchScope);
        // Open selection dialog
        DebugTypeSelectionDialog mmsd = new DebugTypeSelectionDialog(getShell(), types, "Select Type");
        IType selectedType = getType();
        if (selectedType != null) {
            mmsd.setInitialElementSelections(Collections.singletonList(selectedType));
        }
        if (mmsd.open() == DebugTypeSelectionDialog.OK) {
            Object[] results = mmsd.getResult();
            if (results != null && results.length >= 1 && results[0] instanceof IType) {
                IType type = (IType) results[0];
                projectText.setText(type.getJavaProject().getElementName());
                typeText.setText(type.getFullyQualifiedName());
            }
        }
    } catch (Exception e) {
        LogUtil.getLogger().logError(e);
        LogUtil.getLogger().openErrorDialog(getShell(), e);
    }
}

From source file:org.key_project.sed.key.ui.launch.MainLaunchConfigurationComposite.java

License:Open Source License

/**
 * {@inheritDoc}/*  www  .  j a v a2  s  .  c om*/
 */
@Override
public String getNotValidMessage() {
    String message = null;
    if (newDebugSessionButton.getSelection()) {
        // Validate Java project
        if (message == null) {
            IJavaProject project = getJavaProject();
            if (project == null || !project.exists()) {
                message = "No existing Java project selected.";
            }
        }
        // Validate type
        if (message == null) {
            IType type = getType();
            if (type == null || !type.exists()) {
                message = "No existing type selected.";
            }
        }
        // Validate method
        IMethod method = null;
        if (message == null) {
            method = getMethod();
            if (method == null || !method.exists()) {
                message = "No existing method selected.";
            }
        }
        // Validate method range
        if (message == null && isExecuteMethodRange()) {
            // Make sure that line and columns of method range are valid integers
            int startLine = 0;
            try {
                startLine = getMethodRangeStartLine();
            } catch (NumberFormatException e) {
                message = "Start line of method range \"" + startLineText.getText() + "\" is no valid integer.";
            }
            int startColumn = 0;
            if (message == null) {
                try {
                    startColumn = getMethodRangeStartColumn();
                } catch (NumberFormatException e) {
                    message = "Start column of method range \"" + startColumnText.getText()
                            + "\" is no valid integer.";
                }
            }
            int endLine = 0;
            if (message == null) {
                try {
                    endLine = getMethodRangeEndLine();
                } catch (NumberFormatException e) {
                    message = "To line of method range \"" + endLineText.getText() + "\" is no valid integer.";
                }
            }
            int endColumn = 0;
            if (message == null) {
                try {
                    endColumn = getMethodRangeEndColumn();
                } catch (NumberFormatException e) {
                    message = "To column of method range \"" + endColumnText.getText()
                            + "\" is no valid integer.";
                }
            }
            // Make sure that defined start and end are in method's source range
            if (message == null) {
                try {
                    ISourceRange methodSourceRange = method.getSourceRange();
                    Position methodStartPosition = KeYUtil.getCursorPositionForOffset(method,
                            methodSourceRange.getOffset());
                    Position methodEndPosition = KeYUtil.getCursorPositionForOffset(method,
                            methodSourceRange.getOffset() + methodSourceRange.getLength());
                    Position startPosition = new KeYUtil.CursorPosition(startLine, startColumn);
                    if (startPosition.compareTo(methodStartPosition) < 0) {
                        message = "From method range (" + startPosition + ") must be greater or equal to \""
                                + methodStartPosition + "\".";
                    }
                    if (message == null && startPosition.compareTo(methodEndPosition) > 0) {
                        message = "From method range (" + startPosition + ") must be lower or equal to \""
                                + methodEndPosition + "\".";
                    }
                    Position endPosition = new KeYUtil.CursorPosition(endLine, endColumn);
                    if (message == null && endPosition.compareTo(methodEndPosition) > 0) {
                        message = "To method range (" + endPosition + ") must be lower or equal to \""
                                + methodEndPosition + "\".";
                    }
                    if (message == null && endPosition.compareTo(methodStartPosition) < 0) {
                        message = "To method range (" + endPosition + ") must be greater or equal to \""
                                + methodStartPosition + "\".";
                    }
                    // Make sure that end is after start
                    if (message == null && startPosition.compareTo(endPosition) > 0) {
                        message = "Method range to (" + startPosition
                                + ") must be greater or equal to method range from (" + endPosition + ").";
                    }
                } catch (Exception e) {
                    message = e.getMessage();
                }
            }
        }
        // Validate contract
        if (message == null) {
            if (useExistingContractButton.getSelection()) {
                if (StringUtil.isTrimmedEmpty(getContractId())) {
                    message = "No existing contract defined.";
                }
            }
        }
    } else {
        // Validate proof file
        String proofText = proofFileText.getText();
        if (StringUtil.isEmpty(proofText)) {
            message = "No proof file to continue defined.";
        } else {
            IFile proofFile = getProofFile();
            if (proofFile != null && proofFile.exists()) {
                if (!KeYUtil.PROOF_FILE_EXTENSION.equals(proofFile.getFileExtension())) {
                    message = "Proof file \"" + proofFile.getFullPath().toString()
                            + "\" has not the expected file extension \"" + KeYUtil.PROOF_FILE_EXTENSION
                            + "\".";
                }
            } else {
                message = "Proof file \"" + proofText + "\" don't exist.";
            }
        }
    }
    return message;
}

From source file:org.key_project.util.jdt.JDTUtil.java

License:Open Source License

/**
 * Checks if the given {@link IProject} is a Java project.
 * @param project The {@link IProject} to check.
 * @return {@code true} is Java project, {@code false} is no Java project.
 *///  ww w  .  j a  va2 s  .c om
public static boolean isJavaProject(IProject project) {
    if (project != null) {
        IJavaProject javaProject = getJavaProject(project);
        return javaProject != null && javaProject.exists();
    } else {
        return false;
    }
}

From source file:org.key_project.util.jdt.JDTUtil.java

License:Open Source License

/**
 * Checks if the given {@link IResource} is or is contained in a source folder of its project.
 * @param resource The {@link IResource} to check.
 * @return {@code true} is source folder of its project or contained in a source folder of its project, {@code false} is somewhere else.
 * @throws JavaModelException Occurred Exception.
 *///from ww w  .ja v  a 2 s  .c  o  m
public static boolean isInSourceFolder(IResource resource) throws JavaModelException {
    boolean inSourceFolder = false;
    if (resource != null) {
        IJavaProject javaProject = getJavaProject(resource.getProject());
        if (javaProject != null && javaProject.exists()) {
            IClasspathEntry[] entries = javaProject.getRawClasspath();
            int i = 0;
            while (!inSourceFolder && i < entries.length) {
                if (entries[i].getContentKind() == IPackageFragmentRoot.K_SOURCE) {
                    IPackageFragmentRoot[] roots = javaProject.findPackageFragmentRoots(entries[i]);
                    int j = 0;
                    while (!inSourceFolder && j < roots.length) {
                        IResource rootResource = roots[j].getResource();
                        if (rootResource != null && rootResource.contains(resource)) {
                            inSourceFolder = true;
                        }
                        j++;
                    }
                }
                i++;
            }
        }
    }
    return inSourceFolder;
}

From source file:org.key_project.util.jdt.JDTUtil.java

License:Open Source License

/**
 * Returns all source {@link IPackageFragmentRoot}s.
 * @param javaProject The {@link IJavaProject} to read source {@link IPackageFragmentRoot}s from.
 * @return The found {@link IPackageFragmentRoot}s.
 * @throws JavaModelException Occurred Exception.
 *///  w  w  w . ja v a2  s . c om
public static List<IPackageFragmentRoot> getSourcePackageFragmentRoots(IJavaProject javaProject)
        throws JavaModelException {
    List<IPackageFragmentRoot> result = new LinkedList<IPackageFragmentRoot>();
    if (javaProject != null && javaProject.exists()) {
        IClasspathEntry[] entries = javaProject.getRawClasspath();
        for (IClasspathEntry entry : entries) {
            if (entry.getContentKind() == IPackageFragmentRoot.K_SOURCE
                    && entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPackageFragmentRoot[] roots = javaProject.findPackageFragmentRoots(entry);
                CollectionUtil.addAll(result, roots);
            }
        }
    }
    return result;
}

From source file:org.key_project.util.jdt.JDTUtil.java

License:Open Source License

/**
 * Internal helper method that is used in {@link #getSourceLocations(IProject)}
 * to compute the source path. It is required to solve cycles in project dependencies.
 * @param project The given Project./*from   w w  w  .j  a v  a  2s . c om*/
 * @param alreadyHandledProjects The already handled {@link IProject} that don't need to be analysed again.
 * @return The found source locations in the file system.
 * @throws JavaModelException Occurred Exception.
 */
private static List<File> getSourceLocations(IProject project, Set<IProject> alreadyHandledProjects)
        throws JavaModelException {
    List<File> result = new LinkedList<File>();
    if (project != null) {
        Assert.isNotNull(alreadyHandledProjects);
        alreadyHandledProjects.add(project);
        IJavaProject javaProject = getJavaProject(project);
        if (javaProject != null && javaProject.exists()) {
            IClasspathEntry[] entries = javaProject.getRawClasspath();
            for (IClasspathEntry entry : entries) {
                if (entry.getContentKind() == IPackageFragmentRoot.K_SOURCE) {
                    List<File> location = getLocationFor(javaProject, entry, IPackageFragmentRoot.K_SOURCE,
                            alreadyHandledProjects);
                    if (location != null) {
                        result.addAll(location);
                    }
                }
            }
        }
    }
    return result;
}