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:com.google.gwt.eclipse.core.launch.ui.tabs.GWTSettingsTab.java

License:Open Source License

private IProject getProject() throws CoreException {
    IJavaProject javaProject = getJavaProject();
    if (javaProject == null || !javaProject.exists()) {
        throw new CoreException(
                new Status(IStatus.ERROR, GWTPlugin.PLUGIN_ID, "Could not get a valid Java project"));
    }//ww w .  j a va2s. com
    return javaProject.getProject();
}

From source file:com.google.gwt.eclipse.core.runtime.GWTProjectsRuntime.java

License:Open Source License

/**
 * FIXME - Were it not for the super source stuff, we would need this method. Can't we provide a
 * way for users to state which folders are super-source, etc?
 *//*ww w.  ja va2s .c om*/
public static List<IRuntimeClasspathEntry> getGWTRuntimeProjectSourceEntries(IJavaProject project,
        boolean includeTestSourceEntries) throws SdkException {

    assert (isGWTRuntimeProject(project) && project.exists());

    String projectName = project.getProject().getName();
    List<IRuntimeClasspathEntry> sourceEntries = new ArrayList<IRuntimeClasspathEntry>();

    IClasspathEntry[] gwtUserJavaProjClasspathEntries = null;

    try {
        gwtUserJavaProjClasspathEntries = project.getRawClasspath();
    } catch (JavaModelException e) {
        throw new SdkException("Cannot extract raw classpath from " + projectName + " project.");
    }

    Set<IPath> absoluteSuperSourcePaths = new HashSet<IPath>();

    for (IClasspathEntry curClasspathEntry : gwtUserJavaProjClasspathEntries) {
        if (curClasspathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            IPath sourcePath = curClasspathEntry.getPath();

            if (isJavadocPath(sourcePath)) {
                // Ignore javadoc paths.
                continue;
            }

            if (GWTProjectUtilities.isTestPath(sourcePath) && !includeTestSourceEntries) {
                // Ignore test paths, unless it is specified explicitly that we should
                // include them.
                continue;
            }

            sourceEntries.add(JavaRuntime.newArchiveRuntimeClasspathEntry(sourcePath));

            // Figure out the location of the super source path.

            IPath absoluteSuperSourcePath = sourcePath.removeLastSegments(1).append(SUPER_SOURCE_FOLDER_NAME);
            IPath relativeSuperSourcePath = absoluteSuperSourcePath.removeFirstSegments(1);

            if (absoluteSuperSourcePaths.contains(absoluteSuperSourcePath)) {
                // I've already included this path.
                continue;
            }

            if (project.getProject().getFolder(relativeSuperSourcePath).exists()) {
                /*
                 * We've found the super source path, and we've not added it already. The existence test
                 * uses a relative path, but the creation of a runtime classpath entry requires an
                 * absolute path.
                 */
                sourceEntries.add(JavaRuntime.newArchiveRuntimeClasspathEntry(absoluteSuperSourcePath));
                absoluteSuperSourcePaths.add(absoluteSuperSourcePath);
            }

            IPath absoluteTestSuperSourcePath = sourcePath.removeLastSegments(1)
                    .append(TEST_SUPER_SOURCE_FOLDER_NAME);
            IPath relativeTestSuperSourcePath = absoluteTestSuperSourcePath.removeFirstSegments(1);
            if (absoluteSuperSourcePaths.contains(absoluteTestSuperSourcePath)) {
                // I've already included this path.
                continue;
            }

            if (includeTestSourceEntries
                    && project.getProject().getFolder(relativeTestSuperSourcePath).exists()) {
                /*
                 * We've found the super source path, and we've not added it already. The existence test
                 * uses a relative path, but the creation of a runtime classpath entry requires an
                 * absolute path.
                 */
                sourceEntries.add(JavaRuntime.newArchiveRuntimeClasspathEntry(absoluteTestSuperSourcePath));
                absoluteSuperSourcePaths.add(absoluteTestSuperSourcePath);
            }
        }
    }

    if (absoluteSuperSourcePaths.isEmpty()) {
        GWTPluginLog.logError("There were no super source folders found for the project '{0}'",
                project.getProject().getName());
    }

    return sourceEntries;
}

From source file:com.google.gwt.eclipse.core.runtime.GWTProjectsRuntime.java

License:Open Source License

@Override
public File getDevJar() throws SdkException /* throws Exception */, JavaModelException {

    IStringVariableManager variableManager = getVariableManager();
    IValueVariable valueVariable = variableManager.getValueVariable("gwt_devjar");
    if (valueVariable != null) {
        String value = valueVariable.getValue();
        if (value != null) {
            IPath path = new Path(value);
            File file = path.toFile();
            if (!file.exists()) {
                throw new SdkException("gwt_devjar Run/Debug variable points to a non-existent jar: " + value);
            }/*from   www .  j  av  a  2 s  . c  o m*/

            return file;
        }
    }

    // We're going to have to search down the trunk to find the built gwt-dev
    // .jar. This assumes that the user has built the trunk at least once

    // TODO: can we remove the check for gwt.devjar from applicationCreator?

    IProject userProject = ResourcesPlugin.getWorkspace().getRoot().getProject(GWT_USER_PROJECT_NAME);
    if (!userProject.exists()) {
        throw new SdkException("The project ' " + userProject.getName() + "' does not exist in the workspace.");
    }

    IJavaProject javaUserProject = JavaCore.create(userProject);

    if (!javaUserProject.exists()) {
        throw new SdkException("The project ' " + userProject.getName() + "' is not a Java project.");
    }

    IClasspathEntry[] rawClasspaths = javaUserProject.getRawClasspath();

    File stagingDir = null;
    IPath stagingPathLocation = null;

    for (IClasspathEntry rawClasspath : rawClasspaths) {
        if (rawClasspath.getEntryKind() == IClasspathEntry.CPE_SOURCE) {

            IPath sourcePathLocation = getAbsoluteLocation(rawClasspath.getPath(), userProject);
            stagingPathLocation = sourcePathLocation.removeLastSegments(2)
                    .append(STAGING_FOLDER_RELATIVE_LOCATION);

            stagingDir = stagingPathLocation.toFile();
            if (stagingDir.exists()) {
                break;
            }
        }
    }

    if (stagingPathLocation == null) {
        throw new SdkException("Contributor SDK build directory not found; Project '" + userProject.getName()
                + "' does not have any source folders.");
    }

    if (stagingDir == null || !stagingDir.exists()) {
        throw new SdkException("Contributor SDK build directory not found (expected at "
                + stagingPathLocation.toString() + ")");
    }

    // Find the staging output directory: gwt-<platform>-<version>
    final File[] buildDirs = stagingDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            return (file.isDirectory() && file.getName().startsWith("gwt-"));
        }
    });
    if (buildDirs.length == 0) {
        throw new SdkException("Contributor SDK build directory not found (expected at " + stagingDir.toString()
                + File.separator + "gwt-<platform>-<version>)");
    }

    // Find the gwt-dev .jar
    File[] gwtDevJars = buildDirs[0].listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            String name = file.getName();
            IPath sdkLocationPath = Path.fromOSString(buildDirs[0].getAbsolutePath());
            return (name.equalsIgnoreCase(Util.getDevJarName(sdkLocationPath)));
        }
    });
    if (gwtDevJars.length == 0) {
        throw new SdkException("Contributor SDK build directory missing required JAR files");
    }

    return gwtDevJars[0];
}

From source file:com.google.gwt.eclipse.core.speedtracer.ViewSourceServlet.java

License:Open Source License

private IPackageFragmentRoot getPackageFragmentRoot(String jarPathString, String preferredProjectName)
        throws IOException {
    try {//w ww  .  j  a  v a  2 s  .c o m
        IFile jarIFile = getFile(jarPathString);

        // The JAR is in the workspace
        return JavaCore.createJarPackageFragmentRootFrom(jarIFile);
    } catch (IOException e) {
        // JAR must not be in the workspace (or is not a file), continue..
    }

    File jarFile = new File(jarPathString);

    // Iterate projects to find the external JAR
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    List<IProject> projects = new ArrayList<IProject>(Arrays.asList(root.getProjects()));
    IProject preferredProject = preferredProjectName != null ? root.getProject(preferredProjectName) : null;
    if (preferredProject != null && preferredProject.exists()) {
        // Search the preferred project first
        projects.remove(preferredProject);
        projects.add(0, preferredProject);
    }

    for (IProject project : projects) {
        IJavaProject javaProject = JavaCore.create(project);
        if (!javaProject.exists()) {
            continue;
        }

        try {
            IClasspathEntry[] classpathEntries = javaProject.getResolvedClasspath(true);
            for (IClasspathEntry classpathEntry : classpathEntries) {
                IPath path = classpathEntry.getPath();
                if (jarFile.equals(path.toFile())) {
                    return javaProject.getPackageFragmentRoot(path.toOSString());
                }
            }

        } catch (JavaModelException e) {
            GWTPluginLog.logWarning(e, "Could not check " + project.getName() + " for JAR file");
            continue;
        }
    }

    return null;
}

From source file:com.google.gwt.eclipse.core.uibinder.model.reference.UiBinderXmlParser.java

License:Open Source License

/**
 * Returns a new instance of the parser.
 * /* w ww  .j  av  a 2s . c  o m*/
 * @param xmlModel the XML model to be parsed
 * @param referenceManager an optional reference manager that receives the
 *          parsed references types and XML files
 * @return an instance of the parser
 * @throws FileNotFoundException if a file backing the model could not be
 *           found
 * @throws UiBinderException if the file does not live in a java project
 */
public static UiBinderXmlParser newInstance(IDOMModel xmlModel, ReferenceManager referenceManager,
        IValidationResultPlacementStrategy<?> validationResultPlacementStrategy)
        throws FileNotFoundException, UiBinderException {
    // TODO: turn this method into a static parse method, because the usage
    // pattern
    // for this class is always UiBinderXmlParser.newInstance().parse().

    IFile xmlFile = SseUtilities.resolveFile(xmlModel);
    if (xmlFile == null) {
        throw new FileNotFoundException("Could not find the file backing the XML model.");
    }

    IJavaProject javaProject = JavaCore.create(xmlFile.getProject());
    if (!javaProject.exists()) {
        throw new UiBinderException("The UiBinder XML file is not part of a Java project.");
    }

    IPath xmlClasspathRelativePath;
    try {
        xmlClasspathRelativePath = ClasspathResourceUtilities.getClasspathRelativePathOfResource(xmlFile,
                javaProject);
        if (xmlClasspathRelativePath == null) {
            throw new UiBinderException(
                    "Could not resolve classpath-relative path to UiBinder XML template file.");
        }
    } catch (JavaModelException e) {
        throw new UiBinderException(e);
    }

    return new UiBinderXmlParser(xmlModel, xmlFile, xmlClasspathRelativePath, referenceManager,
            validationResultPlacementStrategy, javaProject);
}

From source file:com.google.gwt.eclipse.core.validators.java.JavaCompilationParticipant.java

License:Open Source License

@Override
public boolean isActive(IJavaProject project) {
    boolean active = project.exists() && GWTNature.isGWTProject(project.getProject());
    return active;
}

From source file:com.google.gwt.eclipse.core.wizards.NewModuleWizardPage.java

License:Open Source License

private IStatus packageChanged() {

    String packName = modulePackageField.getText();
    IStatus validatePackageStatus = Util.validatePackageName(packName);

    if (validatePackageStatus.getSeverity() == IStatus.ERROR) {
        return validatePackageStatus;
    }//ww  w .  j av  a2  s.  c  om

    if (packName.length() == 0) {
        modulePackageField.setStatus(NewWizardMessages.NewTypeWizardPage_default);
    } else {
        modulePackageField.setStatus("");
    }

    IJavaProject project = getJavaProject();
    IPackageFragmentRoot root = getPackageFragmentRoot();

    if (project != null && root != null) {
        if (project.exists() && packName.length() > 0) {
            try {
                IPath rootPath = root.getPath();
                IPath outputPath = project.getOutputLocation();
                if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
                    // if the bin folder is inside of our root, don't allow to name a
                    // package like the bin folder
                    IPath packagePath = rootPath.append(packName.replace('.', '/'));
                    if (outputPath.isPrefixOf(packagePath)) {
                        return Util
                                .newErrorStatus(NewWizardMessages.NewTypeWizardPage_error_ClashOutputLocation);
                    }
                }
            } catch (JavaModelException e) {
                // Not a critical exception at this juncture; we'll just log it
                // and move on.
                GWTPluginLog.logError(e);
            }
        }
    }

    return validatePackageStatus;
}

From source file:com.google.test.metric.eclipse.ui.TestabilityLaunchConfigurationTab.java

License:Apache License

public void initializeFrom(ILaunchConfiguration configuration) {
    setMessage("Create a configuration to launch a testability session.");
    try {//w ww  .  jav  a2 s  .c o m
        String initProjectName = configuration
                .getAttribute(TestabilityConstants.CONFIGURATION_ATTR_PROJECT_NAME, "");
        if (initProjectName != null && initProjectName.length() > 0) {
            projectText.setText(initProjectName);
            IJavaProject javaProject = javaProjectHelper.getJavaProject(initProjectName);
            if (javaProject == null || !javaProject.exists()) {
                setErrorMessage(MessageFormat.format(
                        "Project named {0} does not exist. Please choose another project.", initProjectName));
            }
        } else {
            projectText.setText("");
        }

        String initReportFolderName = configuration
                .getAttribute(TestabilityConstants.CONFIGURATION_ATTR_REPORT_FOLDER_NAME, "");
        if (initReportFolderName != null && initReportFolderName.length() > 0) {
            reportFolderText.setText(initReportFolderName);
        } else {
            reportFolderText.setText("");
        }

        initializeTextBoxesFromHistory(configuration);

        boolean isRunOnBuild = configuration.getAttribute(TestabilityConstants.CONFIGURATION_ATTR_RUN_ON_BUILD,
                false);
        runOnCompileCheckbox.setSelection(isRunOnBuild);
    } catch (CoreException e) {
        e.printStackTrace();
    }
}

From source file:com.google.test.metric.eclipse.ui.TestabilityLaunchConfigurationTab.java

License:Apache License

@Override
public boolean isValid(ILaunchConfiguration launchConfig) {
    String currentProjectName = projectText.getText();
    if (currentProjectName != null) {
        IJavaProject javaProject = getSelectedProject();
        if (javaProject == null || !javaProject.exists()) {
            setErrorMessage(MessageFormat.format(
                    "Project named {0} does not exist. Please choose another project.", currentProjectName));
            return false;
        } else if (configurationHelper.isExistingLaunchConfigWithRunOnBuildOtherThanCurrent(currentProjectName,
                launchConfig.getName()) && runOnCompileCheckbox.getSelection()) {
            setErrorMessage(MessageFormat.format(
                    "Project named {0} already has another active configuration with Run on every build "
                            + "set. Please uncheck the box or remove it from the other configuration",
                    currentProjectName));
            return false;
        } else {//from   ww  w.  jav  a  2 s.c o  m
            setErrorMessage(null);
            setMessage("Create a configuration to launch a testability session.");
            return true;
        }
    }
    return false;
}

From source file:com.gwtplatform.plugin.wizard.NewActionWizardPage.java

License:Apache License

private IStatus actionHandlerChanged() {
    StatusInfo status = new StatusInfo();

    if (actionHandlerPackage.getText().isEmpty()) {
        status.setError("You must select the ActionHandler's package");
        return status;
    }//from  w  w  w .  j a  v a2s . co m

    IPackageFragmentRoot root = getPackageFragmentRoot();
    IJavaProject project = root.getJavaProject();
    IPackageFragment pack = root.getPackageFragment(actionHandlerPackage.getText());

    if (!pack.getElementName().isEmpty()) {
        IStatus val = JavaConventionsUtil.validatePackageName(pack.getElementName(), project);
        if (val.getSeverity() == IStatus.ERROR) {
            status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidPackageName,
                    val.getMessage()));
            return status;
        } else if (val.getSeverity() == IStatus.WARNING) {
            status.setWarning(Messages.format(
                    NewWizardMessages.NewTypeWizardPage_warning_DiscouragedPackageName, val.getMessage()));
            // continue
        }
    } else {
        status.setWarning(NewWizardMessages.NewTypeWizardPage_warning_DefaultPackageDiscouraged);
    }

    if (!pack.getElementName().contains(".server")) {
        status.setError("ActionHandler's package must be in the server package");
        return status;
    }

    if (project != null) {
        if (project.exists() && !pack.getElementName().isEmpty()) {
            try {
                IPath rootPath = root.getPath();
                IPath outputPath = project.getOutputLocation();
                if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
                    // if the bin folder is inside of our root, don't allow to name a
                    // package
                    // like the bin folder
                    IPath packagePath = rootPath.append(pack.getElementName().replace('.', '/'));
                    if (outputPath.isPrefixOf(packagePath)) {
                        status.setError(NewWizardMessages.NewTypeWizardPage_error_ClashOutputLocation);
                        return status;
                    }
                }
            } catch (JavaModelException e) {
                JavaPlugin.log(e);
                // let pass
            }
        }
    } else {
        status.setError("");
    }
    return status;
}