Example usage for org.eclipse.jdt.internal.core JavaProject getProject

List of usage examples for org.eclipse.jdt.internal.core JavaProject getProject

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.core JavaProject getProject.

Prototype

@Override
public IProject getProject() 

Source Link

Usage

From source file:com.cisco.yangide.core.indexing.DeltaProcessor.java

License:Open Source License

private OutputsInfo outputsInfo(IResource res) {
    try {/* w  w  w.  j ava 2s .  c om*/
        JavaProject proj = (JavaProject) JavaCore.create(res.getProject());
        if (proj != null) {
            IPath projectOutput = proj.getOutputLocation();
            int traverseMode = IGNORE;
            if (proj.getProject().getFullPath().equals(projectOutput)) { // case of
                // proj==bin==src
                return new OutputsInfo(new IPath[] { projectOutput }, new int[] { SOURCE }, 1);
            }
            IClasspathEntry[] classpath = proj.getResolvedClasspath();
            IPath[] outputs = new IPath[classpath.length + 1];
            int[] traverseModes = new int[classpath.length + 1];
            int outputCount = 1;
            outputs[0] = projectOutput;
            traverseModes[0] = traverseMode;
            for (int i = 0, length = classpath.length; i < length; i++) {
                IClasspathEntry entry = classpath[i];
                IPath entryPath = entry.getPath();
                IPath output = entry.getOutputLocation();
                if (output != null) {
                    outputs[outputCount] = output;
                    // check case of src==bin
                    if (entryPath.equals(output)) {
                        traverseModes[outputCount++] = (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE)
                                ? SOURCE
                                : BINARY;
                    } else {
                        traverseModes[outputCount++] = IGNORE;
                    }
                }

                // check case of src==bin
                if (entryPath.equals(projectOutput)) {
                    traverseModes[0] = (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) ? SOURCE : BINARY;
                }
            }
            return new OutputsInfo(outputs, traverseModes, outputCount);
        }
    } catch (JavaModelException e) {
        // java project doesn't exist: ignore
    }
    return null;
}

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

License:Open Source License

/**
 * Compute the non-java resources contained in this java project.
 *//*w w w .j a  v  a2s.com*/
private Object[] computeNonJavaResources(JavaProject project) {

    // determine if src == project and/or if bin == project
    IPath projectPath = project.getProject().getFullPath();
    boolean srcIsProject = false;
    boolean binIsProject = false;
    char[][] inclusionPatterns = null;
    char[][] exclusionPatterns = null;
    IPath projectOutput = null;
    boolean isClasspathResolved = true;
    try {
        IClasspathEntry entry = project.getClasspathEntryFor(projectPath);
        if (entry != null) {
            srcIsProject = true;
            inclusionPatterns = ((ClasspathEntry) entry).fullInclusionPatternChars();
            exclusionPatterns = ((ClasspathEntry) entry).fullExclusionPatternChars();
        }
        projectOutput = project.getOutputLocation();
        binIsProject = projectPath.equals(projectOutput);
    } catch (JavaModelException e) {
        isClasspathResolved = false;
    }

    Object[] resources = new IResource[5];
    int resourcesCounter = 0;
    try {
        IResource[] members = ((IContainer) project.getResource()).members();
        int length = members.length;
        if (length > 0) {
            String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
            String complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
            IClasspathEntry[] classpath = project.getResolvedClasspath();
            for (int i = 0; i < length; i++) {
                IResource res = members[i];
                switch (res.getType()) {
                case IResource.FILE:
                    IPath resFullPath = res.getFullPath();
                    String resName = res.getName();

                    // ignore a jar file on the classpath
                    if (isClasspathResolved && isClasspathEntryOrOutputLocation(resFullPath,
                            res.getLocation()/* see https://bugs.eclipse
                                             .org/bugs/show_bug.cgi?id=244406 */, classpath, projectOutput)) {
                        break;
                    }
                    // ignore .java file if src == project
                    if (srcIsProject && Util.isValidCompilationUnitName(resName, sourceLevel, complianceLevel)
                            && !Util.isExcluded(res, inclusionPatterns, exclusionPatterns)) {
                        break;
                    }
                    // ignore .class file if bin == project
                    if (binIsProject && Util.isValidClassFileName(resName, sourceLevel, complianceLevel)) {
                        break;
                    }
                    // else add non java resource
                    if (resources.length == resourcesCounter) {
                        // resize
                        System.arraycopy(resources, 0, (resources = new IResource[resourcesCounter * 2]), 0,
                                resourcesCounter);
                    }
                    resources[resourcesCounter++] = res;
                    break;
                case IResource.FOLDER:
                    resFullPath = res.getFullPath();

                    // ignore non-excluded folders on the classpath or that correspond to an output location
                    if ((srcIsProject && !Util.isExcluded(res, inclusionPatterns, exclusionPatterns)
                            && Util.isValidFolderNameForPackage(res.getName(), sourceLevel, complianceLevel))
                            || (isClasspathResolved && isClasspathEntryOrOutputLocation(resFullPath,
                                    res.getLocation(), classpath, projectOutput))) {
                        break;
                    }
                    // else add non java resource
                    if (resources.length == resourcesCounter) {
                        // resize
                        System.arraycopy(resources, 0, (resources = new IResource[resourcesCounter * 2]), 0,
                                resourcesCounter);
                    }
                    resources[resourcesCounter++] = res;
                }
            }
        }
        if (resources.length != resourcesCounter) {
            System.arraycopy(resources, 0, (resources = new IResource[resourcesCounter]), 0, resourcesCounter);
        }
    } catch (CoreException e) {
        resources = NO_NON_JAVA_RESOURCES;
        resourcesCounter = 0;
    }
    return resources;
}

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

License:Open Source License

private static boolean canSeeFocus(IJavaElement focus, JavaProject javaProject,
        char[][][] focusQualifiedNames) {
    try {/*from  w w  w.  ja  v  a2s .  co  m*/
        if (focus == null)
            return false;
        if (focus.equals(javaProject))
            return true;

        if (focus instanceof JarPackageFragmentRoot) {
            // focus is part of a jar
            IPath focusPath = focus.getPath();
            IClasspathEntry[] entries = javaProject.getExpandedClasspath();
            for (int i = 0, length = entries.length; i < length; i++) {
                IClasspathEntry entry = entries[i];
                if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY && entry.getPath().equals(focusPath))
                    return true;
            }
            return false;
        }
        // look for dependent projects
        IPath focusPath = ((JavaProject) focus).getProject().getFullPath();
        IClasspathEntry[] entries = javaProject.getExpandedClasspath();
        for (int i = 0, length = entries.length; i < length; i++) {
            IClasspathEntry entry = entries[i];
            if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT && entry.getPath().equals(focusPath)) {
                if (focusQualifiedNames != null) { // builder state is usable, hence use it to try to reduce project which can see the focus...
                    State projectState = (State) JavaModelManager.getJavaModelManager()
                            .getLastBuiltState(javaProject.getProject(), null);
                    if (projectState != null) {
                        Object[] values = projectState.getReferences().valueTable;
                        int vLength = values.length;
                        for (int j = 0; j < vLength; j++) {
                            if (values[j] == null)
                                continue;
                            ReferenceCollection references = (ReferenceCollection) values[j];
                            if (references.includes(focusQualifiedNames, null, null)) {
                                return true;
                            }
                        }
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    } catch (JavaModelException e) {
        return false;
    }
}

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

License:Open Source License

public IPath[] enclosingProjectsAndJars() {
    IPath[] result = this.enclosingPaths;
    if (result != null) {
        return result;
    }// w w w . j  av  a  2  s .c o  m
    long start = BasicSearchEngine.VERBOSE ? System.currentTimeMillis() : -1;
    try {
        IJavaProject[] projects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProjects();
        // use a linked set to preserve the order during search: see bug 348507
        Set paths = new LinkedHashSet(projects.length * 2);
        for (int i = 0, length = projects.length; i < length; i++) {
            JavaProject javaProject = (JavaProject) projects[i];

            // Add project full path
            IPath projectPath = javaProject.getProject().getFullPath();
            paths.add(projectPath);
        }

        // add the project source paths first in a separate loop above
        // to ensure source files always get higher precedence during search.
        // see bug 348507

        for (int i = 0, length = projects.length; i < length; i++) {
            JavaProject javaProject = (JavaProject) projects[i];

            // Add project libraries paths
            IClasspathEntry[] entries = javaProject.getResolvedClasspath();
            for (int j = 0, eLength = entries.length; j < eLength; j++) {
                IClasspathEntry entry = entries[j];
                if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                    IPath path = entry.getPath();
                    Object target = JavaModel.getTarget(path, false/*don't check existence*/);
                    if (target instanceof IFolder) // case of an external folder
                        path = ((IFolder) target).getFullPath();
                    paths.add(entry.getPath());
                }
            }
        }
        result = new IPath[paths.size()];
        paths.toArray(result);
        return this.enclosingPaths = result;
    } catch (JavaModelException e) {
        Util.log(e, "Exception while computing workspace scope's enclosing projects and jars"); //$NON-NLS-1$
        return new IPath[0];
    } finally {
        if (BasicSearchEngine.VERBOSE) {
            long time = System.currentTimeMillis() - start;
            int length = result == null ? 0 : result.length;
            Util.verbose("JavaWorkspaceScope.enclosingProjectsAndJars: " + length + " paths computed in " + time //$NON-NLS-1$//$NON-NLS-2$
                    + "ms."); //$NON-NLS-1$
        }
    }
}

From source file:com.motorola.studio.android.packaging.ui.export.PackageExportWizardArea.java

License:Apache License

/**
 * do the finish: Create the package for each selected descriptor
 *///  w w w  . j  a  v  a  2  s  .c  o  m
public boolean performFinish() {
    final boolean[] finished = { false };
    boolean destOK = false;
    final MultiStatus status = new MultiStatus(PackagingUIPlugin.PLUGIN_ID, IStatus.OK, "", null); //$NON-NLS-1$
    ProgressMonitorDialog monitorDialog = null;
    String DESCRIPTION_TO_LOG = StudioLogger.DESCRIPTION_DEFAULT;

    try {
        destOK = checkDestination();
    } catch (CoreException e) {
        status.add(e.getStatus());
    }

    if (destOK) {
        monitorDialog = new ProgressMonitorDialog(parentComposite.getShell());
        try {
            monitorDialog.run(false, false, new IRunnableWithProgress() {

                @Override
                public void run(IProgressMonitor aMonitor)
                        throws InvocationTargetException, InterruptedException {
                    int finishSize = getSelectedItems().size() * PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER;
                    SubMonitor monitor = SubMonitor.convert(aMonitor);
                    monitor.beginTask(Messages.PACKAGE_EXPORT_WIZARD_AREA_FINISH_ACTION_LABEL, finishSize);
                    IPath exportDestinationFolder = new Path(destinationText.getText());
                    IPath exportDestinationFile = null;

                    for (TreeItem item : getSelectedItems()) {
                        // get the eclipse project as a java project to get
                        // the project
                        // destination
                        IProject eclipseProject = (IProject) item.getData();
                        try {
                            monitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER / 4);

                            JavaProject javaProject = new JavaProject();
                            javaProject.setProject(eclipseProject);

                            // find all packages built by Android builder
                            Map<String, String> apkConfigurations = SdkUtils
                                    .getAPKConfigurationsForProject(eclipseProject);

                            Set<String> apkConfNames = new HashSet<String>();
                            if (apkConfigurations != null) {
                                apkConfNames.addAll(apkConfigurations.keySet());
                            }
                            apkConfNames.add(""); // the default package //$NON-NLS-1$

                            SubMonitor submonitor = monitor
                                    .newChild(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER / 4);

                            submonitor.beginTask(Messages.PACKAGE_EXPORT_WIZARD_AREA_EXPORTING_ACTION_LABEL,
                                    3 * PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER * apkConfNames.size());

                            for (String apkConfName : apkConfNames) {

                                String apkName = eclipseProject.getName() + (apkConfName.isEmpty() ? apkConfName
                                        : "-" //$NON-NLS-1$ //$NON-NLS-2$
                                                + apkConfName);
                                if (defaultDestination.getSelection()) {
                                    exportDestinationFolder = eclipseProject.getLocation()
                                            .append(CertificateManagerActivator.PACKAGE_PROJECT_DESTINATION);
                                }
                                exportDestinationFile = exportDestinationFolder.append(apkName)
                                        .addFileExtension(CertificateManagerActivator.PACKAGE_EXTENSION);
                                File file = exportDestinationFile.toFile();
                                submonitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER);

                                //always export unsigned package
                                AdtUtils.exportUnsignedReleaseApk(javaProject.getProject(), file, submonitor);

                                submonitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER);

                                if (signCheckBox.getSelection()) {
                                    //sign the package if required
                                    IStatus signStatus = signPackage(eclipseProject, file);
                                    status.add(signStatus);
                                }

                                //zipalign the file and we are done exporting the package
                                PackageFile.zipAlign(file);

                                submonitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER);
                            }
                            submonitor.done();
                        } catch (CoreException e) {
                            StudioLogger.error(PackageExportWizardArea.class,
                                    "Error while building project or getting project output folder" //$NON-NLS-1$
                                            + eclipseProject.getName(),
                                    e);
                            status.add(new Status(IStatus.ERROR, PackagingUIPlugin.PLUGIN_ID,
                                    Messages.PACKAGE_EXPORT_WIZARD_AREA_ERROR_PROJECT_BUILD + " " //$NON-NLS-1$
                                            + eclipseProject.getName()));
                        } finally {
                            try {
                                eclipseProject.refreshLocal(IResource.DEPTH_INFINITE,
                                        monitor.newChild(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER / 4));
                            } catch (CoreException e) {
                                // do nothing
                            }
                        }
                        monitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER / 4);
                    }
                    finished[0] = true;

                }
            });
        } catch (Exception e) {
            StudioLogger.warn("Error finishing package export.");
        }
    }

    if (!status.isOK()) {
        status.getMessage();
        DESCRIPTION_TO_LOG = Messages.PACKAGE_EXPORT_WIZARD_AREA_READONLY_TITLE;
        ErrorDialog.openError(parentComposite.getShell(), Messages.PACKAGE_EXPORT_WIZARD_AREA_READONLY_TITLE,
                Messages.PACKAGE_EXPORT_WIZARD_AREA_READONLY_MESSAGE, status);
    }

    // Saving usage data
    try {
        StudioLogger.collectUsageData(StudioLogger.WHAT_APP_MANAGEMENT_PACKAGE,
                StudioLogger.KIND_APP_MANAGEMENT, DESCRIPTION_TO_LOG, PackagingUIPlugin.PLUGIN_ID,
                PackagingUIPlugin.getDefault().getBundle().getVersion().toString());
    } catch (Throwable e) {
        // Do nothing, but error on the log should never prevent app from
        // working
    }

    return finished[0];
}

From source file:com.motorola.studio.android.propertypage.MotodevStudioPropertyPage.java

License:Apache License

/**
 * Checks if project have Proguard settings and, if so, update checkbox state 
 *//*from  w  w  w  . j a  va2s .c  o  m*/
private void setDefaultObfuscate() {
    project = null;
    if (getElement() instanceof IResource) {
        IResource resource = (IResource) getElement();
        if (resource != null) {
            project = resource.getProject();
        }
    } else if (getElement() instanceof JavaProject) {
        JavaProject javaProject = (JavaProject) getElement();
        project = javaProject.getProject();
    }

    if (project != null) {
        obfuscateCkbox.setSelection(ObfuscatorManager.isProguardSet(project));
    } else {
        //project not found
        obfuscateCkbox.setSelection(false);
    }
}

From source file:com.motorola.studio.android.propertypage.MotodevStudioPropertyPage.java

License:Apache License

/**
 * Add or remove Proguard setting depending on obfuscateCkbox checkbox state
 *//*w w w .j a  v a 2  s  .c o  m*/
@Override
public boolean performOk() {
    IProject project = null;
    Boolean needToObfuscate = obfuscateCkbox.getSelection();
    if (getElement() instanceof IResource) {
        IResource resource = (IResource) getElement();
        if (resource != null) {
            project = resource.getProject();
        }
    } else if (getElement() instanceof JavaProject) {
        JavaProject javaProject = (JavaProject) getElement();
        project = javaProject.getProject();
    }
    if (project != null) {
        IStatus status = null;
        try {
            if (needToObfuscate.booleanValue()) {
                status = ObfuscatorManager.obfuscate(project, null);
            } else {
                status = ObfuscatorManager.unobfuscate(project);
            }
            project.refreshLocal(IResource.DEPTH_INFINITE, null);
        } catch (Exception e) {
            EclipseUtils.showErrorDialog(AndroidNLS.MotodevStudioPropertyPage_ChangeProguardSettingsProblem,
                    status.getMessage(), status);
            StudioLogger.error(MotodevStudioPropertyPage.class, e.getMessage(), e);
            return false;
        }
    }
    return true;
}

From source file:net.sf.j2s.core.builder.NameEnvironment.java

License:Open Source License

private void computeClasspathLocations(IWorkspaceRoot root, JavaProject javaProject,
        SimpleLookupTable binaryLocationsPerProject) throws CoreException {

    /* Update cycle marker */
    IMarker cycleMarker = javaProject.getCycleMarker();
    if (cycleMarker != null) {
        int severity = JavaCore.ERROR.equals(javaProject.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true))
                ? IMarker.SEVERITY_ERROR
                : IMarker.SEVERITY_WARNING;
        if (severity != cycleMarker.getAttribute(IMarker.SEVERITY, severity))
            cycleMarker.setAttribute(IMarker.SEVERITY, severity);
    }// w w w.j a v  a  2  s .  c  o m

    IClasspathEntry[] classpathEntries = javaProject.getExpandedClasspath();
    ArrayList sLocations = new ArrayList(classpathEntries.length);
    ArrayList bLocations = new ArrayList(classpathEntries.length);
    nextEntry: for (int i = 0, l = classpathEntries.length; i < l; i++) {
        ClasspathEntry entry = (ClasspathEntry) classpathEntries[i];
        IPath path = entry.getPath();
        Object target = JavaModel.getTarget(path, true);
        if (target == null)
            continue nextEntry;

        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_SOURCE:
            if (!(target instanceof IContainer))
                continue nextEntry;
            IPath outputPath = entry.getOutputLocation() != null ? entry.getOutputLocation()
                    : javaProject.getOutputLocation();
            IContainer outputFolder;
            if (outputPath.segmentCount() == 1) {
                outputFolder = javaProject.getProject();
            } else {
                outputFolder = root.getFolder(outputPath);
                if (!outputFolder.exists())
                    createOutputFolder(outputFolder);
            }
            sLocations.add(ClasspathLocation.forSourceFolder((IContainer) target, outputFolder,
                    entry.fullInclusionPatternChars(), entry.fullExclusionPatternChars(),
                    entry.ignoreOptionalProblems()));
            continue nextEntry;

        case IClasspathEntry.CPE_PROJECT:
            if (!(target instanceof IProject))
                continue nextEntry;
            IProject prereqProject = (IProject) target;
            if (!JavaProject.hasJavaNature(prereqProject))
                continue nextEntry; // if project doesn't have java nature or is not accessible

            JavaProject prereqJavaProject = (JavaProject) JavaCore.create(prereqProject);
            IClasspathEntry[] prereqClasspathEntries = prereqJavaProject.getRawClasspath();
            ArrayList seen = new ArrayList();
            nextPrereqEntry: for (int j = 0, m = prereqClasspathEntries.length; j < m; j++) {
                IClasspathEntry prereqEntry = prereqClasspathEntries[j];
                if (prereqEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    Object prereqTarget = JavaModel.getTarget(prereqEntry.getPath(), true);
                    if (!(prereqTarget instanceof IContainer))
                        continue nextPrereqEntry;
                    IPath prereqOutputPath = prereqEntry.getOutputLocation() != null
                            ? prereqEntry.getOutputLocation()
                            : prereqJavaProject.getOutputLocation();
                    IContainer binaryFolder = prereqOutputPath.segmentCount() == 1 ? (IContainer) prereqProject
                            : (IContainer) root.getFolder(prereqOutputPath);
                    if (binaryFolder.exists() && !seen.contains(binaryFolder)) {
                        seen.add(binaryFolder);
                        ClasspathLocation bLocation = ClasspathLocation.forBinaryFolder(binaryFolder, true,
                                entry.getAccessRuleSet());
                        bLocations.add(bLocation);
                        if (binaryLocationsPerProject != null) { // normal builder mode
                            ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject
                                    .get(prereqProject);
                            if (existingLocations == null) {
                                existingLocations = new ClasspathLocation[] { bLocation };
                            } else {
                                int size = existingLocations.length;
                                System.arraycopy(existingLocations, 0,
                                        existingLocations = new ClasspathLocation[size + 1], 0, size);
                                existingLocations[size] = bLocation;
                            }
                            binaryLocationsPerProject.put(prereqProject, existingLocations);
                        }
                    }
                }
            }
            continue nextEntry;

        case IClasspathEntry.CPE_LIBRARY:
            if (target instanceof IResource) {
                IResource resource = (IResource) target;
                ClasspathLocation bLocation = null;
                if (resource instanceof IFile) {
                    AccessRuleSet accessRuleSet = (JavaCore.IGNORE
                            .equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
                            && JavaCore.IGNORE.equals(
                                    javaProject.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true)))
                                            ? null
                                            : entry.getAccessRuleSet();
                    bLocation = ClasspathLocation.forLibrary((IFile) resource, accessRuleSet);
                } else if (resource instanceof IContainer) {
                    AccessRuleSet accessRuleSet = (JavaCore.IGNORE
                            .equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
                            && JavaCore.IGNORE.equals(
                                    javaProject.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true)))
                                            ? null
                                            : entry.getAccessRuleSet();
                    bLocation = ClasspathLocation.forBinaryFolder((IContainer) target, false, accessRuleSet); // is library folder not output folder
                }
                bLocations.add(bLocation);
                if (binaryLocationsPerProject != null) { // normal builder mode
                    IProject p = resource.getProject(); // can be the project being built
                    ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject
                            .get(p);
                    if (existingLocations == null) {
                        existingLocations = new ClasspathLocation[] { bLocation };
                    } else {
                        int size = existingLocations.length;
                        System.arraycopy(existingLocations, 0,
                                existingLocations = new ClasspathLocation[size + 1], 0, size);
                        existingLocations[size] = bLocation;
                    }
                    binaryLocationsPerProject.put(p, existingLocations);
                }
            } else if (target instanceof File) {
                AccessRuleSet accessRuleSet = (JavaCore.IGNORE
                        .equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
                        && JavaCore.IGNORE.equals(
                                javaProject.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true))) ? null
                                        : entry.getAccessRuleSet();
                bLocations.add(ClasspathLocation.forLibrary(path.toString(), accessRuleSet));
            }
            continue nextEntry;
        }
    }

    // now split the classpath locations... place the output folders ahead of the other .class file folders & jars
    ArrayList outputFolders = new ArrayList(1);
    this.sourceLocations = new ClasspathMultiDirectory[sLocations.size()];
    if (!sLocations.isEmpty()) {
        sLocations.toArray(this.sourceLocations);

        // collect the output folders, skipping duplicates
        next: for (int i = 0, l = this.sourceLocations.length; i < l; i++) {
            ClasspathMultiDirectory md = this.sourceLocations[i];
            IPath outputPath = md.binaryFolder.getFullPath();
            for (int j = 0; j < i; j++) { // compare against previously walked source folders
                if (outputPath.equals(this.sourceLocations[j].binaryFolder.getFullPath())) {
                    md.hasIndependentOutputFolder = this.sourceLocations[j].hasIndependentOutputFolder;
                    continue next;
                }
            }
            outputFolders.add(md);

            // also tag each source folder whose output folder is an independent folder & is not also a source folder
            for (int j = 0, m = this.sourceLocations.length; j < m; j++)
                if (outputPath.equals(this.sourceLocations[j].sourceFolder.getFullPath()))
                    continue next;
            md.hasIndependentOutputFolder = true;
        }
    }

    // combine the output folders with the binary folders & jars... place the output folders before other .class file folders & jars
    this.binaryLocations = new ClasspathLocation[outputFolders.size() + bLocations.size()];
    int index = 0;
    for (int i = 0, l = outputFolders.size(); i < l; i++)
        this.binaryLocations[index++] = (ClasspathLocation) outputFolders.get(i);
    for (int i = 0, l = bLocations.size(); i < l; i++)
        this.binaryLocations[index++] = (ClasspathLocation) bLocations.get(i);
}

From source file:org.codehaus.jdt.groovy.integration.internal.GroovyEventHandler.java

License:Open Source License

public void handle(JavaProject javaProject, String event) {
    if (event.equals("cleanOutputFolders")) {
        if (javaProject != null) {
            GroovyParser.tidyCache(javaProject.getProject().getName());
        }/*from  w  w  w.jav a2  s .  co m*/
    } else if (event.equals("close")) {
        if (javaProject != null) {
            String projectName = javaProject.getProject().getName();
            GroovyParser.closeClassLoader(projectName);
            GroovyParser.tidyCache(projectName);
        }
    }
}

From source file:org.codehaus.jdt.groovy.model.GroovyCompilationUnit.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes", "nls", "restriction" })
@Override/*from  w ww .jav a  2s. co m*/
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements,
        IResource underlyingResource) throws JavaModelException {
    try {
        depth.set(depth.get() + 1);

        // if (!isOnBuildPath()) {
        // return false;
        // }

        if (GroovyLogManager.manager.hasLoggers()) {
            GroovyLogManager.manager.log(TraceCategory.COMPILER, "Build Structure starting for " + this.name);
            GroovyLogManager.manager
                    .logStart("Build structure: " + name + " : " + Thread.currentThread().getName());
        }

        CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;

        // ensure buffer is opened
        IBuffer buffer = getBufferManager().getBuffer(this);
        if (buffer == null) {
            openBuffer(pm, unitInfo); // open buffer independently from the
            // info, since we are building the info
        }

        // generate structure and compute syntax problems if needed
        GroovyCompilationUnitStructureRequestor requestor = new GroovyCompilationUnitStructureRequestor(this,
                unitInfo, newElements);
        JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
        JavaProject project = (JavaProject) getJavaProject();

        // determine what kind of buildStructure we are doing
        boolean createAST;
        int reconcileFlags;
        boolean resolveBindings;
        HashMap problems;
        if (info instanceof ASTHolderCUInfo) {
            ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info;
            createAST = ((Integer) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "astLevel", //$NON-NLS-1$
                    astHolder)).intValue() != NO_AST;
            resolveBindings = ((Boolean) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class,
                    "resolveBindings", astHolder)).booleanValue();
            reconcileFlags = ((Integer) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "reconcileFlags", //$NON-NLS-1$
                    astHolder)).intValue();
            problems = (HashMap) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "problems", astHolder);
        } else {
            createAST = false;
            resolveBindings = false;
            reconcileFlags = 0;
            problems = null;
        }

        boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null
                && JavaProject.hasJavaNature(project.getProject());
        IProblemFactory problemFactory = new DefaultProblemFactory();

        // compiler options
        Map<String, String> options = (project == null ? JavaCore.getOptions() : project.getOptions(true));
        if (!computeProblems) {
            // disable task tags checking to speed up parsing
            options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
        }

        // FIXASC deal with the case of project==null to reduce duplication in this next line and call to setGroovyClasspath
        // Required for Groovy, but not for Java
        options.put(CompilerOptions.OPTIONG_BuildGroovyFiles, CompilerOptions.ENABLED);

        CompilerOptions compilerOptions = new CompilerOptions(options);

        if (project != null) {
            CompilerUtils.setGroovyClasspath(compilerOptions, project);
        }

        // Required for Groovy, but not for Java
        ProblemReporter reporter = new ProblemReporter(new GroovyErrorHandlingPolicy(!computeProblems),
                compilerOptions, new DefaultProblemFactory());

        SourceElementParser parser = new MultiplexingSourceElementRequestorParser(reporter, requestor, /*
                                                                                                       * not needed if
                                                                                                       * computing groovy only
                                                                                                       */
                problemFactory, compilerOptions, true/* report local declarations */, !createAST /*
                                                                                                 * optimize string literals only if not
                                                                                                 * creating a DOM AST
                                                                                                 */);
        parser.reportOnlyOneSyntaxError = !computeProblems;
        // maybe not needed for groovy, but I don't want to find out.
        parser.setMethodsFullRecovery(true);
        parser.setStatementsRecovery((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);

        if (!computeProblems && !resolveBindings && !createAST) // disable javadoc parsing if not computing problems, not
            // resolving
            // and not creating ast
            parser.javadocParser.checkDocComment = false;
        requestor.setParser(parser);

        // update timestamp (might be IResource.NULL_STAMP if original does not
        // exist)
        if (underlyingResource == null) {
            underlyingResource = getResource();
        }
        // underlying resource is null in the case of a working copy on a class
        // file in a jar
        if (underlyingResource != null) {
            ReflectionUtils.setPrivateField(CompilationUnitElementInfo.class, "timestamp", unitInfo, //$NON-NLS-1$
                    underlyingResource.getModificationStamp());
        }

        GroovyCompilationUnitDeclaration compilationUnitDeclaration = null;
        CompilationUnit source = cloneCachingContents();
        try {
            // GROOVY
            // note that this is a slightly different approach than taken by super.buildStructure
            // in super.buildStructure, there is a test here to see if computeProblems is true.
            // if false, then parser.parserCompilationUnit is called.
            // this will not work for Groovy because we need to ensure bindings are resolved
            // for many operations (content assist and code select) to work.
            // So, for groovy, always use CompilationUnitProblemFinder.process and then process problems
            // separately only if necessary
            // addendum (GRECLIPSE-942). The testcase for that bug includes a package with 200
            // types in that refer to each other in a chain, through field references. If a reconcile
            // references the top of the chain we can go through a massive number of recursive calls into
            // this buildStructure for each one. The 'full' parse (with bindings) is only required for
            // the top most (regardless of the computeProblems setting) and so we track how many recursive
            // calls we have made - if we are at depth 2 we do what JDT was going to do (the quick thing).
            if (computeProblems || depth.get() < 2) {
                if (problems == null) {
                    // report problems to the problem requestor
                    problems = new HashMap();
                    compilationUnitDeclaration = (GroovyCompilationUnitDeclaration) CompilationUnitProblemFinder
                            .process(source, parser, this.owner, problems, createAST, reconcileFlags, pm);
                    if (computeProblems) {
                        try {
                            perWorkingCopyInfo.beginReporting();
                            for (Iterator iteraror = problems.values().iterator(); iteraror.hasNext();) {
                                CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror
                                        .next();
                                if (categorizedProblems == null)
                                    continue;
                                for (int i = 0, length = categorizedProblems.length; i < length; i++) {
                                    perWorkingCopyInfo.acceptProblem(categorizedProblems[i]);
                                }
                            }
                        } finally {
                            perWorkingCopyInfo.endReporting();
                        }
                    }
                } else {
                    // collect problems
                    compilationUnitDeclaration = (GroovyCompilationUnitDeclaration) CompilationUnitProblemFinder
                            .process(source, parser, this.owner, problems, createAST, reconcileFlags, pm);
                }
            } else {
                compilationUnitDeclaration = (GroovyCompilationUnitDeclaration) parser
                        .parseCompilationUnit(source, true /* full parse to find local elements */, pm);
            }

            // GROOVY
            // if this is a working copy, then we have more work to do
            maybeCacheModuleNode(perWorkingCopyInfo, compilationUnitDeclaration);

            // create the DOM AST from the compiler AST
            if (createAST) {
                org.eclipse.jdt.core.dom.CompilationUnit ast;
                try {
                    ast = AST.convertCompilationUnit(AST.JLS3, compilationUnitDeclaration, options,
                            computeProblems, source, reconcileFlags, pm);
                    ReflectionUtils.setPrivateField(ASTHolderCUInfo.class, "ast", info, ast); //$NON-NLS-1$
                } catch (OperationCanceledException e) {
                    // catch this exception so as to not enter the catch(RuntimeException e) below
                    // might need to do the same for AbortCompilation
                    throw e;
                } catch (IllegalArgumentException e) {
                    // if necessary, we can do some better reporting here.
                    Util.log(e, "Problem with build structure: Offset for AST node is incorrect in " //$NON-NLS-1$
                            + this.getParent().getElementName() + "." + getElementName()); //$NON-NLS-1$
                } catch (Exception e) {
                    Util.log(e, "Problem with build structure for " + this.getElementName()); //$NON-NLS-1$
                }
            }
        } catch (OperationCanceledException e) {
            // catch this exception so as to not enter the catch(RuntimeException e) below
            // might need to do the same for AbortCompilation
            throw e;
        } catch (JavaModelException e) {
            // GRECLIPSE-1480 don't log element does not exist exceptions. since this could occur when element is in a non-java
            // project
            if (e.getStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST
                    || this.getJavaProject().exists()) {
                Util.log(e, "Problem with build structure for " + this.getElementName()); //$NON-NLS-1$
            }
        } catch (Exception e) {
            // GROOVY: The groovy compiler does not handle broken code well in many situations
            // use this general catch clause so that exceptions thrown by broken code
            // do not bubble up the stack.
            Util.log(e, "Problem with build structure for " + this.getElementName()); //$NON-NLS-1$
        } finally {
            if (compilationUnitDeclaration != null) {
                compilationUnitDeclaration.cleanUp();
            }
        }
        return unitInfo.isStructureKnown();
    } finally {
        depth.set(depth.get() - 1);
        if (GroovyLogManager.manager.hasLoggers()) {
            GroovyLogManager.manager.logEnd(
                    "Build structure: " + name + " : " + Thread.currentThread().getName(),
                    TraceCategory.COMPILER);
        }
    }
}