Example usage for org.eclipse.jdt.core IPackageFragmentRoot getJavaProject

List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot getJavaProject

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragmentRoot getJavaProject.

Prototype

IJavaProject getJavaProject();

Source Link

Document

Returns the Java project this element is contained in, or null if this element is not contained in any Java project (for instance, the IJavaModel is not contained in any Java project).

Usage

From source file:de.fxworld.generationgap.ui.properties.SourceFolderContentProvider.java

License:Open Source License

@Override
public Object[] getElements(Object inputElement) {
    List<Object> result = new ArrayList<Object>();
    IJavaProject javaProject = (IJavaProject) inputElement;

    try {/*from ww  w.  j  av a  2s .c o m*/
        for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) {
            if ((root.getKind() == IPackageFragmentRoot.K_SOURCE) && (root.getJavaProject() == javaProject)) {
                result.add(root);
            }
        }

    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result.toArray();
}

From source file:es.bsc.servicess.ide.wizards.ServiceSsCommonWizardPage.java

License:Apache License

/**
 * A hook method that gets called when the package field has changed. The
 * method validates the package name and returns the status of the
 * validation. The validation also updates the package fragment model.
 * <p>/*from  ww  w . j  a  v  a 2 s  .  c o m*/
 * Subclasses may extend this method to perform their own validation.
 * </p>
 * 
 * @return the status of the validation
 */
protected IStatus packageChanged() {
    StatusInfo status = new StatusInfo();
    IPackageFragmentRoot root = getPackageFragmentRoot();
    fPackageDialogField.enableButton(root != null);

    IJavaProject project = root != null ? root.getJavaProject() : null;

    String packName = getPackageText();
    if (packName.length() > 0) {
        IStatus val = validatePackageName(packName, 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 (project != 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)) {
                        status.setError(NewWizardMessages.NewTypeWizardPage_error_ClashOutputLocation);
                        return status;
                    }
                }
            } catch (JavaModelException e) {
                JavaPlugin.log(e);
                // let pass
            }
        }

        fCurrPackage = root.getPackageFragment(packName);
    } else {
        status.setError(""); //$NON-NLS-1$
    }
    return status;
}

From source file:es.bsc.servicess.ide.wizards.ServiceSsNewServiceClassPage.java

License:Apache License

/**
 * A hook method that gets called when the package field has changed. The
 * method validates the package name and returns the status of the
 * validation. The validation also updates the package fragment model.
 * <p>//  w  ww .j a  v  a2  s.c om
 * Subclasses may extend this method to perform their own validation.
 * </p>
 * 
 * @return the status of the validation
 */
protected IStatus packageChanged() {
    StatusInfo status = new StatusInfo();
    IPackageFragmentRoot root = getPackageFragmentRoot();
    fPackageDialogField.enableButton(root != null);

    IJavaProject project = root != null ? root.getJavaProject() : null;

    String packName = getPackageText();
    if (packName.length() > 0) {
        IStatus val = validatePackageName(packName, 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 (project != 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)) {
                        status.setError(NewWizardMessages.NewTypeWizardPage_error_ClashOutputLocation);
                        return status;
                    }
                }
            } catch (JavaModelException e) {
                JavaPlugin.log(e);
                // let pass
            }
        }
        fCurrPackage = root.getPackageFragment(packName);
    } else {
        status.setError(""); //$NON-NLS-1$
    }
    return status;
}

From source file:it.unibz.instasearch.indexing.WorkspaceIndexerJDT.java

License:Open Source License

/**
 * @param jar/* w w w.  j av a 2 s . com*/
 * @return
 */
private String getProjectPath(IPackageFragmentRoot jar) {
    return jar.getJavaProject().getElementName() + "/" + getJarName(jar);
}

From source file:org.apache.felix.sigil.eclipse.ui.internal.refactor.MovePackageParticipant.java

License:Apache License

@Override
public RefactoringStatus checkConditions(IProgressMonitor monitor, CheckConditionsContext context)
        throws OperationCanceledException {
    if (getArguments().getUpdateReferences()) {
        try {//from  ww w . j av a2 s .c  o m
            ISigilProjectModel sourceProject = SigilCore.create(packageFragment.getJavaProject().getProject());
            IPackageFragmentRoot dest = (IPackageFragmentRoot) getArguments().getDestination();
            ISigilProjectModel destProject = SigilCore.create(dest.getJavaProject().getProject());

            RefactoringStatus status = new RefactoringStatus();
            if (!sourceProject.equals(destProject)) {
                RefactorUtil.touch(context, sourceProject);
                RefactorUtil.touch(context, destProject);

                final String packageName = packageFragment.getElementName();
                IPackageExport oldExport = ModelHelper.findExport(sourceProject, packageName);

                if (oldExport != null) {
                    IPackageExport newExport = ModelElementFactory.getInstance()
                            .newModelElement(IPackageExport.class);

                    newExport.setPackageName(oldExport.getPackageName());
                    newExport.setVersion(oldExport.getRawVersion());

                    changes.add(new ExportPackageChange(destProject, null, newExport));
                    changes.add(new ExportPackageChange(sourceProject, oldExport, null));

                    status.addWarning(
                            "Package " + packageName + " is exported from " + sourceProject.getSymbolicName()
                                    + ", this may effect client bundles that use require bundle");
                } else {
                    SubMonitor sub = SubMonitor.convert(monitor);

                    sub.beginTask("Resolving package users", 200);

                    Set<String> users = JavaHelper.findLocalPackageUsers(sourceProject, packageName,
                            sub.newChild(100));
                    Set<String> dependencies = JavaHelper.findLocalPackageDependencies(sourceProject,
                            packageName, sub.newChild(100));

                    if (users.size() > 0 && dependencies.size() > 0) {
                        status.addWarning("Package " + packageName + " is coupled to " + users + " and "
                                + dependencies + " this may cause a cyclical dependency");
                    }

                    if (users.size() > 0) { // attempt to move an API package
                        IPackageExport newExport = RefactorUtil.createNewExport(status, changes, destProject,
                                packageName);
                        RefactorUtil.createNewImport(status, changes, sourceProject, newExport);
                    }

                    if (dependencies.size() > 0) { // moved an impl package
                        for (String dep : dependencies) {
                            IPackageExport newExport = RefactorUtil.createNewExport(status, changes,
                                    sourceProject, dep);
                            RefactorUtil.createNewImport(status, changes, destProject, newExport);
                        }
                    }
                }
            }
            return status;
        } catch (CoreException e) {
            SigilCore.warn("Failed to create move refactor conditions", e);
            throw new OperationCanceledException(e.getMessage());
        }
    } else {
        return new RefactoringStatus();
    }
}

From source file:org.apache.tapestrytools.ui.internal.wizards.NewTapestryComponentPage.java

License:Open Source License

/**
 * Add folder group to composite//w ww  .ja  v a  2 s .  c o m
 */
private void addFolderGroup(Composite composite) {
    // folder
    Label folderLabel = new Label(composite, SWT.LEFT);
    folderLabel.setText("Source folder:");
    folderLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    folderText = new Text(composite, SWT.SINGLE | SWT.BORDER);
    folderText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    IPackageFragmentRoot root = getSelectedPackageFragmentRoot();
    String projectName = projectNameCombo.getText();
    if (projectName != null && projectName.length() > 0) {
        IProject targetProject = ResourcesPlugin.getWorkspace().getRoot().findMember(projectName).getProject();
        if (root == null || !root.getJavaProject().getProject().equals(targetProject)) {
            IFolder folder = getDefaultJavaSourceFolder(targetProject);
            if (folder != null)
                folderText.setText(folder.getFullPath().toString());
        } else {
            folderText.setText(root.getPath().toString());
        }
    }

    folderButton = new Button(composite, SWT.PUSH);
    folderButton.setText("Browse");
    folderButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    folderButton.addSelectionListener(new SelectionListener() {
        public void widgetSelected(SelectionEvent e) {
            handleFolderButtonPressed();
        }

        public void widgetDefaultSelected(SelectionEvent e) {
            // Do nothing
        }
    });
}

From source file:org.apache.tapestrytools.ui.internal.wizards.NewTapestryPageClassWizard.java

License:Open Source License

/**
 * Add folder group to composite//w  w  w .j  a v  a 2s.  c  om
 */
private void addFolderGroup(Composite composite) {
    // folder
    Label folderLabel = new Label(composite, SWT.LEFT);
    folderLabel.setText("Source folder:");
    folderLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    folderText = new Text(composite, SWT.SINGLE | SWT.BORDER);
    folderText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    IPackageFragmentRoot root = getSelectedPackageFragmentRoot();
    String projectName = projectNameCombo.getText();
    if (projectName != null && projectName.length() > 0) {
        IProject targetProject = ResourcesPlugin.getWorkspace().getRoot().findMember(projectName).getProject();
        if (root == null || !root.getJavaProject().getProject().equals(targetProject)) {
            IFolder folder = getDefaultJavaSourceFolder(targetProject);
            if (folder != null) {
                folderText.setText(folder.getFullPath().toString());
            }

        } else {
            folderText.setText(root.getPath().toString());
        }
    }

    folderButton = new Button(composite, SWT.PUSH);
    folderButton.setText("Browse");
    folderButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    folderButton.addSelectionListener(new SelectionListener() {
        public void widgetSelected(SelectionEvent e) {
            handleFolderButtonPressed();
        }

        public void widgetDefaultSelected(SelectionEvent e) {
            // Do nothing
        }
    });
}

From source file:org.cloudfoundry.ide.eclipse.server.standalone.internal.application.JavaPackageFragmentRootHandler.java

License:Open Source License

/**
 * /*from  ww w .  j a v a 2 s.c o m*/
 * Determines if the given package fragment root corresponds to the class
 * path entry path.
 * <p/>
 * Note that different package fragment roots may point to the same class
 * path entry.
 * <p/>
 * Example:
 * <p/>
 * A Java project may have the following package fragment roots:
 * <p/>
 * - src/main/java
 * <p/>
 * - src/main/resources
 * <p/>
 * Both may be using the same output folder:
 * <p/>
 * target/classes.
 * <p/>
 * In this case, the output folder will have a class path entry -
 * target/classes - and it will be the same for both roots, and this method
 * will return true for both roots if passed the entry for target/classes
 * 
 * @param root
 *            to check if it corresponds to the given class path entry path
 * @param entry
 * @return true if root is at the given entry
 */
private static boolean isRootAtEntry(IPackageFragmentRoot root, IPath entry) {
    try {
        IClasspathEntry cpe = root.getRawClasspathEntry();
        if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            IPath outputLocation = cpe.getOutputLocation();
            if (outputLocation == null) {
                outputLocation = root.getJavaProject().getOutputLocation();
            }

            IPath location = ResourcesPlugin.getWorkspace().getRoot().findMember(outputLocation).getLocation();
            if (entry.equals(location)) {
                return true;
            }
        }
    } catch (JavaModelException e) {
        CloudFoundryPlugin.logError(e);
    }

    IResource resource = root.getResource();
    if (resource != null && entry.equals(resource.getLocation())) {
        return true;
    }

    IPath path = root.getPath();
    if (path != null && entry.equals(path)) {
        return true;
    }

    return false;
}

From source file:org.eclim.plugin.jdt.command.search.SearchCommand.java

License:Open Source License

/**
 * Creates a Position from the supplied SearchMatch.
 *
 * @param project The project searching from.
 * @param match The SearchMatch.//from  w  ww.  ja  va 2  s .c o  m
 * @return The Position.
 */
protected Position createPosition(IProject project, SearchMatch match) throws Exception {
    IJavaElement element = (IJavaElement) match.getElement();
    IJavaElement parent = JavaUtils.getPrimaryElement(element);

    String file = null;
    String elementName = JavaUtils.getFullyQualifiedName(parent);
    if (parent.getElementType() == IJavaElement.CLASS_FILE) {
        IResource resource = parent.getResource();
        // occurs with a referenced project as a lib with no source and class
        // files that are not archived in that project
        if (resource != null && resource.getType() == IResource.FILE && !isJarArchive(resource.getLocation())) {
            file = resource.getLocation().toOSString();

        } else {
            IPath path = null;
            IPackageFragmentRoot root = (IPackageFragmentRoot) parent.getParent().getParent();
            resource = root.getResource();
            if (resource != null) {
                if (resource.getType() == IResource.PROJECT) {
                    path = ProjectUtils.getIPath((IProject) resource);
                } else {
                    path = resource.getLocation();
                }
            } else {
                path = root.getPath();
            }

            String classFile = elementName.replace('.', File.separatorChar);
            if (isJarArchive(path)) {
                file = "jar:file://" + path.toOSString() + '!' + classFile + ".class";
            } else {
                file = path.toOSString() + '/' + classFile + ".class";
            }

            // android injects its jdk classes, so filter those out if the project
            // doesn't have the android nature.
            if (ANDROID_JDK_URL.matcher(file).matches() && project != null
                    && !project.hasNature(ANDROID_NATURE)) {
                return null;
            }

            // if a source path attachment exists, use it.
            IPath srcPath = root.getSourceAttachmentPath();
            if (srcPath != null) {
                String rootPath;
                IProject elementProject = root.getJavaProject().getProject();

                // determine if src path is project relative or file system absolute.
                if (srcPath.isAbsolute() && elementProject.getName().equals(srcPath.segment(0))) {
                    rootPath = ProjectUtils.getFilePath(elementProject, srcPath.toString());
                } else {
                    rootPath = srcPath.toOSString();
                }
                String srcFile = FileUtils.toUrl(rootPath + File.separator + classFile + ".java");

                // see if source file exists at source path.
                FileSystemManager fsManager = VFS.getManager();
                FileObject fileObject = fsManager.resolveFile(srcFile.replace("%", "%25"));
                if (fileObject.exists()) {
                    file = srcFile;

                    // jdk sources on osx are under a "src/" dir in the jar
                } else if (Os.isFamily(Os.FAMILY_MAC)) {
                    srcFile = FileUtils
                            .toUrl(rootPath + File.separator + "src" + File.separator + classFile + ".java");
                    fileObject = fsManager.resolveFile(srcFile.replace("%", "%25"));
                    if (fileObject.exists()) {
                        file = srcFile;
                    }
                }
            }
        }
    } else {
        IPath location = match.getResource().getLocation();
        file = location != null ? location.toOSString() : null;
    }

    elementName = JavaUtils.getFullyQualifiedName(element);
    return Position.fromOffset(file.replace('\\', '/'), elementName, match.getOffset(), match.getLength());
}

From source file:org.eclipse.ajdt.internal.buildpath.AddToAspectpathAction.java

License:Open Source License

public void selectionChanged(IAction action, ISelection sel) {
    boolean enable = false;
    if (sel instanceof IStructuredSelection) {
        IStructuredSelection selection = (IStructuredSelection) sel;
        Object element = selection.getFirstElement();
        try {// w  ww  . j a  va2 s  .  co  m
            if (element instanceof IPackageFragmentRoot) {
                IPackageFragmentRoot root = (IPackageFragmentRoot) element;
                project = root.getJavaProject().getProject();
                cpEntry = root.getRawClasspathEntry();
                jarFile = null;
                fileName = root.getElementName();
                enable = !AspectJCorePreferences.isOnAspectpath(cpEntry);
            } else {
                jarFile = getJARFile(selection);
                if (jarFile != null) {
                    cpEntry = null;
                    project = jarFile.getProject();
                    enable = (!AspectJCorePreferences.isOnAspectpath(project,
                            jarFile.getFullPath().toPortableString()) && !checkIfAddingOutjar(project));
                    fileName = jarFile.getName();
                }
            }
        } catch (JavaModelException e) {
        }
        action.setEnabled(enable);
    }
}