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

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

Introduction

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

Prototype

IResource getCorrespondingResource() throws JavaModelException;

Source Link

Document

Returns the resource that corresponds directly to this element, or null if there is no resource that corresponds to this element.

Usage

From source file:at.bestsolution.efxclipse.tooling.fxgraph.ui.contentassist.FXGraphProposalProvider.java

License:Open Source License

@Override
public void completeLocationValueProperty_Value(EObject model, Assignment assignment,
        final ContentAssistContext context, final ICompletionProposalAcceptor acceptor) {
    IJavaProject javaProject = projectProvider.getJavaProject(model.eResource().getResourceSet());

    try {// ww w. j av  a2  s .  c  om
        for (IPackageFragmentRoot r : javaProject.getPackageFragmentRoots()) {
            if (r.getCorrespondingResource() != null) {
                final int count = r.getCorrespondingResource().getProjectRelativePath().segmentCount();
                r.getCorrespondingResource().accept(new IResourceVisitor() {

                    @Override
                    public boolean visit(IResource resource) throws CoreException {
                        if (resource.getType() == IResource.FOLDER || resource.getType() == IResource.PROJECT) {
                            return true;
                        } else if (resource.getType() == IResource.FILE && !resource.isLinked()) {
                            String extension = resource.getProjectRelativePath().getFileExtension();
                            if (extension.equals("png") || extension.equals("jpg") || extension.equals("gif")) {
                                IPath p = resource.getProjectRelativePath().removeFirstSegments(count);
                                String prefix = "\"/"
                                        + (p.segmentCount() > 1 ? p.removeLastSegments(1).toString()
                                                : p.toString())
                                        + "/" + context.getPrefix();
                                ICompletionProposal proposal = createCompletionProposal(
                                        "\"/" + p.toString() + "\"", new StyledString("/" + p.toString()), null,
                                        getPriorityHelper().getDefaultPriority(), prefix, context);
                                acceptor.accept(proposal);
                            }
                        }

                        return false;
                    }
                });
            }
        }
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:co.turnus.widgets.util.WidgetsUtils.java

License:Open Source License

/**
 * Returns the list of source folders of the given project as a list of
 * absolute workspace paths./* w  ww. j ava 2 s  . c  o m*/
 * 
 * @param project
 *            a project
 * @return a list of absolute workspace paths
 */
public static List<IFolder> getSourceFolders(IProject project) {
    List<IFolder> srcFolders = new ArrayList<IFolder>();

    IJavaProject javaProject = JavaCore.create(project);
    if (!javaProject.exists()) {
        return srcFolders;
    }

    // iterate over package roots
    try {
        for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
            IResource resource = root.getCorrespondingResource();
            if (resource != null && resource.getType() == IResource.FOLDER) {
                srcFolders.add((IFolder) resource);
            }
        }
    } catch (CoreException e) {
        e.printStackTrace();
    }

    return srcFolders;
}

From source file:com.centurylink.mdw.plugin.ResourceWrapper.java

License:Apache License

public IFolder getFolder() throws JavaModelException {
    IFolder folder = null;//from   w w w . j av  a2s .c o m
    if (adaptable != null) {
        folder = (IFolder) adaptable.getAdapter(IFolder.class);
        if (folder == null) {
            // try as java element
            IPackageFragmentRoot pkgFragmentRoot = (IPackageFragmentRoot) adaptable
                    .getAdapter(IPackageFragmentRoot.class);
            if (pkgFragmentRoot != null) {
                IResource res = pkgFragmentRoot.getCorrespondingResource();
                folder = (IFolder) res.getAdapter(IFolder.class);
            } else {
                IPackageFragment pkgFragment = (IPackageFragment) adaptable.getAdapter(IPackageFragment.class);
                if (pkgFragment != null) {
                    IResource res = pkgFragment.getCorrespondingResource();
                    folder = (IFolder) res.getAdapter(IFolder.class);
                }
            }
        }
    } else {
        if (resourceObj instanceof IFolder) {
            folder = (IFolder) resourceObj;
        } else if (resourceObj instanceof IPackageFragmentRoot) {
            IPackageFragmentRoot pkgFragmentRoot = (IPackageFragmentRoot) resourceObj;
            IResource res = pkgFragmentRoot.getCorrespondingResource();
            folder = (IFolder) res.getAdapter(IFolder.class);
        } else if (resourceObj instanceof IPackageFragment) {
            IPackageFragment pkgFragment = (IPackageFragment) resourceObj;
            IResource res = pkgFragment.getCorrespondingResource();
            folder = (IFolder) res.getAdapter(IFolder.class);
        }
    }
    return folder;
}

From source file:com.google.test.metric.eclipse.internal.util.JavaProjectHelper.java

License:Apache License

public List<String> getAllJavaPackages(IJavaProject javaProject) throws JavaModelException, CoreException {
    List<String> allJavaPackages = new ArrayList<String>();
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (IPackageFragmentRoot root : roots) {
        if (!root.isArchive()) {
            IResource rootResource = root.getCorrespondingResource();
            String rootURL = rootResource.getFullPath().toOSString();
            rootResource.accept(new JavaPackageVisitor(allJavaPackages, rootURL), IContainer.NONE);
        }/*from   w  ww  . jav a 2 s  .c  o  m*/
    }
    return allJavaPackages;
}

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

License:Apache License

private void createMarkersFromClassIssues(List<ClassIssues> classIssues, IJavaProject javaProject)
        throws CoreException {
    javaProject.getProject().deleteMarkers(TestabilityConstants.TESTABILITY_COLLABORATOR_MARKER_TYPE, true,
            IResource.DEPTH_INFINITE);//from   ww  w .  j av  a2s  .  c  o  m
    javaProject.getProject().deleteMarkers(TestabilityConstants.TESTABILITY_CONSTRUCTOR_MARKER_TYPE, true,
            IResource.DEPTH_INFINITE);
    javaProject.getProject().deleteMarkers(TestabilityConstants.TESTABILITY_DIRECT_COST_MARKER_TYPE, true,
            IResource.DEPTH_INFINITE);
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    List<IPath> sourceFolderPaths = new ArrayList<IPath>();
    for (IPackageFragmentRoot root : roots) {
        if (!root.isArchive()) {
            IResource rootResource = root.getCorrespondingResource();
            sourceFolderPaths.add(rootResource.getFullPath().removeFirstSegments(1));
        }
    }
    for (ClassIssues classIssue : classIssues) {
        IResource resource = getAbsolutePathFromJavaFile(classIssue.getClassName(), sourceFolderPaths,
                javaProject.getProject());
        if (resource != null) {
            for (Issue issue : classIssue.getMostImportantIssues()) {
                Map<String, Object> attributes = new HashMap<String, Object>();
                attributes.put(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
                attributes.put(IMarker.LINE_NUMBER, issue.getLocation().getLineNumber());
                attributes.put(IMarker.MESSAGE, retriever.getSuggestion(issue.getType(), issue.getSubType()));
                IssueType issueType = issue.getType();
                attributes.put(TestabilityConstants.ISSUE_TYPE, issue.getType().toString());
                String markerType = null;
                if (IssueType.COLLABORATOR.equals(issueType)) {
                    markerType = TestabilityConstants.TESTABILITY_COLLABORATOR_MARKER_TYPE;
                } else if (IssueType.CONSTRUCTION.equals(issueType)) {
                    markerType = TestabilityConstants.TESTABILITY_CONSTRUCTOR_MARKER_TYPE;
                } else if (IssueType.DIRECT_COST.equals(issueType)) {
                    markerType = TestabilityConstants.TESTABILITY_DIRECT_COST_MARKER_TYPE;
                }
                if (markerType != null) {
                    MarkerUtilities.createMarker(resource, attributes, markerType);
                }
            }
        } else {
            logger.logException("No Resource found for Class : " + classIssue.getClassName(), null);
        }
    }
}

From source file:edu.pdx.cs.multiview.test.JavaTestProject.java

License:Open Source License

public IFolder createFolder(IPackageFragmentRoot root, String fname) throws JavaModelException, CoreException {
    IFolder folder = (IFolder) root.getCorrespondingResource();
    IFolder ret = folder.getFolder(fname);
    if (!folder.exists()) {
        monitor.reset();/*w ww. ja  va  2  s .c  o m*/
        ret.create(true, true, monitor);
        monitor.waitForCompletion();
    }
    return ret;
}

From source file:in.cypal.studio.gwt.ui.refactor.DeleteRemoteServiceChange.java

License:Apache License

public Change perform(IProgressMonitor pm) throws CoreException {

    IPackageFragment clientPackage = (IPackageFragment) compilationUnit.getParent();
    ICompilationUnit asyncInterface = clientPackage
            .getCompilationUnit(getRemoteInterfaceName().concat("Async.java"));
    IResource asyncFile = asyncInterface.getResource();
    if (asyncFile.exists())
        asyncFile.delete(true, null);//from w  w  w.  j ava 2 s .c o m

    IPackageFragmentRoot sourceFolder = (IPackageFragmentRoot) clientPackage.getParent();
    IJavaElement[] subPackages = sourceFolder.getChildren();
    for (int i = 0; i < subPackages.length; i++) {

        IPackageFragment packageFragment = (IPackageFragment) subPackages[i];
        if (subPackages[i].getElementName().endsWith(Constants.SERVER_PACKAGE)) {
            ICompilationUnit implClass = packageFragment
                    .getCompilationUnit(getRemoteInterfaceName().concat("Impl.java"));
            IResource implFile = implClass.getResource();
            if (implFile.exists()) {
                implFile.delete(true, null);
            }
        }
    }

    IFolder moduleFolder = (IFolder) sourceFolder.getCorrespondingResource();
    moduleFolder.accept(new IResourceVisitor() {

        public boolean visit(IResource resource) throws CoreException {

            if (Util.isModuleXml(resource)) {
                try {
                    deleteFromGwtXml((IFile) resource, null);
                } catch (Exception e) {
                    Activator.logException(e);
                }
            }
            return true;
        }

    });

    deleteFromWebXml(null);

    return null;
}

From source file:org.codecover.eclipse.builder.CodeCoverCompilationParticipant.java

License:Open Source License

/**
 * This method is called for each project separately.
 *///www .ja  v a  2s . c  om
@Override
public void buildStarting(BuildContext[] files, boolean isBatch) {
    if (files.length == 0) {
        return;
    }

    final IProject iProject = files[0].getFile().getProject();
    final IPath projectFullPath = iProject.getFullPath();
    final IPath projectLocation = iProject.getLocation();
    final String projectFolderLocation = iProject.getLocation().toOSString();
    final Queue<SourceTargetContainer> sourceTargetContainers = new LinkedList<SourceTargetContainer>();
    final String instrumentedFolderLocation = CodeCoverPlugin.getDefault()
            .getPathToInstrumentedSources(iProject).toOSString();

    // try to get all source folders
    final Queue<String> possibleSourceFolders = new LinkedList<String>();
    try {
        final IJavaProject javaProject = JavaCore.create(iProject);
        for (IPackageFragmentRoot thisRoot : javaProject.getAllPackageFragmentRoots()) {
            IResource resource = thisRoot.getCorrespondingResource();
            if (resource != null) {
                possibleSourceFolders.add(resource.getLocation().toOSString());
            }
        }
    } catch (JavaModelException e) {
        eclipseLogger.fatal("JavaModelException in CompilationParticipant", e); //$NON-NLS-1$
        return;
    }

    InstrumentableItemsManager instrumentableItemsManager = CodeCoverPlugin.getDefault()
            .getInstrumentableItemsManager();
    TSContainerManager tscManager = CodeCoverPlugin.getDefault().getTSContainerManager();

    // //////////////////////////////////////////////////////////////////////
    // CREATE THE SOURCE TARGET CONTAINERS AND COPY THE UNINSTRUMENTED
    // FILES TO THE INSTRUMENTEDFOLDERLOCATION
    // //////////////////////////////////////////////////////////////////////
    fillSourceTargetContainers(files, possibleSourceFolders, sourceTargetContainers, instrumentedFolderLocation,
            eclipseLogger, instrumentableItemsManager);

    // //////////////////////////////////////////////////////////////////////
    // SEARCH IN ALL TSC OF THIS PROJECT IF A TSC CAN BE REUSED
    // //////////////////////////////////////////////////////////////////////

    TestSessionContainer tsc;
    if (SEARCH_IN_ALL_TSC) {
        tsc = searchUseableTSC(iProject, files, instrumentableItemsManager, tscManager);
    } else {
        tsc = getUseableTSC(files, instrumentableItemsManager, tscManager);
    }

    // //////////////////////////////////////////////////////////////////////
    // PREPARE INSTRUMENTATION
    // //////////////////////////////////////////////////////////////////////
    InstrumenterDescriptor descriptor = new org.codecover.instrumentation.java15.InstrumenterDescriptor();
    if (descriptor == null) {
        eclipseLogger.fatal("NullPointerException in CompilationParticipant"); //$NON-NLS-1$
    }

    // check whether TSC's criteria match
    // with the selected criteria of the project
    if (tsc != null) {
        Set<Criterion> tscCriteria = tsc.getCriteria();

        for (Criterion criterion : tscCriteria) {
            if (!CodeCoverPlugin.getCriterionSelectedState(iProject, criterion)) {
                // the TSC uses a criterion which is not selected for the project
                // therefore it can't be used
                tsc = null;
            }
        }

        // all selected criteria must be active for the TSC
        for (Criterion criterion : descriptor.getSupportedCriteria()) {
            if (CodeCoverPlugin.getCriterionSelectedState(iProject, criterion)) {
                if (!tscCriteria.contains(criterion)) {
                    // the TSC doesn't use a criterion which is selected
                    // for the project, this means we can't use the TSC
                    tsc = null;
                }
            }
        }
    }

    eclipseLogger.debug("can reuse TSC: " + (tsc != null ? tsc : "no")); //$NON-NLS-1$ //$NON-NLS-2$

    InstrumenterFactory factory = new DefaultInstrumenterFactory();
    factory.setDescriptor(descriptor);

    // only instrument with the selected criteria
    for (Criterion criterion : descriptor.getSupportedCriteria()) {
        if (CodeCoverPlugin.getCriterionSelectedState(iProject, criterion)) {
            factory.addCriterion(criterion);
        }
    }

    factory.setCharset(DEFAULT_CHARSET_FOR_COMPILING);

    Instrumenter instrumenter = null;
    try {
        instrumenter = factory.getInstrumenter();
    } catch (FactoryMisconfigurationException e) {
        eclipseLogger.fatal("FactoryMisconfigurationException in CompilationParticipant"); //$NON-NLS-1$
    }

    // //////////////////////////////////////////////////////////////////////
    // INSTRUMENT
    // //////////////////////////////////////////////////////////////////////
    File rootFolder = new File(projectFolderLocation);
    File targetFolder = new File(instrumentedFolderLocation);
    MASTBuilder builder = new MASTBuilder(eclipseLogger);
    Map<String, Object> instrumenterDirectives = descriptor.getDefaultDirectiveValues();
    CodeCoverPlugin plugin = CodeCoverPlugin.getDefault();
    eclipseLogger.debug("Plugin: " + plugin);
    IPath coverageLogPath = CodeCoverPlugin.getDefault().getPathToCoverageLogs(iProject);
    coverageLogPath = coverageLogPath.append("coverage-log-file.clf"); //$NON-NLS-1$

    instrumenterDirectives.put(
            org.codecover.instrumentation.java15.InstrumenterDescriptor.CoverageLogPathDirective.KEY,
            coverageLogPath.toOSString());

    if (tsc != null) {
        // we can reuse the TSC
        instrumenterDirectives.put(org.codecover.instrumentation.UUIDDirective.KEY, tsc.getId());
    }

    TestSessionContainer testSessionContainer;
    try {
        testSessionContainer = instrumenter.instrument(rootFolder, targetFolder, sourceTargetContainers,
                builder, instrumenterDirectives);
    } catch (InstrumentationIOException e) {
        eclipseLogger.fatal("InstrumentationIOException in CompilationParticipant", e); //$NON-NLS-1$
        return;
    } catch (InstrumentationException e) {
        eclipseLogger.fatal("InstrumentationException in CompilationParticipant", e); //$NON-NLS-1$
        return;
    }

    // //////////////////////////////////////////////////////////////////////
    // SAVE TSC
    // //////////////////////////////////////////////////////////////////////
    if (tsc == null) {
        // we have to create a new TSC
        try {
            tscManager.addTestSessionContainer(testSessionContainer, iProject, false, null, null);
        } catch (FileSaveException e) {
            eclipseLogger.fatal("FileSaveException in CompilationParticipant", e); //$NON-NLS-1$
        } catch (TSCFileCreateException e) {
            eclipseLogger.fatal("CoreException in CompilationParticipant", e); //$NON-NLS-1$
        } catch (FileLoadException e) {
            eclipseLogger.fatal("CoreException in CompilationParticipant", e); //$NON-NLS-1$
        } catch (InvocationTargetException e) {
            // can't happen because we didn't pass a runnable
            eclipseLogger.warning("InvocationTargetException in CompilationParticipant", e); //$NON-NLS-1$
        } catch (CancelException e) {
            eclipseLogger.warning("User canceled writing of" + //$NON-NLS-1$
                    " new test session container in" + //$NON-NLS-1$
                    " CompilationParticipant"); //$NON-NLS-1$
        }
    }

    // TODO handle compilation errors
    IJavaProject javaProject = JavaCore.create(iProject);

    // set up classpath
    StringBuilder runCommand = new StringBuilder(1024);
    IClasspathEntry[] cpEntries;
    try {
        cpEntries = javaProject.getResolvedClasspath(true);
    } catch (JavaModelException e) {
        eclipseLogger.fatal("JavaModelException in CompilationParticipant", e); //$NON-NLS-1$
        return;
    }

    for (int i = 0; i < cpEntries.length; i++) {
        IClasspathEntry thisEntry = cpEntries[i];
        if (thisEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
            if (runCommand.length() == 0) {
                // this is the first entry -> create the class path option
                runCommand.append("-cp "); //$NON-NLS-1$
            } else {
                // this is not the first -> we need a separator
                runCommand.append(File.pathSeparatorChar);
            }
            runCommand.append("\""); //$NON-NLS-1$
            IPath itsIPath = thisEntry.getPath();
            if (projectFullPath.isPrefixOf(itsIPath)) {
                itsIPath = itsIPath.removeFirstSegments(1);
                itsIPath = projectLocation.append(itsIPath);
            }
            runCommand.append(itsIPath.toOSString());
            runCommand.append("\""); //$NON-NLS-1$
        }
    }

    // check java version related options
    String targetVersion = javaProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true);
    runCommand.append(" -target "); //$NON-NLS-1$
    runCommand.append(targetVersion);
    String sourceVersion = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
    runCommand.append(" -source "); //$NON-NLS-1$
    runCommand.append(sourceVersion);

    // no warnings
    runCommand.append(" -nowarn"); //$NON-NLS-1$

    // use the default charset for the encoding
    // all files have been instrumented or copied using this charset
    runCommand.append(" -encoding "); //$NON-NLS-1$
    runCommand.append(DEFAULT_CHARSET_FOR_COMPILING.toString());

    // the directory to compile
    // put the path in "", because the commandline tokenizes this path
    runCommand.append(" \""); //$NON-NLS-1$
    runCommand.append(instrumentedFolderLocation);
    runCommand.append("\""); //$NON-NLS-1$

    eclipseLogger.debug("I run this compile command now:\n" + runCommand); //$NON-NLS-1$
    StringWriter out = new StringWriter();
    StringWriter err = new StringWriter();
    boolean result;
    result = org.eclipse.jdt.internal.compiler.batch.Main.compile(runCommand.toString(), new PrintWriter(out),
            new PrintWriter(err));

    eclipseLogger.debug("ECJ Output: " + out.toString()); //$NON-NLS-1$
    eclipseLogger.debug("ECJ Error Output: " + err.toString()); //$NON-NLS-1$

    if (!result) {
        eclipseLogger.fatal("An error occured when trying to compile the instrumented sources."); //$NON-NLS-1$
    }

    super.buildStarting(files, isBatch);
}

From source file:org.eclipse.ajdt.internal.ui.wizards.exports.AJJarPackageWizardPage.java

License:Open Source License

private Set removeContainedChildren(Set elements) {
    Set newList = new HashSet(elements.size());
    Set javaElementResources = getCorrespondingContainers(elements);
    Iterator iter = elements.iterator();
    boolean removedOne = false;
    while (iter.hasNext()) {
        Object element = iter.next();
        Object parent;//from ww w . j ava  2  s .c  om
        if (element instanceof IResource)
            parent = ((IResource) element).getParent();
        else if (element instanceof IJavaElement) {
            parent = ((IJavaElement) element).getParent();
            if (parent instanceof IPackageFragmentRoot) {
                IPackageFragmentRoot pkgRoot = (IPackageFragmentRoot) parent;
                try {
                    if (pkgRoot.getCorrespondingResource() instanceof IProject)
                        parent = pkgRoot.getJavaProject();
                } catch (JavaModelException ex) {
                    // leave parent as is
                }
            }
        } else {
            // unknown type
            newList.add(element);
            continue;
        }
        if (element instanceof IJavaModel || ((!(parent instanceof IJavaModel))
                && (elements.contains(parent) || javaElementResources.contains(parent))))
            removedOne = true;
        else
            newList.add(element);
    }
    if (removedOne)
        return removeContainedChildren(newList);
    else
        return newList;
}

From source file:org.eclipse.che.jdt.testplugin.JavaProjectHelper.java

License:Open Source License

/**
 * Adds a source container to a IJavaProject and imports all files contained
 * in the given ZIP file./*from   ww w.j  av a  2s .c  o  m*/
 * @param jproject The parent project
 * @param containerName Name of the source container
 * @param zipFile Archive to import
 * @param containerEncoding encoding for the generated source container
 * @param exclusionFilters Exclusion filters to set
 * @return The handle to the new source container
 * @throws InvocationTargetException Creation failed
 * @throws CoreException Creation failed
 * @throws IOException Creation failed
 */
public static IPackageFragmentRoot addSourceContainerWithImport(IJavaProject jproject, String containerName,
        File zipFile, String containerEncoding, IPath[] exclusionFilters)
        throws InvocationTargetException, CoreException, IOException {
    ZipFile file = new ZipFile(zipFile);
    try {
        IPackageFragmentRoot root = addSourceContainer(jproject, containerName, exclusionFilters);
        ((IContainer) root.getCorrespondingResource()).setDefaultCharset(containerEncoding, null);
        importFilesFromZip(file, root.getPath(), null);
        return root;
    } finally {
        file.close();
    }
}