Java Code Examples for org.eclipse.jdt.internal.corext.util.JavaModelUtil#isVersionLessThan()

The following examples show how to use org.eclipse.jdt.internal.corext.util.JavaModelUtil#isVersionLessThan() . 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 File: GenerateToStringHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static TextEdit generateToString(IType type, LspVariableBinding[] fields) {
	if (type == null || type.getCompilationUnit() == null) {
		return null;
	}

	Preferences preferences = JavaLanguageServerPlugin.getPreferencesManager().getPreferences();
	ToStringGenerationSettingsCore settings = new ToStringGenerationSettingsCore();
	settings.overrideAnnotation = true;
	settings.createComments = preferences.isCodeGenerationTemplateGenerateComments();
	settings.useBlocks = preferences.isCodeGenerationTemplateUseBlocks();
	settings.stringFormatTemplate = StringUtils.isBlank(preferences.getGenerateToStringTemplate()) ? DEFAULT_TEMPLATE : preferences.getGenerateToStringTemplate();
	settings.toStringStyle = getToStringStyle(preferences.getGenerateToStringCodeStyle());
	settings.skipNulls = preferences.isGenerateToStringSkipNullValues();
	settings.customArrayToString = preferences.isGenerateToStringListArrayContents();
	settings.limitElements = preferences.getGenerateToStringLimitElements() > 0;
	settings.limitValue = Math.max(preferences.getGenerateToStringLimitElements(), 0);
	settings.customBuilderSettings = new CustomBuilderSettings();
	if (type.getCompilationUnit().getJavaProject() != null) {
		String version = type.getCompilationUnit().getJavaProject().getOption(JavaCore.COMPILER_SOURCE, true);
		settings.is50orHigher = !JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_5);
		settings.is60orHigher = !JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_6);
	}

	return generateToString(type, fields, settings);
}
 
Example 2
Source File: ReorgCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 3
Source File: SnippetCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static CompletionItem getRecordSnippet(SnippetCompletionContext scc, IProgressMonitor monitor) {
	ICompilationUnit cu = scc.getCompilationUnit();
	IJavaProject javaProject = cu.getJavaProject();
	if (javaProject == null) {
		return null;
	}
	String version = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
	if (JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_14)) {
		//not checking if preview features are enabled, as Java 14+ might support records without preview flag
		return null;
	}
	if (!accept(cu, scc.getCompletionContext(), false /* Or should it be true???*/)) {
		return null;
	}
	if (monitor.isCanceled()) {
		return null;
	}
	final CompletionItem recordSnippet = new CompletionItem();
	recordSnippet.setFilterText(RECORD_SNIPPET_LABEL);
	recordSnippet.setLabel(RECORD_SNIPPET_LABEL);
	recordSnippet.setSortText(SortTextHelper.convertRelevance(0));

	try {
		CodeGenerationTemplate template = (scc.needsPublic(monitor)) ? CodeGenerationTemplate.RECORDSNIPPET_PUBLIC : CodeGenerationTemplate.RECORDSNIPPET_DEFAULT;
		recordSnippet.setInsertText(getSnippetContent(scc, template, true));
		setFields(recordSnippet, cu);
	} catch (CoreException e) {
		JavaLanguageServerPlugin.log(e.getStatus());
		return null;
	}
	return recordSnippet;
}
 
Example 4
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addOverrideAnnotation(IJavaProject project, ASTRewrite rewrite, MethodDeclaration decl, IMethodBinding binding) {
	if (binding.getDeclaringClass().isInterface()) {
		String version= project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
		if (JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_6))
			return; // not allowed in 1.5
		if (JavaCore.DISABLED.equals(project.getOption(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION_FOR_INTERFACE_METHOD_IMPLEMENTATION, true)))
			return; // user doesn't want to use 1.6 style
	}
	
	Annotation marker= rewrite.getAST().newMarkerAnnotation();
	marker.setTypeName(rewrite.getAST().newSimpleName("Override")); //$NON-NLS-1$
	rewrite.getListRewrite(decl, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(marker, null);
}
 
Example 5
Source File: GenerateToStringAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
CodeGenerationSettings createSettings(IType type, SourceActionDialog dialog) {
	ToStringGenerationSettings settings= ((GenerateToStringDialog) dialog).getGenerationSettings();
	super.createSettings(type, dialog).setSettings(settings);
	settings.createComments= dialog.getGenerateComment();
	settings.useBlocks= useBlocks(type.getJavaProject());
	String version= fUnit.getJavaElement().getJavaProject().getOption(JavaCore.COMPILER_SOURCE, true);
	settings.is50orHigher= !JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_5);
	settings.is60orHigher= !JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_6);
	return settings;
}
 
Example 6
Source File: ReorgCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isRequiredOrGreaterVMInstall(IVMInstall install) {
	if (install instanceof IVMInstall2) {
		String compliance= JavaModelUtil.getCompilerCompliance((IVMInstall2) install, JavaCore.VERSION_1_3);
		return !JavaModelUtil.isVersionLessThan(compliance, fRequiredVersion);
	}
	return false;
}
 
Example 7
Source File: ReorgCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IExecutionEnvironment findBestMatchingEE() {
	IExecutionEnvironmentsManager eeManager= JavaRuntime.getExecutionEnvironmentsManager();
	IExecutionEnvironment[] ees= eeManager.getExecutionEnvironments();
	IExecutionEnvironment bestEE= null;
	String bestEECompliance= null;
	
	for (int i= 0; i < ees.length; i++) {
		IExecutionEnvironment ee= ees[i];
		String eeCompliance= JavaModelUtil.getExecutionEnvironmentCompliance(ee);
		String eeId= ee.getId();
		
		if (fRequiredVersion.equals(eeCompliance)) {
			if (eeId.startsWith("J") && eeId.endsWith(fRequiredVersion)) { //$NON-NLS-1$
				bestEE= ee;
				break; // perfect match
			}
			
		} else if (JavaModelUtil.isVersionLessThan(eeCompliance, fRequiredVersion)) {
			continue; // no match
			
		} else { // possible match
			if (bestEE != null) {
				if (! eeId.startsWith("J")) { //$NON-NLS-1$
					continue; // avoid taking e.g. OSGi profile if a Java profile is available
				}
				if (JavaModelUtil.isVersionLessThan(bestEECompliance, eeCompliance)) {
					continue; // the other one is the least matching
				}
			}
		}
		// found a new best
		bestEE= ee;
		bestEECompliance= eeCompliance;
	}
	return bestEE;
}
 
Example 8
Source File: ContributedProcessorDescriptor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean matches(ICompilationUnit cunit) {
	if (fRequiredSourceLevel != null) {
		String current= cunit.getJavaProject().getOption(JavaCore.COMPILER_SOURCE, true);
		if (JavaModelUtil.isVersionLessThan(current, fRequiredSourceLevel)) {
			return false;
		}
	}

	if (fStatus != null) {
		return fStatus.booleanValue();
	}

	IConfigurationElement[] children= fConfigurationElement.getChildren(ExpressionTagNames.ENABLEMENT);
	if (children.length == 1) {
		try {
			ExpressionConverter parser= ExpressionConverter.getDefault();
			Expression expression= parser.perform(children[0]);
			EvaluationContext evalContext= new EvaluationContext(null, cunit);
			evalContext.addVariable("compilationUnit", cunit); //$NON-NLS-1$
			IJavaProject javaProject= cunit.getJavaProject();
			String[] natures= javaProject.getProject().getDescription().getNatureIds();
			evalContext.addVariable("projectNatures", Arrays.asList(natures)); //$NON-NLS-1$
			evalContext.addVariable("sourceLevel", javaProject.getOption(JavaCore.COMPILER_SOURCE, true)); //$NON-NLS-1$
			return expression.evaluate(evalContext) == EvaluationResult.TRUE;
		} catch (CoreException e) {
			JavaPlugin.log(e);
		}
		return false;
	}
	fStatus= Boolean.FALSE;
	return false;
}
 
Example 9
Source File: ComplianceConfigurationBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IStatus validateCompliance() {
	StatusInfo status= new StatusInfo();
	String compliance= getValue(PREF_COMPLIANCE);
	String source= getValue(PREF_SOURCE_COMPATIBILITY);
	String target= getValue(PREF_CODEGEN_TARGET_PLATFORM);
	
	if (ComplianceConfigurationBlock.VERSION_JSR14.equals(target)) {
		target= source;
	}

	// compliance must not be smaller than source or target
	if (JavaModelUtil.isVersionLessThan(compliance, source)) {
		status.setError(PreferencesMessages.ComplianceConfigurationBlock_src_greater_compliance);
		return status;
	}

	if (JavaModelUtil.isVersionLessThan(compliance, target)) {
		status.setError(PreferencesMessages.ComplianceConfigurationBlock_classfile_greater_compliance);
		return status;
	}

	if (VERSION_CLDC_1_1.equals(target)) {
		if (!VERSION_1_3.equals(source) || !JavaModelUtil.isVersionLessThan(compliance, VERSION_1_5)) {
			status.setError(PreferencesMessages.ComplianceConfigurationBlock_cldc11_requires_source13_compliance_se14);
			return status;
		}
	}

	// target must not be smaller than source
	if (!VERSION_1_3.equals(source) && JavaModelUtil.isVersionLessThan(target, source)) {
		status.setError(PreferencesMessages.ComplianceConfigurationBlock_classfile_greater_source);
		return status;
	}

	return status;
}
 
Example 10
Source File: JavadocCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private String createTypeTags(IDocument document, int offset, String indentation, String lineDelimiter, IType type) throws CoreException, BadLocationException {
	if (!accept(offset, type)) {
		return null;
	}
	CompilationUnit unit = SharedASTProviderCore.getAST(type.getTypeRoot(), SharedASTProviderCore.WAIT_ACTIVE_ONLY, null);
	if (unit == null) {
		return null;
	}
	String version = type.getJavaProject().getOption(JavaCore.COMPILER_COMPLIANCE, true);
	String[] typeParamNames = null;
	boolean isRecord = false;
	if (!JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_14)) {
		ISourceRange range = type.getNameRange();
		ASTNode node = NodeFinder.perform(unit, range.getOffset(), range.getLength()).getParent();
		if (node instanceof RecordDeclaration) {
			List components = ((RecordDeclaration) node).recordComponents();
			List<String> paramList = new ArrayList<>(components.size());
			for (Object o : components) {
				if (o instanceof VariableDeclaration) {
					paramList.add(((VariableDeclaration) o).getName().getFullyQualifiedName());
				}
			}
			typeParamNames = paramList.toArray(new String[0]);
			isRecord = true;
		}
	}
	if (typeParamNames == null) {
		typeParamNames = StubUtility.getTypeParameterNames(type.getTypeParameters());
	}
	String comment = CodeGeneration.getTypeComment(type.getCompilationUnit(), type.getTypeQualifiedName('.'), typeParamNames, lineDelimiter);
	if (comment != null) {
		if (isRecord) {
			String[] lines = comment.split(System.getProperty("line.separator"));
			for (int i = 0; i < lines.length; i++) {
				if (lines[i].contains("param <")) {
					lines[i] = lines[i].replace("<", "").replace(">", "");
				}
			}
			comment = String.join(System.getProperty("line.separator"), lines);
		}
		return prepareTemplateComment(comment.trim(), indentation, type.getJavaProject(), lineDelimiter);
	}
	return null;
}
 
Example 11
Source File: ComplianceConfigurationBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void validateSettings(Key changedKey, String oldValue, String newValue) {
	if (!areSettingsEnabled()) {
		return;
	}
	if (changedKey != null) {
		if (INTR_DEFAULT_COMPLIANCE.equals(changedKey)) {
			updateComplianceEnableState();
			updateComplianceDefaultSettings(true, null);
			fComplianceStatus= validateCompliance();
		} else if (INTR_COMPLIANCE_FOLLOWS_EE.equals(changedKey)) {
			setValue(INTR_DEFAULT_COMPLIANCE, DEFAULT_CONF);
			updateComplianceEnableState();
			updateComplianceDefaultSettings(true, null);
			updateControls();
			fComplianceStatus= validateCompliance();
			validateComplianceStatus();
		} else if (PREF_COMPLIANCE.equals(changedKey)) {
		    // set compliance settings to default
		    Object oldDefault= getValue(INTR_DEFAULT_COMPLIANCE);
			boolean rememberOld= USER_CONF.equals(oldDefault);
			updateComplianceDefaultSettings(rememberOld, oldValue);
			fComplianceStatus= validateCompliance();
			validateComplianceStatus();
		} else if (PREF_SOURCE_COMPATIBILITY.equals(changedKey)) {
			updateAssertEnumAsIdentifierEnableState();
			fComplianceStatus= validateCompliance();
		} else if (PREF_CODEGEN_TARGET_PLATFORM.equals(changedKey)) {
			if (VERSION_CLDC_1_1.equals(newValue) && !oldValue.equals(newValue)) {
				String compliance= getValue(PREF_COMPLIANCE);
				String source= getValue(PREF_SOURCE_COMPATIBILITY);
				if (!JavaModelUtil.isVersionLessThan(compliance, VERSION_1_5)) {
					setValue(PREF_COMPLIANCE, VERSION_1_4);
				}
				if (!VERSION_1_3.equals(source)) {
					setValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_3);
				}
			}
			updateControls();
			updateInlineJSREnableState();
			updateStoreMethodParamNamesEnableState();
			updateAssertEnumAsIdentifierEnableState();
			fComplianceStatus= validateCompliance();
		} else if (PREF_PB_ENUM_AS_IDENTIFIER.equals(changedKey) ||
				PREF_PB_ASSERT_AS_IDENTIFIER.equals(changedKey)) {
			fComplianceStatus= validateCompliance();
		} else {
			return;
		}
	} else {
		updateComplianceFollowsEE();
		updateControls();
		updateComplianceEnableState();
		updateAssertEnumAsIdentifierEnableState();
		updateInlineJSREnableState();
		updateStoreMethodParamNamesEnableState();
		fComplianceStatus= validateCompliance();
		validateComplianceStatus();
	}
	fContext.statusChanged(fComplianceStatus);
}