List of usage examples for org.eclipse.jdt.core IJavaProject setRawClasspath
void setRawClasspath(IClasspathEntry[] entries, IProgressMonitor monitor) throws JavaModelException;
From source file:org.eclipse.ajdt.internal.utils.AJDTUtils.java
License:Open Source License
private static void excludeAJfiles(IProject project) { IJavaProject jp = JavaCore.create(project); try {/*w w w. j av a 2s.c o m*/ boolean changed = false; IClasspathEntry[] cpEntry = jp.getRawClasspath(); for (int i = 0; i < cpEntry.length; i++) { IClasspathEntry entry = cpEntry[i]; if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { List<IPath> excludeList = new ArrayList<IPath>(); IPackageFragmentRoot[] roots = jp.findPackageFragmentRoots(entry); for (int j = 0; j < roots.length; j++) { IJavaElement[] rootFragments; try { rootFragments = roots[j].getChildren(); for (int k = 0; k < rootFragments.length; k++) { if (rootFragments[k] instanceof IPackageFragment) { IPackageFragment pack = (IPackageFragment) rootFragments[k]; ICompilationUnit[] files = pack.getCompilationUnits(); for (int l = 0; l < files.length; l++) { IResource resource = files[l].getResource(); if (resource.getFileExtension().equals("aj")) { //$NON-NLS-1$ IPath resPath = resource.getFullPath(); int seg = resPath.matchingFirstSegments(roots[j].getPath()); excludeList.add(resPath.removeFirstSegments(seg)); } } } } } catch (JavaModelException e) { } } if (excludeList.size() > 0) { IPath[] exc = new IPath[excludeList.size()]; excludeList.toArray(exc); IClasspathEntry classpathEntry = JavaCore.newSourceEntry(entry.getPath(), exc); cpEntry[i] = classpathEntry; changed = true; } } } if (changed) { jp.setRawClasspath(cpEntry, null); } } catch (JavaModelException e) { } }
From source file:org.eclipse.ajdt.internal.utils.AJDTUtils.java
License:Open Source License
/** * @param current//from w w w . j av a 2 s .c om */ public static void verifyAjrtVersion(IProject current) { IJavaProject javaProject = JavaCore.create(current); String ajrtPath = CoreUtils.getAspectjrtClasspath(); try { IClasspathEntry[] originalCP = javaProject.getRawClasspath(); ArrayList<IClasspathEntry> tempCP = new ArrayList<IClasspathEntry>(); boolean changed = false; // Go through each current classpath entry one at a time. If it is a // reference to aspectjrt.jar // replace it - I could look through each reference to check if it // is now invalid - but I don't ... for (int i = 0; i < originalCP.length; i++) { IPath path = originalCP[i].getPath(); if (path.toOSString().endsWith("aspectjrt.jar")) { //$NON-NLS-1$ IClasspathEntry ajrtCP = JavaCore.newLibraryEntry(new Path(ajrtPath), // library location null, // no source null // no source ); tempCP.add(ajrtCP); changed = true; AJLog.log("In project " //$NON-NLS-1$ + current.getName() + " - replacing " //$NON-NLS-1$ + originalCP[i].getPath() + " with " //$NON-NLS-1$ + ajrtCP.getPath()); } else { tempCP.add(originalCP[i]); } } // Set the classpath with only those elements that survived the // above filtration process. if (changed) { IClasspathEntry[] newCP = (IClasspathEntry[]) tempCP.toArray(new IClasspathEntry[tempCP.size()]); javaProject.setRawClasspath(newCP, new NullProgressMonitor()); } } catch (JavaModelException e) { // Thrown if attempted to add a duplicate classpath entry. } }
From source file:org.eclipse.ajdt.ui.AspectJUIPlugin.java
License:Open Source License
/** * Attempt to update the project's build classpath with the AspectJ runtime * library./* www . j a v a 2 s . c o m*/ * * @param project */ public static void addAjrtToBuildPath(IProject project) { IJavaProject javaProject = JavaCore.create(project); try { IClasspathEntry[] originalCP = javaProject.getRawClasspath(); IPath ajrtPath = new Path(AspectJPlugin.ASPECTJRT_CONTAINER); boolean found = false; for (int i = 0; i < originalCP.length; i++) { if (originalCP[i].getPath().equals(ajrtPath)) { found = true; break; } } if (!found) { IClasspathEntry ajrtLIB = JavaCore.newContainerEntry(ajrtPath, false); // Update the raw classpath with the new ajrtCP entry. int originalCPLength = originalCP.length; IClasspathEntry[] newCP = new IClasspathEntry[originalCPLength + 1]; System.arraycopy(originalCP, 0, newCP, 0, originalCPLength); newCP[originalCPLength] = ajrtLIB; javaProject.setRawClasspath(newCP, new NullProgressMonitor()); } } catch (JavaModelException e) { } }
From source file:org.eclipse.ajdt.ui.AspectJUIPlugin.java
License:Open Source License
/** * Attempt to update the project's build classpath by removing any occurance * of the AspectJ runtime library.//from w w w . j a v a 2s.c om * * @param project */ public static void removeAjrtFromBuildPath(IProject project) { IJavaProject javaProject = JavaCore.create(project); try { IClasspathEntry[] originalCP = javaProject.getRawClasspath(); ArrayList tempCP = new ArrayList(); // Go through each current classpath entry one at a time. If it // is not a reference to the aspectjrt.jar then do not add it // to the collection of new classpath entries. for (int i = 0; i < originalCP.length; i++) { IPath path = originalCP[i].getPath(); boolean keep = true; if (path.toOSString().endsWith("ASPECTJRT_LIB") //$NON-NLS-1$ || path.toOSString().endsWith("aspectjrt.jar")) { //$NON-NLS-1$ keep = false; } if (originalCP[i].getEntryKind() == IClasspathEntry.CPE_CONTAINER) { if (path.segment(0).equals(AspectJPlugin.ASPECTJRT_CONTAINER)) { keep = false; } } if (keep) { tempCP.add(originalCP[i]); } } // end for // Set the classpath with only those elements that survived the // above filtration process. if (originalCP.length != tempCP.size()) { IClasspathEntry[] newCP = (IClasspathEntry[]) tempCP.toArray(new IClasspathEntry[tempCP.size()]); javaProject.setRawClasspath(newCP, new NullProgressMonitor()); } // end if at least one classpath element removed } catch (JavaModelException e) { } }
From source file:org.eclipse.ajdt.ui.tests.builder.ProjectDependenciesUtils.java
License:Open Source License
public static void addProjectDependency(IJavaProject projectToHaveDependency, IProject projectDependedOn) { try {/*from w w w . j a v a 2 s . c o m*/ IClasspathEntry[] cpEntry = projectToHaveDependency.getRawClasspath(); IClasspathEntry newProjectEntry = JavaCore.newProjectEntry(projectDependedOn.getFullPath()); IClasspathEntry[] newEntries = new IClasspathEntry[cpEntry.length + 1]; for (int i = 0; i < cpEntry.length; i++) { newEntries[i] = cpEntry[i]; } newEntries[cpEntry.length] = newProjectEntry; projectToHaveDependency.setRawClasspath(newEntries, null); waitForJobsToComplete(); } catch (JavaModelException e) { e.printStackTrace(); } }
From source file:org.eclipse.ajdt.ui.tests.builder.ProjectDependenciesUtils.java
License:Open Source License
public static void removeProjectDependency(IJavaProject projectWhichHasDependency, IProject projectDependedOn) { try {/* w w w .j a va 2s .co m*/ IClasspathEntry[] cpEntry = projectWhichHasDependency.getRawClasspath(); List newEntries = new ArrayList(); for (int j = 0; j < cpEntry.length; j++) { IClasspathEntry entry = cpEntry[j]; if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { if (!entry.getPath().equals(projectDependedOn.getFullPath()) && !entry.getPath().equals(projectDependedOn.getFullPath().makeAbsolute())) { newEntries.add(entry); } } else { newEntries.add(entry); } } IClasspathEntry[] newCP = (IClasspathEntry[]) newEntries .toArray(new IClasspathEntry[newEntries.size()]); projectWhichHasDependency.setRawClasspath(newCP, null); waitForJobsToComplete(); waitForJobsToComplete(); } catch (JavaModelException e) { e.printStackTrace(); } }
From source file:org.eclipse.amp.escape.ide.ProjectWizard.java
License:Open Source License
@Override public boolean performFinish() { try {//ww w. j ava 2 s .c o m IJavaProject javaProject = JavaCore.create(getProject()); final IProjectDescription projectDescription = ResourcesPlugin.getWorkspace() .newProjectDescription(projectPage.getProjectName()); if (projectPage.useDefaults()) { projectDescription.setLocation(null); } else { projectDescription.setLocation(projectPage.getLocationPath()); } getProject().create(projectDescription, null); projectDescription.setNatureIds(getNatures().toArray(new String[0])); List<String> builderIDs = getBuilders(); ICommand[] buildCMDS = new ICommand[builderIDs.size()]; int i = 0; for (String builderID : builderIDs) { ICommand build = projectDescription.newCommand(); build.setBuilderName(builderID); buildCMDS[i++] = build; } projectDescription.setBuildSpec(buildCMDS); getProject().open(null); getProject().setDescription(projectDescription, null); List<IClasspathEntry> classpathEntries = getClasspathsEntries(); javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), null); javaProject.setOutputLocation(new Path("/" + projectPage.getProjectName() + "/bin"), null); createFiles(); return true; } catch (Exception exception) { StatusManager.getManager().handle(new Status(IStatus.ERROR, getCurrentPluginID(), "Problem creating " + getProjectTypeName() + " project. Ignoring.", exception)); try { getProject().delete(true, null); } catch (Exception e) { // TODO: handle exception } return false; } }
From source file:org.eclipse.andmore.android.common.utilities.EclipseUtils.java
License:Apache License
/** * This method adds a list of paths to all projects classpaths settings. * //from w w w . ja va 2s . c o m * @param javaProjects * List of projects that will have the classpath changed * @param libsPaths * List of lib paths to be added to Projects' classpaths * @param monitor * Monitor to track progress or null if it's not necessary. * @return IStatus The status of the operation. This method stops processing * at the first error found. */ public static IStatus addLibsToProjects(List<IJavaProject> javaProjects, List<IPath> libsPaths, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor); subMonitor.beginTask(UtilitiesNLS.ProjectUtils_AddLibsProgress_ConfiguringClassPaths, ((javaProjects.size() * 2) + libsPaths.size()) * 1000); IStatus status = Status.OK_STATUS; IClasspathEntry[] classPathEntries = new IClasspathEntry[libsPaths.size()]; int i = 0; subMonitor.subTask(UtilitiesNLS.ProjectUtils_AddLibsProgress_PreparingPaths); for (IPath libPath : libsPaths) { IClasspathEntry classpathEntry = JavaCore.newLibraryEntry(libPath, null, null); classPathEntries[i] = classpathEntry; i++; subMonitor.worked(1000); } subMonitor.subTask(UtilitiesNLS.ProjectUtils_AddLibsProgress_ConfiguringProjects); for (IJavaProject javaProject : javaProjects) { IClasspathEntry[] rawClasspath; try { rawClasspath = javaProject.getRawClasspath(); int length = rawClasspath.length; int newEntriesLength = classPathEntries.length; int newLenght = length + newEntriesLength; IClasspathEntry[] newClassPath = new IClasspathEntry[newLenght]; System.arraycopy(rawClasspath, 0, newClassPath, 0, length); // Copy // the // existent // classPath // to // the // new // array. System.arraycopy(classPathEntries, 0, newClassPath, length, newEntriesLength); // Copy // the // new // entries // to // the // new // array subMonitor.worked(1000); javaProject.setRawClasspath(newClassPath, subMonitor.newChild(1000)); // Set // the // Project's // classpath. } catch (JavaModelException e) { status = new Status(IStatus.ERROR, CommonPlugin.PLUGIN_ID, UtilitiesNLS.ProjectUtils_AddLibsProgress_ErrorSettingClasspaths, e); break; } } subMonitor.done(); return status; }
From source file:org.eclipse.andmore.core.AppProjectGenerator.java
License:Open Source License
@Override public void generate(Map<String, Object> model, IProgressMonitor monitor) throws CoreException { model.put("packageName", packageName); //$NON-NLS-1$ model.put("packagePath", packageName.replace('.', '/')); //$NON-NLS-1$ model.put("activityName", activityName); //$NON-NLS-1$ model.put("layoutName", layoutName); //$NON-NLS-1$ super.generate(model, monitor); IProject project = getProject();/*from ww w .j ava 2 s . c o m*/ // Do initial code generation from gradle monitor.setTaskName("Generating initial sources..."); AndroidBuilder.gradleBuild(project, "generateDebugSources", monitor); //$NON-NLS-1$ // Mark the build and .gradle folders derived project.getFolder("build").setDerived(true, monitor); //$NON-NLS-1$ project.getFolder(".gradle").setDerived(true, monitor); //$NON-NLS-1$ // Set up Java project IJavaProject javaProject = JavaCore.create(project); // Source folders IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); List<SourceRoot> srcRoots = getManifest().getSrcRoots(); List<IClasspathEntry> entries = new ArrayList<>(); if (srcRoots != null) { for (SourceRoot srcRoot : srcRoots) { IPath srcPath = project.getFolder(srcRoot.getDir()).getFullPath(); entries.add(JavaCore.newSourceEntry(srcPath)); } } // Generated source - TODO this is in the model too IPath genPath = project.getFolder("/build/generated/source/r/debug").getFullPath(); //$NON-NLS-1$ entries.add(JavaCore.newSourceEntry(genPath)); // Android Gradle container entries.add(JavaCore.newContainerEntry(AndroidClasspathContainer.path)); // JRE IVMInstall vm = JavaRuntime.getDefaultVMInstall(); IPath vmPath = JavaRuntime.newJREContainerPath(vm); entries.add(JavaCore.newContainerEntry(vmPath)); javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), monitor); }
From source file:org.eclipse.andmore.internal.build.builders.ResourceManagerBuilder.java
License:Open Source License
@SuppressWarnings("unchecked") @Override/*from w w w . java 2 s. co m*/ protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException { // Get the project. final IProject project = getProject(); IJavaProject javaProject = JavaCore.create(project); // Clear the project of the generic markers removeMarkersFromContainer(project, AndmoreAndroidConstants.MARKER_ADT); // check for existing target marker, in which case we abort. // (this means: no SDK, no target, or unresolvable target.) try { abortOnBadSetup(javaProject, null); } catch (AbortBuildException e) { return null; } // Check the compiler compliance level, displaying the error message // since this is the first builder. Pair<Integer, String> result = ProjectHelper.checkCompilerCompliance(project); String errorMessage = null; switch (result.getFirst().intValue()) { case ProjectHelper.COMPILER_COMPLIANCE_LEVEL: errorMessage = Messages.Requires_Compiler_Compliance_s; break; case ProjectHelper.COMPILER_COMPLIANCE_SOURCE: errorMessage = Messages.Requires_Source_Compatibility_s; break; case ProjectHelper.COMPILER_COMPLIANCE_CODEGEN_TARGET: errorMessage = Messages.Requires_Class_Compatibility_s; break; } if (errorMessage != null) { errorMessage = String.format(errorMessage, result.getSecond() == null ? "(no value)" : result.getSecond()); if (JavaCore.VERSION_1_7.equals(result.getSecond())) { // If the user is trying to target 1.7 but compiling with something older, // the error message can be a bit misleading; instead point them in the // direction of updating the project's build target. Sdk currentSdk = Sdk.getCurrent(); if (currentSdk != null) { IAndroidTarget target = currentSdk.getTarget(project.getProject()); if (target != null && target.getVersion().getApiLevel() < 19) { errorMessage = "Using 1.7 requires compiling with Android 4.4 " + "(KitKat); currently using " + target.getVersion(); } ProjectState projectState = Sdk.getProjectState(project); if (projectState != null) { BuildToolInfo buildToolInfo = projectState.getBuildToolInfo(); if (buildToolInfo == null) { buildToolInfo = currentSdk.getLatestBuildTool(); } if (buildToolInfo != null && buildToolInfo.getRevision().getMajor() < 19) { errorMessage = "Using 1.7 requires using Android Build Tools " + "version 19 or later; currently using " + buildToolInfo.getRevision(); } } } } markProject(AndmoreAndroidConstants.MARKER_ADT, errorMessage, IMarker.SEVERITY_ERROR); AndmoreAndroidPlugin.printErrorToConsole(project, errorMessage); return null; } // Check that the SDK directory has been setup. String osSdkFolder = AndmoreAndroidPlugin.getOsSdkFolder(); if (osSdkFolder == null || osSdkFolder.length() == 0) { AndmoreAndroidPlugin.printErrorToConsole(project, Messages.No_SDK_Setup_Error); markProject(AndmoreAndroidConstants.MARKER_ADT, Messages.No_SDK_Setup_Error, IMarker.SEVERITY_ERROR); return null; } // check the 'gen' source folder is present boolean hasGenSrcFolder = false; // whether the project has a 'gen' source folder setup IClasspathEntry[] classpaths = javaProject.readRawClasspath(); if (classpaths != null) { for (IClasspathEntry e : classpaths) { if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) { IPath path = e.getPath(); if (path.segmentCount() == 2 && path.segment(1).equals(SdkConstants.FD_GEN_SOURCES)) { hasGenSrcFolder = true; break; } } } } boolean genFolderPresent = false; // whether the gen folder actually exists IResource resource = project.findMember(SdkConstants.FD_GEN_SOURCES); genFolderPresent = resource != null && resource.exists(); if (hasGenSrcFolder == false && genFolderPresent) { // No source folder setup for 'gen' in the project, but there's already a // 'gen' resource (file or folder). String message; if (resource.getType() == IResource.FOLDER) { // folder exists already! This is an error. If the folder had been created // by the NewProjectWizard, it'd be a source folder. message = String.format( "%1$s already exists but is not a source folder. Convert to a source folder or rename it.", resource.getFullPath().toString()); } else { // resource exists but is not a folder. message = String.format( "Resource %1$s is in the way. ADT needs a source folder called 'gen' to work. Rename or delete resource.", resource.getFullPath().toString()); } AndmoreAndroidPlugin.printErrorToConsole(project, message); markProject(AndmoreAndroidConstants.MARKER_ADT, message, IMarker.SEVERITY_ERROR); return null; } else if (hasGenSrcFolder == false || genFolderPresent == false) { // either there is no 'gen' source folder in the project (older SDK), // or the folder does not exist (was deleted, or was a fresh svn checkout maybe.) // In case we are migrating from an older SDK, we go through the current source // folders and delete the generated Java files. List<IPath> sourceFolders = BaseProjectHelper.getSourceClasspaths(javaProject); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (IPath path : sourceFolders) { IResource member = root.findMember(path); if (member != null) { removeDerivedResources(member, monitor); } } // create the new source folder, if needed IFolder genFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES); if (genFolderPresent == false) { AndmoreAndroidPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, "Creating 'gen' source folder for generated Java files"); genFolder.create(true /* force */, true /* local */, new SubProgressMonitor(monitor, 10)); } // add it to the source folder list, if needed only (or it will throw) if (hasGenSrcFolder == false) { IClasspathEntry[] entries = javaProject.getRawClasspath(); entries = ProjectHelper.addEntryToClasspath(entries, JavaCore.newSourceEntry(genFolder.getFullPath())); javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 10)); } // refresh specifically the gen folder first, as it may break the build // if it doesn't arrive in time then refresh the whole project as usual. genFolder.refreshLocal(IResource.DEPTH_ZERO, new SubProgressMonitor(monitor, 10)); project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 10)); // it seems like doing this fails to properly rebuild the project. the Java builder // running right after this builder will not see the gen folder, and will not be // restarted after this build. Therefore in this particular case, we start another // build asynchronously so that it's rebuilt after this build. launchJob(new Job("rebuild") { @Override protected IStatus run(IProgressMonitor m) { try { project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, m); return Status.OK_STATUS; } catch (CoreException e) { return e.getStatus(); } } }); } // convert older projects which use bin as the eclipse output folder into projects // using bin/classes IFolder androidOutput = BaseProjectHelper.getAndroidOutputFolder(project); IFolder javaOutput = BaseProjectHelper.getJavaOutputFolder(project); if (androidOutput.exists() == false || javaOutput == null || javaOutput.getParent().equals(androidOutput) == false) { // get what we want as the new java output. IFolder newJavaOutput = androidOutput.getFolder(SdkConstants.FD_CLASSES_OUTPUT); if (androidOutput.exists() == false) { androidOutput.create(true /*force*/, true /*local*/, monitor); } if (newJavaOutput.exists() == false) { newJavaOutput.create(true /*force*/, true /*local*/, monitor); } // set the java output to this project. javaProject.setOutputLocation(newJavaOutput.getFullPath(), monitor); // need to do a full build. Can't build while we're already building, so launch a // job to build it right after this build launchJob(new Job("rebuild") { @Override protected IStatus run(IProgressMonitor jobMonitor) { try { project.build(IncrementalProjectBuilder.CLEAN_BUILD, jobMonitor); return Status.OK_STATUS; } catch (CoreException e) { return e.getStatus(); } } }); } // check that we have bin/res/ IFolder binResFolder = androidOutput.getFolder(SdkConstants.FD_RESOURCES); if (binResFolder.exists() == false) { binResFolder.create(true /* force */, true /* local */, new SubProgressMonitor(monitor, 10)); project.refreshLocal(IResource.DEPTH_ONE, new SubProgressMonitor(monitor, 10)); } // Check the preference to be sure we are supposed to refresh // the folders. if (AdtPrefs.getPrefs().getBuildForceResResfresh()) { AndmoreAndroidPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, Messages.Refreshing_Res); // refresh the res folder. IFolder resFolder = project.getFolder(AndmoreAndroidConstants.WS_RESOURCES); resFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor); // Also refresh the assets folder to make sure the ApkBuilder // will now it's changed and will force a new resource packaging. IFolder assetsFolder = project.getFolder(AndmoreAndroidConstants.WS_ASSETS); assetsFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor); } return null; }