Java Code Examples for org.eclipse.jdt.launching.JavaRuntime

The following examples show how to use org.eclipse.jdt.launching.JavaRuntime. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: codewind-eclipse   Source File: LaunchUtilities.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
* @return argsToConfigure updated with the new arguments.
*/
  public static Map<String, Connector.Argument> configureConnector(
  		Map<String, Connector.Argument> argsToConfigure, String host, int portNumber) {

      Connector.StringArgument hostArg = (Connector.StringArgument) argsToConfigure.get("hostname"); //$NON-NLS-1$
      hostArg.setValue(host);

      Connector.IntegerArgument portArg = (Connector.IntegerArgument) argsToConfigure.get("port"); //$NON-NLS-1$
      portArg.setValue(portNumber);

      Connector.IntegerArgument timeoutArg = (Connector.IntegerArgument) argsToConfigure.get("timeout"); //$NON-NLS-1$
      if (timeoutArg != null) {
          int timeout = Platform.getPreferencesService().getInt(
                                                                "org.eclipse.jdt.launching", //$NON-NLS-1$
                                                                JavaRuntime.PREF_CONNECT_TIMEOUT,
                                                                JavaRuntime.DEF_CONNECT_TIMEOUT,
                                                                null);
          timeoutArg.setValue(timeout);
      }

      return argsToConfigure;
  }
 
Example 2
/** Compute the class path for the given launch configuration.
 *
 * @param configuration the configuration that provides the classpath.
 * @param configAccessor the accessor to the SRE configuration.
 * @param projectAccessor the accessor to the Java project.
 * @return the filtered entries.
 * @throws CoreException if impossible to get the classpath.
 */
public static IRuntimeClasspathEntry[] computeUnresolvedSARLRuntimeClasspath(ILaunchConfiguration configuration,
		ILaunchConfigurationAccessor configAccessor,
		IJavaProjectAccessor projectAccessor) throws CoreException {
	// Get the classpath from the configuration.
	final IRuntimeClasspathEntry[] entries = JavaRuntime.computeUnresolvedRuntimeClasspath(configuration);
	//
	final List<IRuntimeClasspathEntry> filteredEntries = new ArrayList<>();
	List<IRuntimeClasspathEntry> sreClasspathEntries = null;
	// Filtering the entries by replacing the "SARL Libraries" with the SARL runtime environment.
	for (final IRuntimeClasspathEntry entry : entries) {
		if (entry.getPath().equals(SARLClasspathContainerInitializer.CONTAINER_ID)) {
			if (sreClasspathEntries == null) {
				sreClasspathEntries = getSREClasspathEntries(configuration, configAccessor, projectAccessor);
			}
			filteredEntries.addAll(sreClasspathEntries);
		} else {
			filteredEntries.add(entry);
		}
	}
	return filteredEntries.toArray(new IRuntimeClasspathEntry[filteredEntries.size()]);
}
 
Example 3
private IClasspathEntry handleContainerEntry(IPath containerPath, IJavaProject jproject, IPath jarPath) throws JavaModelException {
	ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(containerPath.segment(0));
	IClasspathContainer container= JavaCore.getClasspathContainer(containerPath, jproject);
	if (initializer == null || container == null) {
		setDescription(Messages.format(PreferencesMessages.NativeLibrariesPropertyPage_invalid_container, BasicElementLabels.getPathLabel(containerPath, false)));
		return null;
	}
	String containerName= container.getDescription();
	IStatus status= initializer.getAttributeStatus(containerPath, jproject, JavaRuntime.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY);
	if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_NOT_SUPPORTED) {
		setDescription(Messages.format(PreferencesMessages.NativeLibrariesPropertyPage_not_supported, containerName));
		return null;
	}
	IClasspathEntry entry= JavaModelUtil.findEntryInContainer(container, jarPath);
	if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_READ_ONLY) {
		setDescription(Messages.format(PreferencesMessages.NativeLibrariesPropertyPage_read_only, containerName));
		fIsReadOnly= true;
		return entry;
	}
	Assert.isNotNull(entry);
	return entry;
}
 
Example 4
protected List<String> getPackageFragmentRootHandles(IJavaProject project) {
	List<String> result = Lists.newArrayList();
	List<String> binaryAndNonLocalFragments = Lists.newArrayList();
	try {
		IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
		result = Lists.newArrayListWithCapacity(roots.length);
		for (IPackageFragmentRoot root : roots) {
			if (root != null && !JavaRuntime.newDefaultJREContainerPath().isPrefixOf(root.getRawClasspathEntry().getPath())) {
				if (root.getKind() == IPackageFragmentRoot.K_SOURCE && project.equals(root.getJavaProject())) {
					// treat local sources with higher priority
					// see Java behavior in SameClassNamesTest
					result.add(root.getHandleIdentifier());	
				} else {
					binaryAndNonLocalFragments.add(root.getHandleIdentifier());
				}
			}
		}
	} catch (JavaModelException e) {
		if (!e.isDoesNotExist()) {
			log.error("Cannot find rootHandles in project " + project.getProject().getName(), e);
		}
	}
	result.addAll(binaryAndNonLocalFragments);
	return result;
}
 
Example 5
private void collectReferencedElements(IJavaProject project, HashSet<JavadocLinkRef> result) throws CoreException {
	IRuntimeClasspathEntry[] unresolved = JavaRuntime.computeUnresolvedRuntimeClasspath(project);
	for (int i= 0; i < unresolved.length; i++) {
		IRuntimeClasspathEntry curr= unresolved[i];
		if (curr.getType() == IRuntimeClasspathEntry.PROJECT) {
			result.add(new JavadocLinkRef(JavaCore.create((IProject) curr.getResource())));
		} else {
			IRuntimeClasspathEntry[] entries= JavaRuntime.resolveRuntimeClasspathEntry(curr, project);
			for (int k = 0; k < entries.length; k++) {
				IRuntimeClasspathEntry entry= entries[k];
				if (entry.getType() == IRuntimeClasspathEntry.PROJECT) {
					result.add(new JavadocLinkRef(JavaCore.create((IProject) entry.getResource())));
				} else if (entry.getType() == IRuntimeClasspathEntry.ARCHIVE) {
					IClasspathEntry classpathEntry= entry.getClasspathEntry();
					if (classpathEntry != null) {
						IPath containerPath= null;
						if (curr.getType() == IRuntimeClasspathEntry.CONTAINER) {
							containerPath= curr.getPath();
						}
						result.add(new JavadocLinkRef(containerPath, classpathEntry, project));
					}
				}
			}
		}
	}
}
 
Example 6
public static void makeJava7Default() {
	if (!isJava7Default) {
		IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
		IExecutionEnvironment[] environments = manager.getExecutionEnvironments();
		for (int i = 0; i < environments.length; i++) {
			IExecutionEnvironment environment = environments[i];
			if (environment.getId().equals("JavaSE-1.6") && environment.getDefaultVM() == null) {
				IVMInstall[] compatibleVMs = environment.getCompatibleVMs();
				for (IVMInstall ivmInstall : compatibleVMs) {
					if (ivmInstall instanceof IVMInstall2) {
						IVMInstall2 install2 = (IVMInstall2) ivmInstall;
						if (install2.getJavaVersion().startsWith("1.7")) {
							environment.setDefaultVM(ivmInstall);
						}
					}
				}
			}
		}
		isJava7Default = true;
	}
}
 
Example 7
/**
 * Checks if the JRE of the given project or workspace default JRE have source compliance 1.5 or
 * greater.
 *
 * @param project the project to test or <code>null</code> to test the workspace JRE
 * @return <code>true</code> if the JRE of the given project or workspace default JRE have
 *         source compliance 1.5 or greater.
 * @throws CoreException if unable to determine the project's VM install
 */
public static boolean is50OrHigherJRE(IJavaProject project) throws CoreException {
	IVMInstall vmInstall;
	if (project == null) {
		vmInstall= JavaRuntime.getDefaultVMInstall();
	} else {
		vmInstall= JavaRuntime.getVMInstall(project);
	}
	if (!(vmInstall instanceof IVMInstall2))
		return true; // assume 1.5.

	String compliance= getCompilerCompliance((IVMInstall2) vmInstall, null);
	if (compliance == null)
		return true; // assume 1.5
	return is50OrHigher(compliance);
}
 
Example 8
protected void fixRuntimeEnvironment( String platformDir )
{
	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject( "platform" );
	IJavaProject javaProject = JavaCore.create( project );
	IVMInstall javaInstall = null;
	try
	{
		if(javaProject.isOpen())
		{
		javaInstall = JavaRuntime.getVMInstall( javaProject );
	}
	}
	catch( CoreException e )
	{
		throw new IllegalStateException( e );
	}
	if( javaInstall != null )
	{
		setHeapSize( javaInstall );
	}
}
 
Example 9
Source Project: eclipse.jdt.ls   Source File: ProjectCommand.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets the project settings.
 *
 * @param uri
 *                        Uri of the source/class file that needs to be queried.
 * @param settingKeys
 *                        the settings we want to query, for example:
 *                        ["org.eclipse.jdt.core.compiler.compliance",
 *                        "org.eclipse.jdt.core.compiler.source"].
 *                        Besides the options defined in JavaCore, the following keys can also be used:
 *                        - "org.eclipse.jdt.ls.core.vm.location": Get the location of the VM assigned to build the given Java project
 * @return A <code>Map<string, string></code> with all the setting keys and
 *         their values.
 * @throws CoreException
 * @throws URISyntaxException
 */
public static Map<String, String> getProjectSettings(String uri, List<String> settingKeys) throws CoreException, URISyntaxException {
	IJavaProject javaProject = getJavaProjectFromUri(uri);
	Map<String, String> settings = new HashMap<>();
	for (String key : settingKeys) {
		switch(key) {
			case VM_LOCATION:
				IVMInstall vmInstall = JavaRuntime.getVMInstall(javaProject);
				if (vmInstall == null) {
					continue;
				}
				File location = vmInstall.getInstallLocation();
				if (location == null) {
					continue;
				}
				settings.putIfAbsent(key, location.getAbsolutePath());
				break;
			default:
				settings.putIfAbsent(key, javaProject.getOption(key, true));
				break;
		}
	}
	return settings;
}
 
Example 10
private static IPath[] getClasspath(ILaunchConfiguration configuration) throws CoreException {
	IRuntimeClasspathEntry[] entries= JavaRuntime.computeUnresolvedRuntimeClasspath(configuration);
	entries= JavaRuntime.resolveRuntimeClasspath(entries, configuration);

	ArrayList<IPath> userEntries= new ArrayList<IPath>(entries.length);
	for (int i= 0; i < entries.length; i++) {
		if (entries[i].getClasspathProperty() == IRuntimeClasspathEntry.USER_CLASSES) {

			String location= entries[i].getLocation();
			if (location != null) {
				IPath entry= Path.fromOSString(location);
				if (!userEntries.contains(entry)) {
					userEntries.add(entry);
				}
			}
		}
	}
	return userEntries.toArray(new IPath[userEntries.size()]);
}
 
Example 11
@Test
public void testJavaHome() throws Exception {
	Preferences prefs = JavaLanguageServerPlugin.getPreferencesManager().getPreferences();
	String javaHomePreference = prefs.getJavaHome();
	IVMInstall defaultVM = JavaRuntime.getDefaultVMInstall();
	try {
		IVMInstallType installType = JavaRuntime.getVMInstallType(StandardVMType.ID_STANDARD_VM_TYPE);
		IVMInstall[] vms = installType.getVMInstalls();
		IVMInstall vm = vms[0];
		JavaRuntime.setDefaultVMInstall(vm, new NullProgressMonitor());
		String javaHome = new File(TestVMType.getFakeJDKsLocation(), "11").getAbsolutePath();
		prefs.setJavaHome(javaHome);
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		IPath rootFolder = root.getLocation().append("/projects/gradle/simple-gradle");
		BuildConfiguration build = GradleProjectImporter.getBuildConfiguration(rootFolder.toFile().toPath());
		assertEquals(vm.getInstallLocation().getAbsolutePath(), build.getJavaHome().get().getAbsolutePath());
	} finally {
		prefs.setJavaHome(javaHomePreference);
		if (defaultVM != null) {
			JavaRuntime.setDefaultVMInstall(defaultVM, new NullProgressMonitor());
		}
	}
}
 
Example 12
Source Project: sarl   Source File: ExportSarlApplicationPage.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected IPath[] getClasspath(ILaunchConfiguration configuration) throws CoreException {
	IRuntimeClasspathEntry[] entries = AbstractSARLLaunchConfigurationDelegate.computeUnresolvedSARLRuntimeClasspath(
			configuration, this.configAccessor, cfg -> getJavaProject(cfg));

	entries = JavaRuntime.resolveRuntimeClasspath(entries, configuration);

	final boolean isModularConfig = JavaRuntime.isModularConfiguration(configuration);
	final List<IPath> userEntries = new ArrayList<>(entries.length);
	for (int i = 0; i < entries.length; i++) {
		final int classPathProperty = entries[i].getClasspathProperty();
		if ((!isModularConfig && classPathProperty == IRuntimeClasspathEntry.USER_CLASSES)
				|| (isModularConfig && (classPathProperty == IRuntimeClasspathEntry.CLASS_PATH
				|| classPathProperty == IRuntimeClasspathEntry.MODULE_PATH))) {

			final String location = entries[i].getLocation();
			if (location != null) {
				final IPath entry = Path.fromOSString(location);
				if (!userEntries.contains(entry)) {
					userEntries.add(entry);
				}
			}
		}
	}
	return userEntries.toArray(new IPath[userEntries.size()]);
}
 
Example 13
Source Project: tlaplus   Source File: AbstractJob.java    License: MIT License 6 votes vote down vote up
protected IVMInstall getVMInstall() {
       IVMInstall vmInstall = null;

	// Try using the very same VM the Toolbox is running with (e.g.
	// this avoids problems when the Toolbox runs with a 64bit VM, but
	// the nested VM is a 32bit one).
       final String javaHome = System.getProperty("java.home");
       if (javaHome != null) {
           final IVMInstallType installType = new StandardVMType();
           vmInstall = installType.createVMInstall("TLCModelCheckerNestedVM");
           vmInstall.setInstallLocation(new File(javaHome));
           return vmInstall;
       }

       // get OS default VM (determined by path) not necessarily the same
	// the toolbox is running with.
       return JavaRuntime.getDefaultVMInstall();
}
 
Example 14
private ISourceContainer[] fromJavaRuntimeResolver() throws CoreException {
  for (final IClasspathEntry cpe : jp.getRawClasspath()) {
    if (IClasspathEntry.CPE_CONTAINER == cpe.getEntryKind() && //
        IClasspathManager.CONTAINER_ID.equals(cpe.getPath().toString())) {
      final IRuntimeClasspathEntry newRuntimeContainerClasspathEntry = JavaRuntime.newRuntimeContainerClasspathEntry(cpe.getPath(),
          IRuntimeClasspathEntry.USER_CLASSES, jp);

      final IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry = JavaRuntime.resolveRuntimeClasspathEntry(
          newRuntimeContainerClasspathEntry, jp);

      // there is only one maven2 classpath container in a project return
      return JavaRuntime.getSourceContainers(resolveRuntimeClasspathEntry);
    }
  }

  return new ISourceContainer[] {};
}
 
Example 15
private ISourceContainer[] fromMavenSourcePathProvider() throws CoreException {

    final IRuntimeClasspathEntry mavenEntry = JavaRuntime.newRuntimeContainerClasspathEntry(new Path(IClasspathManager.CONTAINER_ID),
        IRuntimeClasspathEntry.USER_CLASSES);

    final ILaunchConfiguration launchConfiguration = getDirector().getLaunchConfiguration();
    // final ILaunchConfigurationWorkingCopy wc = launchConfiguration.getWorkingCopy();
    // wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, getProjectName());
    // final ILaunchConfiguration doSave = wc.doSave();
    final ILaunchConfiguration javaProjectLaunchConfiguration = new JavaProjectLaunchConfiguration(launchConfiguration, this);

    final IRuntimeClasspathEntry[] resolved = mavenRuntimeClasspathProvider.resolveClasspath(new IRuntimeClasspathEntry[] {
      mavenEntry
    }, javaProjectLaunchConfiguration);

    // final IRuntimeClasspathEntry[] entries = JavaRuntime.computeUnresolvedSourceLookupPath(doSave);
    // final IRuntimeClasspathEntry[] resolved = JavaRuntime.resolveSourceLookupPath(entries, doSave);

    return JavaRuntime.getSourceContainers(resolved);
  }
 
Example 16
Source Project: uima-uimaj   Source File: DocumentUimaImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the project class loader.
 *
 * @param project the project
 * @return the project class loader
 * @throws CoreException the core exception
 */
public static ClassLoader getProjectClassLoader(IProject project) throws CoreException {
  IProjectNature javaNature = project.getNature(JAVA_NATURE);
  if (javaNature != null) {
    JavaProject javaProject = (JavaProject) JavaCore.create(project);
    
    String[] runtimeClassPath = JavaRuntime.computeDefaultRuntimeClassPath(javaProject);
    List<URL> urls = new ArrayList<>();
    for (String cp : runtimeClassPath) {
      try {
        urls.add(Paths.get(cp).toUri().toURL());
      } catch (MalformedURLException e) {
        CasEditorPlugin.log(e);
      }
    }
    return new URLClassLoader(urls.toArray(new URL[0]));
  } 
  return null;
}
 
Example 17
@Override
public URLClassLoader createClassLoader() throws SdkException, MalformedURLException {
  IJavaProject userProject = findUserProject();
  if (userProject != null) {
    IRuntimeClasspathEntry outputEntry = JavaRuntime.newDefaultProjectClasspathEntry(userProject);
    try {
      IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry =
          JavaRuntime.resolveRuntimeClasspathEntry(outputEntry, userProject);
      List<URL> urls = new ArrayList<URL>();
      for (IRuntimeClasspathEntry entry : resolveRuntimeClasspathEntry) {
        urls.add(new File(entry.getLocation()).toURI().toURL());
      }

      return new URLClassLoader(urls.toArray(NO_URLS), null);

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

  // TODO Auto-generated method stub
  return null;
}
 
Example 18
private static String computeClasspath(GwtSdk gwtRuntime, String[] extraClassPath)
    throws CoreException {
  List<String> cpPaths = new ArrayList<String>();
  for (IClasspathEntry c : gwtRuntime.getClasspathEntries()) {
    if (c.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
      IJavaProject javaProject = JavaProjectUtilities.findJavaProject(c.getPath().toOSString());
      IRuntimeClasspathEntry projectRuntimeEntry = JavaRuntime.newDefaultProjectClasspathEntry(javaProject);
      IRuntimeClasspathEntry[] resolvedEntries = JavaRuntime.resolveRuntimeClasspathEntry(
          projectRuntimeEntry, javaProject);
      for (IRuntimeClasspathEntry resolvedEntry : resolvedEntries) {
        cpPaths.add(resolvedEntry.getLocation());
      }
    } else {
      cpPaths.add(c.getPath().toFile().getAbsolutePath());
    }
  }
  if (extraClassPath != null) {
    cpPaths.addAll(Arrays.asList(extraClassPath));
  }
  return ProcessUtilities.buildClasspathString(cpPaths);
}
 
Example 19
private IExecutionEnvironment getEE() {
	if (fProject == null)
		return null;
	
	try {
		IClasspathEntry[] entries= JavaCore.create(fProject).getRawClasspath();
		for (int i= 0; i < entries.length; i++) {
			IClasspathEntry entry= entries[i];
			if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
				String eeId= JavaRuntime.getExecutionEnvironmentId(entry.getPath());
				if (eeId != null) {
					return JavaRuntime.getExecutionEnvironmentsManager().getEnvironment(eeId);
				}
			}
		}
	} catch (CoreException e) {
		JavaPlugin.log(e);
	}
	return null;
}
 
Example 20
private boolean updateClasspath(IPath newPath, IProgressMonitor monitor) throws JavaModelException {
	boolean updated= false;
	
	IClasspathEntry[] classpath= fProject.getRawClasspath();
	IPath jreContainerPath= new Path(JavaRuntime.JRE_CONTAINER);
	for (int i= 0; i < classpath.length; i++) {
		IClasspathEntry curr= classpath[i];
		if (curr.getEntryKind() == IClasspathEntry.CPE_CONTAINER && curr.getPath().matchingFirstSegments(jreContainerPath) > 0) {
			if (! newPath.equals(curr.getPath())) {
				updated= true;
				classpath[i]= JavaCore.newContainerEntry(newPath, curr.getAccessRules(), curr.getExtraAttributes(), curr.isExported());
			}
		}
	}
	if (updated) {
		fProject.setRawClasspath(classpath, monitor);
	}
	return updated;
}
 
Example 21
@Override
public boolean isValid(ILaunchConfiguration launchConfig) {
  setErrorMessage(null);
  setMessage(null);

  if (!super.isValid(launchConfig)) {
    return false;
  }

  IProject project;
  try {
    IJavaProject javaProject = JavaRuntime.getJavaProject(launchConfig);
    if (javaProject == null) {
      return false;
    }

    project = javaProject.getProject();
  } catch (CoreException ce) {
    // Thrown if the Java project does not exist, which is not of concern in
    // this tab (the Main tab handles those error messages)
    return false;
  }

  return true;
}
 
Example 22
private IVMInstall findRequiredOrGreaterVMInstall() {
	String bestMatchingCompliance= null;
	IVMInstall bestMatchingVMInstall= null;
	IVMInstallType[] installTypes= JavaRuntime.getVMInstallTypes();
	for (int i= 0; i < installTypes.length; i++) {
		IVMInstall[] installs= installTypes[i].getVMInstalls();
		for (int k= 0; k < installs.length; k++) {
			String vmInstallCompliance= getVMInstallCompliance(installs[k]);
			
			if (fRequiredVersion.equals(vmInstallCompliance)) {
				return installs[k]; // perfect match
				
			} else if (JavaModelUtil.isVersionLessThan(vmInstallCompliance, fRequiredVersion)) {
				continue; // no match
				
			} else if (bestMatchingVMInstall != null) {
				if (JavaModelUtil.isVersionLessThan(bestMatchingCompliance, vmInstallCompliance)) {
					continue; // the other one is the least matching
				}
			}
			bestMatchingCompliance= vmInstallCompliance;
			bestMatchingVMInstall= installs[k];
		}
	}
	return null;
}
 
Example 23
protected String javaBinaryLocation() throws FileNotFoundException {
    IVMInstall defaultVMInstall = JavaRuntime.getDefaultVMInstall();
    if (defaultVMInstall == null) {
        throw new FileNotFoundException("Default VM not installed");
    }
    File javaBinaryPath = StandardVMType.findJavaExecutable(defaultVMInstall.getInstallLocation());
    if (javaBinaryPath == null) {
        throw new FileNotFoundException("Java binary not configured");
    } else if (!javaBinaryPath.exists()) {
        throw new FileNotFoundException(
                String.format("Java binary not found at '%s'", javaBinaryPath.getAbsolutePath()));
    }
    return javaBinaryPath.getAbsolutePath();
}
 
Example 24
/**
 * Compute runtime classpath of a java project.
 *
 * @param javaProject java project
 * @param excludeTestCode whether to exclude the test code and test dependencies
 * @param mappedResources the associated resources with the application
 * @return class path
 * @throws CoreException
 *             CoreException
 */
private static String[][] computeClassPath(IJavaProject javaProject, String mainType, boolean excludeTestCode, List<IResource> mappedResources)
        throws CoreException {
    if (javaProject == null) {
        throw new IllegalArgumentException("javaProject is null");
    }

    ILaunchConfiguration launchConfig = new JavaApplicationLaunchConfiguration(javaProject.getProject(), mainType, excludeTestCode, mappedResources);
    IRuntimeClasspathEntry[] unresolved = JavaRuntime.computeUnresolvedRuntimeClasspath(launchConfig);
    IRuntimeClasspathEntry[] resolved = JavaRuntime.resolveRuntimeClasspath(unresolved, launchConfig);
    Set<String> classpaths = new LinkedHashSet<>();
    Set<String> modulepaths = new LinkedHashSet<>();
    for (IRuntimeClasspathEntry entry : resolved) {
        String location = entry.getLocation();
        if (location != null) {
            if (entry.getClasspathProperty() == IRuntimeClasspathEntry.USER_CLASSES
                    || entry.getClasspathProperty() == IRuntimeClasspathEntry.CLASS_PATH) {
                classpaths.add(location);
            } else if (entry.getClasspathProperty() == IRuntimeClasspathEntry.MODULE_PATH) {
                modulepaths.add(location);
            }
        }
    }

    return new String[][] {
        modulepaths.toArray(new String[modulepaths.size()]),
        classpaths.toArray(new String[classpaths.size()])
    };
}
 
Example 25
private int getErrorTicksFromMarkers(IResource res, int depth, ISourceReference sourceElement) throws CoreException {
	if (res == null || !res.isAccessible()) {
		return 0;
	}
	int severity= 0;
	if (sourceElement == null) {
		if (res instanceof IProject) {
			severity= res.findMaxProblemSeverity(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, IResource.DEPTH_ZERO);
			if (severity == IMarker.SEVERITY_ERROR) {
				return ERRORTICK_BUILDPATH_ERROR;
			}
			severity= res.findMaxProblemSeverity(JavaRuntime.JRE_CONTAINER_MARKER, true, IResource.DEPTH_ZERO);
			if (severity == IMarker.SEVERITY_ERROR) {
				return ERRORTICK_BUILDPATH_ERROR;
			}
		}
		severity= res.findMaxProblemSeverity(IMarker.PROBLEM, true, depth);
	} else {
		IMarker[] markers= res.findMarkers(IMarker.PROBLEM, true, depth);
		if (markers != null && markers.length > 0) {
			for (int i= 0; i < markers.length && (severity != IMarker.SEVERITY_ERROR); i++) {
				IMarker curr= markers[i];
				if (isMarkerInRange(curr, sourceElement)) {
					int val= curr.getAttribute(IMarker.SEVERITY, -1);
					if (val == IMarker.SEVERITY_WARNING || val == IMarker.SEVERITY_ERROR) {
						severity= val;
					}
				}
			}
		}
	}
	if (severity == IMarker.SEVERITY_ERROR) {
		return ERRORTICK_ERROR;
	} else if (severity == IMarker.SEVERITY_WARNING) {
		return ERRORTICK_WARNING;
	}
	return 0;
}
 
Example 26
private void validateComplianceStatus() {
		if (fJRE50InfoText != null && !fJRE50InfoText.isDisposed()) {
			boolean isVisible= false;
			String compliance= getStoredValue(PREF_COMPLIANCE); // get actual value
			IVMInstall install= null;
			if (fProject != null) { // project specific settings: only test if a 50 JRE is installed
				try {
					install= JavaRuntime.getVMInstall(JavaCore.create(fProject));
				} catch (CoreException e) {
					JavaPlugin.log(e);
				}
			} else {
				install= JavaRuntime.getDefaultVMInstall();
			}
			if (install instanceof IVMInstall2) {
				String compilerCompliance= JavaModelUtil.getCompilerCompliance((IVMInstall2) install, compliance);
				if (!compilerCompliance.equals(compliance)) { // Discourage using compiler with version other than compliance
					String[] args= { getVersionLabel(compliance), getVersionLabel(compilerCompliance) };
					if (fProject == null) {
						fJRE50InfoText.setText(Messages.format(PreferencesMessages.ComplianceConfigurationBlock_jrecompliance_info, args));
					} else {
						fJRE50InfoText.setText(Messages.format(PreferencesMessages.ComplianceConfigurationBlock_jrecompliance_info_project, args));
					}
					isVisible= true;
				}
			}
			
//			String source= getValue(PREF_SOURCE_COMPATIBILITY);
//			if (VERSION_1_8.equals(source)) {
//				fJRE50InfoText.setText("This is an implementation of an early-draft specification developed under the Java Community Process (JCP) and is made available for testing and evaluation purposes only. The code is not compatible with any specification of the JCP."); //$NON-NLS-1$
//				isVisible= true;
//			}
			
			fJRE50InfoText.setVisible(isVisible);
			fJRE50InfoImage.setImage(isVisible ? JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_WARNING) : null);
			fJRE50InfoImage.getParent().layout();
		}
	}
 
Example 27
private void fillExecutionEnvironments(ComboDialogField comboField) {
	String selectedItem= getLastSelectedEE();
	int selectionIndex= -1;
	if (fUseEEJRE.isSelected()) {
		selectionIndex= comboField.getSelectionIndex();
		if (selectionIndex != -1) {// paranoia
			selectedItem= comboField.getItems()[selectionIndex];
		}
	}

	fInstalledEEs= JavaRuntime.getExecutionEnvironmentsManager().getExecutionEnvironments();
	Arrays.sort(fInstalledEEs, new Comparator<IExecutionEnvironment>() {
		public int compare(IExecutionEnvironment arg0, IExecutionEnvironment arg1) {
			return Policy.getComparator().compare(arg0.getId(), arg1.getId());
		}
	});
	selectionIndex= -1;//find new index
	String[] eeLabels= new String[fInstalledEEs.length];
	fEECompliance= new String[fInstalledEEs.length];
	for (int i= 0; i < fInstalledEEs.length; i++) {
		eeLabels[i]= fInstalledEEs[i].getId();
		if (selectedItem != null && eeLabels[i].equals(selectedItem)) {
			selectionIndex= i;
		}
		fEECompliance[i]= JavaModelUtil.getExecutionEnvironmentCompliance(fInstalledEEs[i]);
	}
	comboField.setItems(eeLabels);
	if (selectionIndex == -1) {
		comboField.selectItem(getDefaultEEName());
	} else {
		comboField.selectItem(selectedItem);
	}
}
 
Example 28
@Override
protected StagingDelegate getStagingDelegate(IProject project) {
  Path javaHome = null;
  try {
    IJavaProject javaProject = JavaCore.create(project);
    IVMInstall vmInstall = JavaRuntime.getVMInstall(javaProject);
    if (vmInstall != null) {
      javaHome = vmInstall.getInstallLocation().toPath();
    }
  } catch (CoreException ex) {
    // Give up.
  }
  return new StandardStagingDelegate(project, javaHome);
}
 
Example 29
@VisibleForTesting
static IPath getJreContainerPath(IProject project) throws CoreException {
  IJavaProject javaProject = JavaCore.create(project);
  for (IClasspathEntry entry : javaProject.getRawClasspath()) {
    if (JavaRuntime.JRE_CONTAINER.equals(entry.getPath().segment(0))) {
      return entry.getPath();
    }
  }
  throw new CoreException(StatusUtil.error(FlexMavenPackagedProjectStagingDelegate.class,
      "Project " + project.getName() + " does not have JRE configured."));
}
 
Example 30
Source Project: google-cloud-eclipse   Source File: DataflowCorePlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void start(BundleContext context) throws Exception {
  super.start(context);
  plugin = this;
  // Initalizes the compliance options to include the default VM's compliance level.
  JavaRuntime.getDefaultVMInstall();
}