List of usage examples for org.eclipse.jdt.core IJavaProject getAllPackageFragmentRoots
IPackageFragmentRoot[] getAllPackageFragmentRoots() throws JavaModelException;
From source file:io.spring.boot.development.eclipse.visitors.SpringFactories.java
License:Open Source License
static SpringFactories find(IProject project) { IJavaProject javaProject = JavaCore.create(project); try {//from w w w . j av a2 s. com for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) { if (root.getKind() == IPackageFragmentRoot.K_SOURCE) { IFile springFactories = project.getFile( root.getResource().getProjectRelativePath().append("META-INF/spring.factories")); if (springFactories.exists()) { Properties properties = new Properties(); properties.load(springFactories.getContents()); return new SpringFactories(properties); } } } } catch (Exception ex) { throw new RuntimeException("Failure while finding spring.factories", ex); } return null; }
From source file:jp.co.dgic.eclipse.jdt.internal.junit.launcher.DJUnitLaunchConfiguration.java
License:Open Source License
private void findSourceDirFrom(IJavaProject javaProject, Set<IPath> sourceDirs) throws CoreException { IPackageFragmentRoot[] roots;//from w ww.j a v a2 s.c o m try { roots = javaProject.getAllPackageFragmentRoots(); for (int idx = 0; idx < roots.length; idx++) { int kind = roots[idx].getKind(); if (kind != IPackageFragmentRoot.K_SOURCE) continue; sourceDirs.add(roots[idx].getResource().getLocation()); } } catch (JavaModelException e) { throw new CoreException(e.getStatus()); } }
From source file:net.harawata.mybatipse.mybatis.MapperNamespaceCache.java
License:Open Source License
private void collectMappers(IJavaProject project, final Map<String, IFile> map, final IReporter reporter) { try {// w w w. j ava2 s . co m for (IPackageFragmentRoot root : project.getAllPackageFragmentRoots()) { if (root.getKind() != IPackageFragmentRoot.K_SOURCE) { continue; } root.getResource().accept(new IResourceProxyVisitor() { @Override public boolean visit(IResourceProxy proxy) throws CoreException { if (!proxy.isDerived() && proxy.getType() == IResource.FILE && proxy.getName().endsWith(".xml")) { IFile file = (IFile) proxy.requestResource(); IContentDescription contentDesc = file.getContentDescription(); if (contentDesc != null) { IContentType contentType = contentDesc.getContentType(); if (contentType != null && contentType.isKindOf(mapperContentType)) { String namespace = extractNamespace(file); if (namespace != null) { map.put(namespace, file); } return false; } } } return true; } }, IContainer.NONE); } } catch (CoreException e) { Activator.log(Status.ERROR, "Searching MyBatis Mapper xml failed.", e); } }
From source file:net.officefloor.eclipse.classpath.ClasspathUtil.java
License:Open Source License
/** * Opens the class path resource./*from w w w . jav a2s . c o m*/ * * @param resourcePath * Path to the resource on the class path. * @param editor * {@link AbstractOfficeFloorEditor} opening the resource. */ public static void openClasspathResource(String resourcePath, AbstractOfficeFloorEditor<?, ?> editor) { // Extensions final String CLASS_EXTENSION = ".class"; final String SOURCE_EXTENSION = ".java"; try { // Obtain the package and resource name int index = resourcePath.lastIndexOf('/'); String packageName = (index < 0 ? "" : resourcePath.substring(0, index)).replace('/', '.'); String resourceName = (index < 0 ? resourcePath : resourcePath.substring(index + 1)); // +1 // to // skip // separator // Obtain the java project IJavaProject project = JavaCore.create(ProjectConfigurationContext.getProject(editor.getEditorInput())); // Iterate over the fragment roots searching for the file for (IPackageFragmentRoot root : project.getAllPackageFragmentRoots()) { // Attempt to obtain the package IPackageFragment packageFragment = root.getPackageFragment(packageName); if (!packageFragment.exists()) { continue; // must have package } // Handle if a java or class file if (JavaCore.isJavaLikeFileName(resourceName) || resourceName.endsWith(CLASS_EXTENSION)) { // Handle based on kind of fragment root int rootKind = root.getKind(); switch (rootKind) { case IPackageFragmentRoot.K_BINARY: // Binary, so ensure extension is class if (resourceName.endsWith(SOURCE_EXTENSION)) { resourceName = resourceName.replace(SOURCE_EXTENSION, CLASS_EXTENSION); } // Attempt to obtain and open the class file IClassFile classFile = packageFragment.getClassFile(resourceName); if (classFile != null) { openEditor(editor, classFile); return; // opened } break; case IPackageFragmentRoot.K_SOURCE: // Source, so ensure extension is java if (resourceName.endsWith(CLASS_EXTENSION)) { resourceName = resourceName.replace(CLASS_EXTENSION, SOURCE_EXTENSION); } // Attempt to obtain the compilation unit (source file) ICompilationUnit sourceFile = packageFragment.getCompilationUnit(resourceName); if (sourceFile != null) { openEditor(editor, sourceFile); return; // opened } break; default: throw new IllegalStateException("Unknown package fragment root kind: " + rootKind); } } else { // Not java file, so open as resource for (Object nonJavaResource : packageFragment.getNonJavaResources()) { // Should only be opening files if (nonJavaResource instanceof IFile) { IFile file = (IFile) nonJavaResource; // Determine if the file looking for if (resourceName.equals(file.getName())) { // Found file to open, so open openEditor(editor, file); return; } } else { // Unknown resource type throw new IllegalStateException( "Unkown resource type: " + nonJavaResource.getClass().getName()); } } } } // Unable to open as could not find MessageDialog.openWarning(editor.getEditorSite().getShell(), "Open", "Could not find: " + resourcePath); } catch (Throwable ex) { // Failed to open file MessageDialog.openInformation(editor.getEditorSite().getShell(), "Open", "Failed to open '" + resourcePath + "': " + ex.getMessage()); } }
From source file:net.rim.ejde.internal.util.ImportUtils.java
License:Open Source License
static private List<LinkBuffer> generateLinks(IJavaProject eclipseJavaProject, ResourcesBuffer buffer, Project legacyProject) {/*from w w w.ja va2s. c o m*/ Map<String, Set<File>> javaArtifacts = buffer.getJavaContener(); Map<String, Set<File>> localeArtifacts = buffer.getlocaleContener(); Set<File> nonPackageableFiles = buffer.getNonPackageContener(); IPath drfpath = null, filePath = null; IFile eclipseFileHandle = null, fileHandle = null; IProject eclipseProject = eclipseJavaProject.getProject(); IWorkspaceRoot workspaceRoot = eclipseProject.getWorkspace().getRoot(); List<String> sources = net.rim.ejde.internal.legacy.Util.getSources(legacyProject); IPackageFragmentRoot[] packageFragmentRoots; IPackageFragment packageFragment; IFolder packageFolder; IResource resource, packageDirectory; List<LinkBuffer> linkBuffers = Collections.emptyList(); try { // packageFragmentRoots = // eclipseJavaProject.getPackageFragmentRoots(); //!WARNING: it // seems this is buggy!!!! packageFragmentRoots = eclipseJavaProject.getAllPackageFragmentRoots(); linkBuffers = new ArrayList<LinkBuffer>(); String srcFolder = POTENTIAL_SOURCE_FOLDERS[PROJECT_SRC_FOLDE_INDEX]; String resFolder = POTENTIAL_SOURCE_FOLDERS[PROJECT_RES_FOLDE_INDEX]; String localeFolder = POTENTIAL_SOURCE_FOLDERS[PROJECT_LOCALE_FOLDE_INDEX]; IJavaProject javaProject = null; for (IPackageFragmentRoot packageFragmentRoot : packageFragmentRoots) { javaProject = packageFragmentRoot.getParent().getJavaProject(); if (javaProject == null || !javaProject.equals(eclipseJavaProject)) { // fixed DPI225325, we only care source folders in the // current project continue; } if (IPackageFragmentRoot.K_SOURCE == packageFragmentRoot.getKind()) { packageDirectory = packageFragmentRoot.getResource(); if (null != packageDirectory) { if (isResourceTargetFolder(packageDirectory)) { if (IResource.FOLDER == packageDirectory.getType()) { // handle resource files which are not java, rrh // and rrc if (resFolder.equalsIgnoreCase(packageDirectory.getName())) { packageFragment = packageFragmentRoot.createPackageFragment(StringUtils.EMPTY, true, new NullProgressMonitor()); packageFolder = (IFolder) packageFragment.getResource(); for (File file : nonPackageableFiles) { filePath = new Path(file.getAbsolutePath()); if (canIgnoreFile(filePath, eclipseJavaProject)) { continue; } // drfpath = PackageUtils.resolvePathForFile( filePath, legacyProjectPath, // legacyWorkspacePath ); // DPI222295 try { drfpath = new Path(PackageUtils.getFilePackageString(filePath.toFile(), legacyProject)).append(filePath.lastSegment()); } catch (CoreException e) { _log.error(e.getMessage()); drfpath = new Path(IConstants.EMPTY_STRING); } if (drfpath.segmentCount() > 1) { if (sources.contains(drfpath.segment(0))) { drfpath = drfpath.removeFirstSegments(1); } drfpath = assureFolderPath(packageFolder, drfpath); } fileHandle = createFileHandle(packageFolder, drfpath.toOSString()); resource = eclipseProject.findMember( PackageUtils.deResolve(filePath, eclipseProject.getLocation())); if (resource != null) eclipseFileHandle = workspaceRoot.getFile(resource.getFullPath()); else eclipseFileHandle = workspaceRoot .getFile(eclipseProject.getFullPath().append(drfpath)); if (!fileHandle.equals(eclipseFileHandle)) { linkBuffers.add(new LinkBuffer(fileHandle, filePath)); } } } if (srcFolder.equalsIgnoreCase(packageDirectory.getName()) || srcFolder.equalsIgnoreCase(packageDirectory.getName())) { // All linkPackagableFiles(javaProject, packageFragmentRoot, javaArtifacts, linkBuffers); } if (localeFolder.equalsIgnoreCase(packageDirectory.getName()) || localeFolder.equalsIgnoreCase(packageDirectory.getName())) { linkPackagableFiles(javaProject, packageFragmentRoot, localeArtifacts, linkBuffers); } } else { continue; } } } } } } catch (JavaModelException e1) { _log.error(e1.getMessage(), e1); } return linkBuffers; }
From source file:net.rim.ejde.internal.util.ProjectUtils.java
License:Open Source License
/** * Locates all the source folders represented by type IPackageFragmentRoot.K_SOURCE for the given project. * * @param project/*from www .ja v a 2s . c o m*/ * The IProject to search for source folders. * @return An IPackageFragmentRoot array containing each K_SOURCE fragment found for the given project. */ public static IPackageFragmentRoot[] getProjectSourceFolders(IProject project) { IJavaProject iJavaProject = JavaCore.create(project); ArrayList<IPackageFragmentRoot> sourceRoots = new ArrayList<IPackageFragmentRoot>(); if (iJavaProject.exists() && iJavaProject.isOpen()) { try { IPackageFragmentRoot[] roots = iJavaProject.getAllPackageFragmentRoots(); for (IPackageFragmentRoot root : roots) { if (IPackageFragmentRoot.K_SOURCE == root.getKind()) { sourceRoots.add(root); } } } catch (JavaModelException e) { logger.error("findProjectSources: Could not retrieve project sources:", e); //$NON-NLS-1$ return new IPackageFragmentRoot[0]; } } return sourceRoots.toArray(new IPackageFragmentRoot[sourceRoots.size()]); }
From source file:net.sf.spindle.core.util.eclipse.JarEntryFileUtil.java
License:Mozilla Public License
private static IPackageFragmentRoot getPackageFragmentRoot(IJavaProject project, JarEntryFile entry, boolean includeOtherProjects) throws CoreException { String path = getJarPath(entry); IPackageFragmentRoot[] roots = includeOtherProjects ? project.getAllPackageFragmentRoots() : project.getPackageFragmentRoots(); for (int i = 0; i < roots.length; i++) { if (roots[i].getKind() != IPackageFragmentRoot.K_BINARY) continue; if (((JarPackageFragmentRoot) roots[i]).getJar().getName().equals(path)) { return roots[i]; }// w w w. j a v a 2 s.c om } return null; }
From source file:org.codecover.eclipse.builder.CodeCoverCompilationParticipant.java
License:Open Source License
/** * This method is called for each project separately. *///from w w w. java2s .com @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.codehaus.groovy.eclipse.launchers.GroovyConsoleLineTracker.java
License:Apache License
/** * @param groovyFileName// w w w . j a v a 2s. com * @return * @throws JavaModelException */ private IFile[] searchForFileInLaunchConfig(String groovyFileName) throws JavaModelException { List<IFile> files = new LinkedList<IFile>(); IJavaProject[] projects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProjects(); for (IJavaProject javaProject : projects) { if (GroovyNature.hasGroovyNature(javaProject.getProject())) { for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) { if (root.getKind() == IPackageFragmentRoot.K_SOURCE) { IResource resource = root.getResource(); if (resource.isAccessible() && resource.getType() != IResource.FILE) { IFile file = ((IContainer) resource).getFile(new Path(groovyFileName)); if (file.isAccessible()) { files.add(file); } } } } } } return files.toArray(new IFile[files.size()]); }
From source file:org.eclipse.ajdt.core.model.AJProjectModelFacade.java
License:Open Source License
private IPackageFragment[] findFragment(IJavaProject jproj, HandleInfo handleInfo) throws JavaModelException { IPackageFragmentRoot[] pkgRoots = jproj.getAllPackageFragmentRoots(); List<IPackageFragment> frags = new ArrayList<IPackageFragment>(); for (int i = 0; i < pkgRoots.length; i++) { IPackageFragment candidate = pkgRoots[i].getPackageFragment(handleInfo.packageName); if (candidate.exists()) { frags.add(candidate);//from w w w . j a va 2s .c o m } } return frags.toArray(new IPackageFragment[frags.size()]); }