List of usage examples for org.eclipse.jdt.core IJavaProject getResource
IResource getResource();
From source file:com.google.inject.tools.ideplugin.eclipse.EclipseJavaProject.java
License:Apache License
private String getProjectOutputLocation(IJavaProject project) throws JavaModelException { IResource resource = project.getResource(); String resourceLocation = resource.getLocation().toOSString(); String projectLocation = project.getOutputLocation().makeRelative().toOSString(); return projectLocation.replaceFirst(project.getProject().getName(), resourceLocation); }
From source file:com.google.inject.tools.ideplugin.eclipse.EclipseJavaProject.java
License:Apache License
private String getProjectLocation(IJavaProject project) { IResource resource = project.getResource(); String resourceLocation = resource.getLocation().toOSString(); return resourceLocation; }
From source file:com.laex.j2objc.CleanupAction.java
License:Open Source License
@Override public void run(IAction action) { if (!action.isEnabled()) { return;/*from w w w. j a v a 2 s . com*/ } MessageBox mb = new MessageBox(targetPart.getSite().getShell(), SWT.OK | SWT.CANCEL | SWT.ERROR); mb.setMessage( "This action cleans up all the internal files generated by the plugin. It won't clean up compiled source files. Are you sure you want to proceed ? "); int resp = mb.open(); if (resp == SWT.CANCEL) return; for (Object o : selected) { if (o instanceof IJavaElement) { IJavaElement jel = (IJavaElement) o; IJavaProject javaProject = jel.getJavaProject(); AntDelegate antDel = new AntDelegate(javaProject); try { antDel.executeCleanup(targetPart.getSite().getShell().getDisplay()); } catch (IOException e) { LogUtil.logException(e); } catch (CoreException e) { LogUtil.logException(e); } try { javaProject.getResource().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { LogUtil.logException(e); } } } }
From source file:com.laex.j2objc.ToObjectiveCAction.java
License:Open Source License
@Override public void run(IAction action) { if (!action.isEnabled()) { return;/* w ww.j av a 2s .c om*/ } /* Show the console view */ final MessageConsole console = MessageUtil.findConsole(MessageUtil.J2OBJC_CONSOLE); IWorkbenchPage page = targetPart.getSite().getWorkbenchWindow().getActivePage(); String id = IConsoleConstants.ID_CONSOLE_VIEW; IConsoleView view; try { view = (IConsoleView) page.showView(id); view.display(console); } catch (PartInitException e1) { LogUtil.logException(e1); } /* Before starting the job, check if the path to J2OBJC has been set up */ final Display display = targetPart.getSite().getShell().getDisplay(); final String pathToCompiler = Activator.getDefault().getPreferenceStore() .getString(PreferenceConstants.PATH_TO_COMPILER); console.clearConsole(); MessageConsoleStream mct = console.newMessageStream(); if (StringUtils.isEmpty(pathToCompiler)) { try { MessageUtil.setConsoleColor(display, mct, SWT.COLOR_RED); mct.write( "Path to compiler empty. Please set the path to J2OBJC compiler from global preferences."); } catch (IOException e) { LogUtil.logException(e); } return; } /* Before starting the job, calculate total no. of files to compile */ calculateWork(); // Start the job final Job job = new Job("J2OBJC Command Line Executor") { @Override protected IStatus run(IProgressMonitor monitor) { try { monitor.beginTask("J2OBJC Compiliation", totalWork); IJavaElement elm = (IJavaElement) strucSelc.getFirstElement(); IJavaProject javaProject = (IJavaProject) elm.getJavaProject(); Map<String, String> props = PropertiesUtil.getProjectProperties(javaProject.getResource()); props.put(PreferenceConstants.PATH_TO_COMPILER, pathToCompiler); // some initial message plumbing ToObjectiveCDelegate.clearPrebuiltSwitch(); ToObjectiveCDelegate delegate = new ToObjectiveCDelegate(display, props, monitor); elm.getResource().accept(delegate); monitor.worked(1); // copy files to some external directory monitor.subTask("Exporting Objective-C Classes"); String destinationDir = PropertiesUtil.getOutputDirectory(javaProject); doOutput(console, display, javaProject, destinationDir); monitor.worked(1); // refresh javaProject.getResource().refreshLocal(IResource.DEPTH_INFINITE, monitor); monitor.worked(1); monitor.done(); } catch (CoreException ce) { LogUtil.logException(ce); return Status.CANCEL_STATUS; } catch (IOException e) { LogUtil.logException(e); return Status.CANCEL_STATUS; } return Status.OK_STATUS; } private void doOutput(final MessageConsole console, final Display display, IJavaProject javaProject, String destinationDir) throws IOException, CoreException { if (StringUtils.isNotEmpty(destinationDir)) { // Ant specific code String sourceDir = javaProject.getResource().getLocation().makeAbsolute().toOSString(); AntDelegate antDelegate = new AntDelegate(javaProject); antDelegate.executeExport(display, sourceDir, destinationDir); } else { MessageConsoleStream mct = console.newMessageStream(); MessageUtil.setConsoleColor(display, mct, SWT.COLOR_BLUE); mct.write("No Output directory specified. Files will not be exported."); } } }; job.setUser(true); job.schedule(); }
From source file:com.laex.j2objc.util.PropertiesUtil.java
License:Open Source License
/** * Gets the output directory.//from ww w . j a v a2 s. com * * @param javaProject the java project * @return the output directory * @throws CoreException the core exception */ public static String getOutputDirectory(IJavaProject javaProject) throws CoreException { return javaProject.getResource().getPersistentProperty(OUTPUT_DIRECTORY_KEY); }
From source file:com.laex.j2objc.util.PropertiesUtil.java
License:Open Source License
/** * Gets the exclude pattern.// w ww.j av a 2s .c o m * * @param javaProject the java project * @return the exclude pattern * @throws CoreException the core exception */ public static String getExcludePattern(IJavaProject javaProject) throws CoreException { return javaProject.getResource().getPersistentProperty(EXCLUDE_FILES_KEY); }
From source file:com.motorola.studio.android.model.BuildingBlockModel.java
License:Apache License
/** * Extract source folder from selection. * @param selection/*from w ww . j a v a 2 s .c o m*/ * @return * @throws CoreException */ private static IPackageFragmentRoot extractPackageFragmentRoot(IStructuredSelection selection) throws CoreException { IPackageFragmentRoot pack = null; Object selectionElement = selection.getFirstElement(); if (selectionElement instanceof IPackageFragmentRoot) { pack = (IPackageFragmentRoot) selectionElement; } else if (selectionElement instanceof IJavaElement) { pack = (IPackageFragmentRoot) ((IJavaElement) selectionElement) .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); if (pack == null) { IJavaProject element = ((IJavaElement) selectionElement).getJavaProject(); for (IPackageFragmentRoot root : element.getPackageFragmentRoots()) { if (root.getResource() != null) { boolean isSrc = (root.getElementType() & IPackageFragmentRoot.K_SOURCE) == IPackageFragmentRoot.K_SOURCE; boolean isGen = root.getElementName().equals(IAndroidConstants.GEN_SRC_FOLDER) && (root.getParent() instanceof IJavaProject); if (isSrc && !isGen) { pack = root; break; } } } } } else if (selectionElement instanceof IResource) { IJavaProject element = JavaCore.create(((IResource) selectionElement).getProject()); if (element.isOpen()) { for (IPackageFragmentRoot root : element.getPackageFragmentRoots()) { if (root.getResource() != null) { boolean isSrc = (root.getElementType() & IPackageFragmentRoot.K_SOURCE) == IPackageFragmentRoot.K_SOURCE; boolean isGen = root.getElementName().equals(IAndroidConstants.GEN_SRC_FOLDER) && (root.getParent() instanceof IJavaProject); if (isSrc && !isGen) { pack = root; break; } } } } } else { IJavaProject[] allProjects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()) .getJavaProjects(); if ((allProjects != null) && (allProjects.length > 0)) { for (IJavaProject project : allProjects) { if (project.getResource().getProject().hasNature(IAndroidConstants.ANDROID_NATURE)) { IPackageFragmentRoot[] roots = project.getPackageFragmentRoots(); if ((roots != null) && (roots.length > 0)) { boolean found = false; for (IPackageFragmentRoot root : roots) { boolean isSrc = (root.getElementType() & IPackageFragmentRoot.K_SOURCE) == IPackageFragmentRoot.K_SOURCE; boolean isGen = root.getElementName().equals(IAndroidConstants.GEN_SRC_FOLDER) && (root.getParent() instanceof IJavaProject); if (isSrc && !isGen) { found = true; pack = root; break; } } if (found) { break; } } } } } } if (pack != null) { if (!pack.getJavaProject().getProject().hasNature(IAndroidConstants.ANDROID_NATURE)) { pack = extractPackageFragmentRoot(new TreeSelection()); } } return pack; }
From source file:com.redhat.ceylon.eclipse.code.explorer.PackageExplorerContentProvider.java
License:Open Source License
@Override protected Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException { if (!project.getProject().isOpen()) return NO_CHILDREN; List<Object> result = new ArrayList<Object>(); IPackageFragmentRoot[] roots = project.getPackageFragmentRoots(); for (int i = 0; i < roots.length; i++) { IPackageFragmentRoot root = roots[i]; IClasspathEntry classpathEntry = root.getRawClasspathEntry(); int entryKind = classpathEntry.getEntryKind(); if (entryKind == IClasspathEntry.CPE_CONTAINER) { // all ClassPathContainers are added later } else if (fShowLibrariesNode && (entryKind == IClasspathEntry.CPE_LIBRARY || entryKind == IClasspathEntry.CPE_VARIABLE)) { IResource resource = root.getResource(); if (resource != null && project.getResource().equals(resource.getParent())) { // show resource as child of project, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=141906 result.add(resource);/*from w w w . j a v a 2s. co m*/ } else { // skip: will add the referenced library node later } } else { if (isProjectPackageFragmentRoot(root)) { // filter out package fragments that correspond to projects and // replace them with the package fragments directly Object[] fragments = getPackageFragmentRootContent(root); for (int j = 0; j < fragments.length; j++) { result.add(fragments[j]); } } else { result.add(root); } } } if (fShowLibrariesNode) { result.add(new LibraryContainer(project)); } // separate loop to make sure all containers are on the classpath (even empty ones) IClasspathEntry[] rawClasspath = project.getRawClasspath(); for (int i = 0; i < rawClasspath.length; i++) { IClasspathEntry classpathEntry = rawClasspath[i]; if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { result.add(new ClassPathContainer(project, classpathEntry)); } } Object[] resources = project.getNonJavaResources(); for (int i = 0; i < resources.length; i++) { result.add(resources[i]); } return result.toArray(); }
From source file:com.siteview.mde.internal.ui.editor.schema.NewClassCreationWizard.java
License:Open Source License
private void initializeValues(IProject project, String value) throws JavaModelException { value = TextUtil.trimNonAlphaChars(value); IJavaProject javaProject = JavaCore.create(project); IPackageFragmentRoot srcEntryDft = null; IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots(); for (int i = 0; i < roots.length; i++) { if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) { srcEntryDft = roots[i];/*from www . j a va 2s.com*/ break; } } if (srcEntryDft != null) packageRoot = srcEntryDft; else packageRoot = javaProject.getPackageFragmentRoot(javaProject.getResource()); String packageNameString = null; int index = value.lastIndexOf("."); //$NON-NLS-1$ if (index == -1) { className = value; } else { className = value.substring(index + 1); packageNameString = value.substring(0, index); } if (packageNameString != null && packageRoot != null) { IFolder packageFolder = project.getFolder(packageNameString); packageName = packageRoot.getPackageFragment(packageFolder.getProjectRelativePath().toOSString()); } }
From source file:com.sureassert.uc.builder.SAUCBuildWorker.java
License:Open Source License
public synchronized void processJavaProject(ProjectProcessEntity projectProcessEntity, // Set<ProjectProcessEntity> alreadyProcessed, boolean hasProjectChanged, IProgressMonitor progressMonitor) { // if (!isStandaloneBuild) { // try {//from w w w. j a va2 s. c o m // BasicUtils.debug("Starting build..."); // int numErrors = BuildClient.getInstance().sendMessage(// // new StartBuildPPEMessage(new SerializableProjectProcessEntity(projectProcessEntity))); // } catch (Exception e) { // throw new RuntimeException(e); // } finally { // BasicUtils.debug("Build complete"); // } // return; // } // JaCoCoClient jacocoClient = new JaCoCoClient(new SAUCEditorCoverageListenner()); CoveragePrinter coveragePrinter = new CoveragePrinter(new SAUCEditorCoverageListenner()); alreadyProcessed.add(projectProcessEntity); AspectJSigCache.clear(); Map<IJavaProject, Set<ProcessEntity>> pEsByProject = null; IJavaProject javaProject = projectProcessEntity.getJavaProject(); Map<IPath, Set<Signature>> affectedFileSigs = projectProcessEntity.getAffectedFileSigs(); Set<IPath> affectedFiles = null; if (affectedFileSigs != null) { affectedFiles = affectedFileSigs.keySet(); if (affectedFiles != null && affectedFiles.isEmpty()) affectedFiles = null; } IWorkspace workspace = javaProject.getProject().getWorkspace(); ProjectClassLoaders projectCLs = null; IFile file = null; IResource resource = javaProject.getResource(); long startTime = System.nanoTime(); sfFactory = new SourceFileFactory(); javaPathData = new JavaPathData(); InstrumentationSession jaCoCoSession = new InstrumentationSession(SaUCPreferences.getIsCoverageEnabled()); boolean fullBuild = (affectedFiles == null); Set<ProcessEntity> allProcessEntities = null; IProject project = (IProject) resource; progressMonitor.beginTask("Processing " + project.getName(), 2000); try { BasicUtils.debug("-------------------------------------------------"); BasicUtils.debug("Sureassert UC building project " + project.getName()); BasicUtils.debug("ProcessEntities: " + projectProcessEntity.toString()); // Get classloader using classpath of this project jaCoCoSession.start(); projectCLs = ProjectClassLoaders.getClassLoaders(javaProject, affectedFiles == null, jaCoCoSession); PersistentDataFactory.getInstance().setCurrentUseCase(null, null, null, null, null, false, null, false); PersistentDataFactory.getInstance().setCurrentProject(project.getName(), // EclipseUtils.getRawPath(project).toString()); PropertyFile propertyFile = new PropertyFile(new File(project.getLocation().toFile(), // PropertyFile.DEFAULT_PROPERTY_FILENAME)); propertyFile.loadExtensions(projectCLs.projectCL); SourceModelFactory smFactory = new SourceModelFactory(projectCLs); UseCaseExecutionDelegate.INSTANCE.init(javaPathData, sfFactory, projectCLs.transformedCL); long getPEsStartTime = System.nanoTime(); // Delete markers for all changed files if (hasProjectChanged) MarkerUtils.deleteAllMarkers(affectedFiles, project, sfFactory, javaPathData); ProcessEntityFactory peFactory = new ProcessEntityFactory(javaPathData, this); // Get ProcessEntities // Stage 1 if (fullBuild) { ProjectClassLoaders.cleanTransformedDirs(javaProject); pEsByProject = peFactory.getProcessEntitiesFullBuild(resource, project, // javaProject, projectCLs, hasProjectChanged, smFactory, sfFactory, // new SubProgressMonitor(progressMonitor, 1000)); } else { pEsByProject = peFactory.getProcessEntitiesIncBuild(affectedFileSigs, resource, project, // javaProject, projectCLs, hasProjectChanged, smFactory, sfFactory, // new SubProgressMonitor(progressMonitor, 1000)); } BasicUtils.debug("Got ProcessEntities in " + ((System.nanoTime() - getPEsStartTime) / 1000000) + // "ms"); Set<ProcessEntity> unprocessedEntities = pEsByProject.get(javaProject); if (unprocessedEntities == null) unprocessedEntities = new HashSet<ProcessEntity>(); allProcessEntities = new HashSet<ProcessEntity>(unprocessedEntities); // Pre-process 1 for (ProcessEntity processEntity : unprocessedEntities) { file = processEntity.getFile(); SourceFile sourceFile = sfFactory.getSourceFile(file); // Delete internal/class level error markers MarkerUtils.deleteUCMarkers(sourceFile, -1, 1, null, null); MarkerUtils.deleteJUnitMarkers(sourceFile, -1, 1, null, null); executeNamedInstances(processEntity, projectCLs.transformedCL, smFactory, sfFactory); registerSINTypes(processEntity, projectCLs.transformedCL, smFactory, sfFactory); } // Set default values in UseCases and sort the PEs according to dependencies List<ProcessEntity> currentProcessEntities = new ArrayList<ProcessEntity>(unprocessedEntities); // System.out.println(">Unsorted: " + currentProcessEntities.toString()); currentProcessEntities = ProcessEntity.setDefaultsAndSort(currentProcessEntities, // projectCLs.transformedCL, smFactory, sfFactory); // System.out.println(">Sorted: " + currentProcessEntities.toString()); // Process // Stage 2 // Iterate over unprocessed java files // jacocoClient.startSession(); boolean lastPass = false; IProgressMonitor processStageMonitor = new SubProgressMonitor(progressMonitor, 1000); try { while (!currentProcessEntities.isEmpty()) { int peIndex = 0; processStageMonitor.beginTask("Executing", currentProcessEntities.size()); for (ProcessEntity processEntity : currentProcessEntities) { processStageMonitor.worked(1); int percentComplete = (int) (((double) peIndex / (double) currentProcessEntities.size()) * 100); file = processEntity.getFile(); SourceFile sourceFile = sfFactory.getSourceFile(file); try { if (javaProject != null && javaProject.exists()) { processJavaType(processEntity, projectCLs, javaProject, smFactory, // sourceFile, processStageMonitor, percentComplete); } // File processed successfully, remove from list. unprocessedEntities.remove(processEntity); } catch (NamedInstanceNotFoundException ninfe) { if (lastPass) { // The last pass is activated when all files remain in the list; on // this last pass we must report the error. int lineNum = sourceFile.getLineNum(ninfe.getSourceLocation()); MarkerUtils.addMarker(sfFactory, javaPathData, sourceFile, ninfe.getMessage(), lineNum, // IMarker.SEVERITY_ERROR, false); unprocessedEntities.remove(processEntity); } else { // The named instance may be loaded in a subsequent file, // leave this file in the list. } } catch (SAUCBuildInterruptedError e) { throw e; } catch (LicenseBreachException e) { throw e; } catch (Throwable e) { String msg = e instanceof CircularDependencyException ? "" : "Sureassert UC error: "; MarkerUtils.addMarker(sfFactory, javaPathData, sourceFile, msg + BasicUtils.toDisplayStr(e), -1, IMarker.SEVERITY_ERROR, false); // iretrievable error, remove from list. unprocessedEntities.remove(processEntity); } peIndex++; } // end execute process entity loop if (lastPass) break; if (unprocessedEntities.size() == currentProcessEntities.size()) { // Every file resulted in a retry request for the next pass; // therefore on the next and last pass they must report their errors. lastPass = true; } // Replace working list with cut-down list currentProcessEntities = new ArrayList<ProcessEntity>(unprocessedEntities); } } finally { processStageMonitor.done(); } addSourceModelErrors(smFactory); } catch (SAUCBuildInterruptedError e) { throw e; } catch (Throwable e) { if (e instanceof LicenseBreachException) { PersistentDataFactory.getInstance().registerLicenseBreached(); } else if (e instanceof CompileErrorsException) { try { handleCompileErrors((CompileErrorsException) e, sfFactory); } catch (Exception e1) { e1.printStackTrace(); } } else { if (e instanceof SAException) file = ((SAException) e).getFile(); EclipseUtils.reportError(e); if (file != null) { String msg = e instanceof CircularDependencyException ? "" : "Sureassert UC error: "; try { MarkerUtils.addMarker(sfFactory, javaPathData, sfFactory.getSourceFile(file), msg + BasicUtils.toDisplayStr(e), -1, IMarker.SEVERITY_ERROR, false); } catch (Exception e1) { e1.printStackTrace(); } } } // PersistentDataFactory.getInstance().setNewPersistentStore(javaProject.getProject().getName()); } finally { // Add coverage markers jaCoCoSession.end(sfFactory, javaPathData, new SubProgressMonitor(progressMonitor, 1000), this); // jacocoClient.dumpExecData(); // jacocoClient.printInfo(sfFactory, javaPathData, new // SubProgressMonitor(progressMonitor, 1000), this); // coveragePrinter.printInfo(sfFactory, javaPathData, new // SubProgressMonitor(progressMonitor, 1000), this, null); // Update coverage report Set<IPath> checkPaths = javaPathData.getAllCachedFilePaths(); checkPaths.addAll(EclipseUtils.toPaths(PersistentDataFactory.getInstance().getMarkedFilePaths())); if (allProcessEntities != null) checkPaths.addAll(ProcessEntity.getPaths(allProcessEntities)); // new CoverageReporter().reportCoverage(checkPaths, javaPathData, workspace, // sfFactory); // Clear caches NamedInstanceFactory.getInstance().clear(); PersistentDataFactory.getInstance().clearMarkedFilePaths(); UseCaseExecutionDelegate.INSTANCE.dispose(); if (projectCLs != null) projectCLs.clear(); sfFactory = null; BasicUtils.debug("-------------------------------------------------"); BasicUtils.debug("Sureassert UC builder finished \"" + javaProject.getElementName() + // "\" in " + ((System.nanoTime() - startTime) / 1000000) + "ms"); // Get foreign client project process entities that now require building if (pEsByProject != null) { for (Entry<IJavaProject, Set<ProcessEntity>> projectPEs : pEsByProject.entrySet()) { if (!projectPEs.getKey().equals(javaProject)) { ProjectProcessEntity ppe = ProjectProcessEntity.newFromProcessEntities(// projectPEs.getKey(), projectPEs.getValue()); if (!alreadyProcessed.contains(ppe)) processJavaProject(ppe, alreadyProcessed, false, new SubProgressMonitor(progressMonitor, 0)); } } } progressMonitor.setTaskName("Building workspace"); // occasional Eclipse bug workaround progressMonitor.done(); } }