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

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

Introduction

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

Prototype

int K_SOURCE

To view the source code for org.eclipse.jdt.core IPackageFragmentRoot K_SOURCE.

Click Source Link

Document

Kind constant for a source path root.

Usage

From source file:com.codenvy.ide.ext.java.server.internal.core.search.JavaSearchScope.java

License:Open Source License

/**
 * Add an element to the java search scope.
 *
 * @param element/*from w  w w .  j  av a  2s  .c om*/
 *         The element we want to add to current java search scope
 * @throws org.eclipse.jdt.core.JavaModelException
 *         May happen if some Java Model info are not available
 */
public void add(IJavaElement element) throws JavaModelException {
    IPath containerPath = null;
    String containerPathToString = null;
    PackageFragmentRoot root = null;
    int includeMask = SOURCES | APPLICATION_LIBRARIES | SYSTEM_LIBRARIES;
    switch (element.getElementType()) {
    case IJavaElement.JAVA_MODEL:
        // a workspace sope should be used
        break;
    case IJavaElement.JAVA_PROJECT:
        add((JavaProject) element, null, includeMask, new HashSet(2), new HashSet(2), null);
        break;
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        root = (PackageFragmentRoot) element;
        IPath rootPath = root.internalPath();
        containerPath = root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : rootPath;
        containerPathToString = containerPath.getDevice() == null ? containerPath.toString()
                : containerPath.toOSString();
        IResource rootResource = root.resource();
        String projectPath = root.getJavaProject().getPath().toString();
        if (rootResource != null && rootResource.isAccessible()) {
            String relativePath = Util.relativePath(rootResource.getFullPath(), containerPath.segmentCount());
            add(projectPath, relativePath, containerPathToString, false/*not a package*/, null);
        } else {
            add(projectPath, "", containerPathToString, false/*not a package*/, null); //$NON-NLS-1$
        }
        break;
    case IJavaElement.PACKAGE_FRAGMENT:
        root = (PackageFragmentRoot) element.getParent();
        projectPath = root.getJavaProject().getPath().toString();
        if (root.isArchive()) {
            String relativePath = Util.concatWith(((PackageFragment) element).names, '/');
            containerPath = root.getPath();
            containerPathToString = containerPath.getDevice() == null ? containerPath.toString()
                    : containerPath.toOSString();
            add(projectPath, relativePath, containerPathToString, true/*package*/, null);
        } else {
            IResource resource = ((JavaElement) element).resource();
            if (resource != null) {
                if (resource.isAccessible()) {
                    containerPath = root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath()
                            : root.internalPath();
                } else {
                    // for working copies, get resource container full path
                    containerPath = resource.getParent().getFullPath();
                }
                containerPathToString = containerPath.getDevice() == null ? containerPath.toString()
                        : containerPath.toOSString();
                String relativePath = Util.relativePath(resource.getFullPath(), containerPath.segmentCount());
                add(projectPath, relativePath, containerPathToString, true/*package*/, null);
            }
        }
        break;
    default:
        // remember sub-cu (or sub-class file) java elements
        if (element instanceof IMember) {
            if (this.elements == null) {
                this.elements = new ArrayList();
            }
            this.elements.add(element);
        }
        root = (PackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        projectPath = root.getJavaProject().getPath().toString();
        String relativePath;
        if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
            containerPath = root.getParent().getPath();
            relativePath = Util.relativePath(getPath(element, false/*full path*/), 1/*remove project segment*/);
        } else {
            containerPath = root.internalPath();
            relativePath = getPath(element, true/*relative path*/).toString();
        }
        containerPathToString = containerPath.getDevice() == null ? containerPath.toString()
                : containerPath.toOSString();
        add(projectPath, relativePath, containerPathToString, false/*not a package*/, null);
    }

    if (root != null)
        addEnclosingProjectOrJar(
                root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : root.getPath());
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.JavaSearchNameEnvironment.java

License:Open Source License

private void computeClasspathLocations(JavaProject javaProject) {

    IPackageFragmentRoot[] roots = null;
    try {//from   ww  w . j ava 2s  .  c om
        roots = javaProject.getAllPackageFragmentRoots();
    } catch (JavaModelException e) {
        // project doesn't exist
        this.locations = new ClasspathLocation[0];
        return;
    }
    int length = roots.length;
    ClasspathLocation[] cpLocations = new ClasspathLocation[length];
    int index = 0;
    JavaModelManager manager = JavaModelManager.getJavaModelManager();
    for (int i = 0; i < length; i++) {
        PackageFragmentRoot root = (PackageFragmentRoot) roots[i];
        IPath path = root.getPath();
        try {
            if (root.isArchive()) {
                ZipFile zipFile = manager.getZipFile(path);
                cpLocations[index++] = new ClasspathJar(zipFile,
                        ((ClasspathEntry) root.getRawClasspathEntry()).getAccessRuleSet());
            } else {
                Object target = JavaModelManager.getTarget(path, true);
                if (target == null) {
                    // target doesn't exist any longer
                    // just resize cpLocations
                    System.arraycopy(cpLocations, 0,
                            cpLocations = new ClasspathLocation[cpLocations.length - 1], 0, index);
                } else if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                    cpLocations[index++] = new ClasspathSourceDirectory((File) target,
                            root.fullExclusionPatternChars(), root.fullInclusionPatternChars());
                } else {
                    cpLocations[index++] = ClasspathLocation.forBinaryFolder((IContainer) target, false,
                            ((ClasspathEntry) root.getRawClasspathEntry()).getAccessRuleSet());
                }
            }
        } catch (CoreException e1) {
            // problem opening zip file or getting root kind
            // consider root corrupt and ignore
            // just resize cpLocations
            System.arraycopy(cpLocations, 0, cpLocations = new ClasspathLocation[cpLocations.length - 1], 0,
                    index);
        }
    }
    this.locations = cpLocations;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.PackageReferenceLocator.java

License:Open Source License

public static boolean isDeclaringPackageFragment(IPackageFragment packageFragment,
        ReferenceBinding typeBinding) {/*from   w w  w  .  ja  v  a 2 s  . c o  m*/
    char[] fileName = typeBinding.getFileName();
    if (fileName != null) {
        // retrieve the actual file name from the full path (sources are generally only containing it already)
        fileName = CharOperation.replaceOnCopy(fileName, '/', '\\'); // ensure to not do any side effect on file name (see https://bugs.eclipse
        // .org/bugs/show_bug.cgi?id=136016)
        fileName = CharOperation.lastSegment(fileName, '\\');

        try {
            switch (packageFragment.getKind()) {
            case IPackageFragmentRoot.K_SOURCE:
                if (!org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(fileName)
                        || !packageFragment.getCompilationUnit(new String(fileName)).exists()) {
                    return false; // unit doesn't live in selected package
                }
                break;
            case IPackageFragmentRoot.K_BINARY:
                //               if (Util.isJavaFileName(fileName)) { // binary with attached source
                //                  int length = fileName.length;
                //                  System.arraycopy(fileName, 0, fileName = new char[length], 0, length - 4); // copy all but extension
                //                  System.arraycopy(SuffixConstants.SUFFIX_class, 0, fileName, length - 4, 4);
                //               }
                if (!Util.isClassFileName(fileName)
                        || !packageFragment.getClassFile(new String(fileName)).exists()) {
                    return false; // classfile doesn't live in selected package
                }
                break;
            }
        } catch (JavaModelException e) {
            // unable to determine kind; tolerate this match
        }
    }
    return true; // by default, do not eliminate
}

From source file:com.dforensic.plugin.manal.parser.SuspectSearch.java

License:Open Source License

private boolean extractPackageInfos(IJavaProject javaProject) throws JavaModelException {
    IPackageFragment[] packages = javaProject.getPackageFragments();
    for (IPackageFragment packageSearched : packages) {
        if (mFilterMethods != null) {
            for (ApiDescriptor api : mFilterMethods) {
                // Package fragments include all packages in the classpath.
                // We will only look at the package from the source folder.
                // K_BINARY would include also included JARS, e.g. rt.jar
                String packageName = api.getPackageNameFromSoot();
                if (packageName != null) {
                    if ((packageSearched.getKind() == IPackageFragmentRoot.K_SOURCE)
                            && packageName.equals(packageSearched.getElementName())) {
                        System.out.println("Package " + packageSearched.getElementName());
                        if (createAST(packageSearched, api)) {
                            return true;
                        }/*w  ww  .  j  a v  a2s  .c  o m*/
                        // extractClassInfo(mypackage);
                    }
                } else {
                    System.err.println("Package name is NULL for " + api.toString());
                }
            }
        } else {
            System.err.println("Methods for search are not initialized. " + "mFilterMethods is NULL.");
        }
    }
    return false;
}

From source file:com.ebmwebsourcing.petals.common.internal.provisional.projectscnf.PetalsProjectsSorter.java

License:Open Source License

/**
 * Compares Java elements.//  w  w  w  . j a  va2s.com
 * @param j1
 * @param j2
 * @return an integer for sorting (0 if equivalent, <0 to display j1 first, >0 to display j2 first)
 */
private int compareJavaElements(IJavaElement j1, IJavaElement j2) {

    // Fragment roots have a special treatment
    if (j1 instanceof IPackageFragmentRoot && j2 instanceof IPackageFragmentRoot) {
        IPackageFragmentRoot p1 = (IPackageFragmentRoot) j1;
        IPackageFragmentRoot p2 = (IPackageFragmentRoot) j2;

        try {
            if (p1.getKind() == p2.getKind())
                return p1.getElementName().compareTo(p2.getElementName());
            else if (p1.getKind() == IPackageFragmentRoot.K_SOURCE)
                return -1;
            else
                return 1;

        } catch (JavaModelException e) {
            PetalsCommonPlugin.log(e, IStatus.ERROR);
        }

        return p1.getElementName().compareTo(p2.getElementName());
    }

    // Otherwise, it depends on the element type
    if (j1.getElementType() == j2.getElementType())
        return j1.getElementName().compareTo(j2.getElementName());
    else
        return j1.getElementType() - j2.getElementType();
}

From source file:com.ecfeed.ui.common.utils.EclipsePackageFragmentGetter.java

License:Open Source License

private static IPackageFragmentRoot getAnySourceFolder(IFileInfoProvider fFileInfoProvider)
        throws CoreException {

    if (fFileInfoProvider.getProject().hasNature(JavaCore.NATURE_ID)) {
        IJavaProject project = JavaCore.create(fFileInfoProvider.getProject());

        for (IPackageFragmentRoot packageFragmentRoot : project.getPackageFragmentRoots()) {
            if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
                return packageFragmentRoot;
            }//w  w  w  .j  a  v  a  2 s.  c  om
        }
    }
    return null;
}

From source file:com.flamefire.importsmalinames.handlers.RenameVariablesHandler.java

License:Open Source License

public IJavaProject getProject(ICompilationUnit cu) {
    try {// w ww . java 2 s.  c  o  m
        // Get the root of the workspace
        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IWorkspaceRoot root = workspace.getRoot();
        // Get all projects in the workspace
        IProject[] projects = root.getProjects();
        // Loop over all projects
        for (IProject project : projects) {
            if (!project.isNatureEnabled("org.eclipse.jdt.core.javanature"))
                continue;
            IJavaProject javaProject = JavaCore.create(project);
            IPackageFragment[] packages = javaProject.getPackageFragments();
            for (IPackageFragment mypackage : packages) {
                if (mypackage.getKind() != IPackageFragmentRoot.K_SOURCE)
                    continue;
                for (ICompilationUnit unit : mypackage.getCompilationUnits()) {
                    if (cu.equals(unit))
                        return javaProject;
                }
            }
        }
    } catch (CoreException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.flamefire.importsmalinames.handlers.RenameVariablesHandler.java

License:Open Source License

private void doRename(Shell shell, ICompilationUnit cu) {
    IJavaProject proj = getProject(cu);//from   w w w .j a v  a 2s.  c o m
    String cClassName = null;
    String pName = null;
    try {
        cClassName = cu.getCorrespondingResource().getName();
        if (proj != null)
            pName = proj.getElementName();
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    if (cClassName == null || pName == null || cClassName.length() == 0 || pName.length() == 0) {
        MessageDialog.openError(shell, "Error", "Could not access project and class names");
        return;
    }
    boolean classOnly = MessageDialog.openQuestion(shell, "Apply smali names only to current class?",
            "Do you want to apply the names only to current java file (" + cClassName + ") ->YES\n"
                    + "Or to the whole project (" + pName + ") -> NO");
    String lastFolder = null;
    IResource res = null;
    try {
        res = proj.getCorrespondingResource();
        lastFolder = com.flamefire.importsmalinames.utils.Util.getPersistentProperty(res, LASTFOLDER);
    } catch (JavaModelException e) {
    }
    JFileChooser j = new JFileChooser();
    j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    j.setDialogTitle("Select smali directory");
    if (lastFolder != null)
        j.setSelectedFile(new File(lastFolder));
    if (j.showOpenDialog(null) != JFileChooser.APPROVE_OPTION)
        return;
    com.flamefire.importsmalinames.utils.Util.setPersistentProperty(res, LASTFOLDER,
            j.getSelectedFile().getAbsolutePath());
    File smaliFolder = j.getSelectedFile();
    RefactoringController controller = new RefactoringController();
    if (!controller.init(smaliFolder)) {
        MessageDialog.openError(shell, "Error", "Could not parse smali classes");
        return;
    }
    if (classOnly) {
        if (!controller.renameVariablesInFile(cu)) {
            MessageDialog.openError(shell, "Error", "Initializing the changes failed. Please check output.");
            return;
        }
    } else {
        try {
            IPackageFragment[] packages = proj.getPackageFragments();
            for (IPackageFragment mypackage : packages) {
                if (mypackage.getKind() != IPackageFragmentRoot.K_SOURCE)
                    continue;
                for (ICompilationUnit unit : mypackage.getCompilationUnits()) {
                    if (!controller.renameVariablesInFile(unit)) {
                        if (!MessageDialog.openConfirm(shell,
                                "Error in " + unit.getCorrespondingResource().getName(),
                                "Initializing the changes to " + unit.getCorrespondingResource().getName()
                                        + " failed. Please check output.\n\nContinue?"))
                            return;
                    }
                }
            }
        } catch (JavaModelException e) {
            e.printStackTrace();
        }
    }
    String msg = "This will apply the smali names to the ";
    if (classOnly)
        msg += "java file " + cClassName;
    else
        msg += "whole project " + pName;
    msg += "\n\nPlease note that you HAVE to check the changes without a preview and it is better to apply this to the decompiled source before you do any changes yourself.";
    msg += "\nThis might fail under certain circumstances e.g. with nested classes and certain name combinations.";
    msg += "\n\nProceed?";
    if (!MessageDialog.openConfirm(shell, "Apply smali names", msg))
        return;
    if (controller.applyRenamings(shell))
        MessageDialog.openInformation(shell, "Success",
                "Names were changed. Please have a look at the output in the console for warnings and errors");
    else
        MessageDialog.openInformation(shell, "Error",
                "There were erros changing the names. Some may have been changed. Please have a look at the output in the console for warnings and errors");
}

From source file:com.github.ko2ic.plugin.eclipse.taggen.core.ui.components.combo.OutputFolderCombo.java

License:Open Source License

public OutputFolderCombo(Composite parent, int style) {
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    IProject[] projects = root.getProjects();

    for (IProject project : projects) {
        try {/*  w w w .  jav  a  2  s.  c o  m*/
            IJavaProject javaProject = JavaCore.create(project);
            IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
            for (IPackageFragmentRoot pRoot : roots) {
                if (pRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
                    outputFolders.add(pRoot.getPath().removeFirstSegments(1).toOSString());
                }
            }
        } catch (JavaModelException e) {
            throw Throwables.propagate(new SystemException(e));
        }
    }

    outputFolderCombo = new Combo(parent, style);
}

From source file:com.google.appengine.eclipse.core.properties.GaeProjectProperties.java

License:Open Source License

public static List<IPath> getOrmEnhancementInclusionPatterns(IProject project) {
    List<IPath> patterns = new ArrayList<IPath>();

    IEclipsePreferences prefs = getProjectProperties(project);
    String rawPropVal = prefs.get(ORM_ENHANCEMENT_INCLUSIONS, null);
    if (rawPropVal == null) {
        // If we haven't set this property yet, default to including all Java src
        IJavaProject javaProject = JavaCore.create(project);
        try {/*from  w ww .  j a v a2s  .c o  m*/
            for (IPackageFragmentRoot pkgRoot : javaProject.getAllPackageFragmentRoots()) {
                if (pkgRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
                    // Only include src roots in this project
                    if (javaProject.equals(pkgRoot.getAncestor(IJavaElement.JAVA_PROJECT))) {
                        // Get project-relative path to source root
                        IPath pattern = pkgRoot.getPath().removeFirstSegments(1).makeRelative()
                                .addTrailingSeparator();
                        patterns.add(pattern);
                    }
                }
            }
        } catch (JavaModelException e) {
            AppEngineCorePluginLog.logError(e);
        }
    } else {
        patterns = PropertiesUtilities.deserializePaths(rawPropVal);
    }

    return patterns;
}