org.eclipse.xtext.util.Strings Java Examples

The following examples show how to use org.eclipse.xtext.util.Strings. 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: sarl   Author: sarl   File: JavaInlineExpressionCompiler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void appendInlineAnnotation(JvmAnnotationTarget target, XtendExecutable source) {
	final ImportManager imports = new ImportManager();
	final InlineAnnotationTreeAppendable result = newAppendable(imports);
	generate(source.getExpression(), null, source, result);

	final String content = result.getContent();
	if (!Strings.isEmpty(content)) {
		final List<String> importedTypes = imports.getImports();
		final JvmTypeReference[] importArray = new JvmTypeReference[importedTypes.size()];
		for (int i = 0; i < importArray.length; ++i) {
			importArray[i] = this.typeReferences.getTypeForName(importedTypes.get(i), source);
		}
		appendInlineAnnotation(target, source.eResource().getResourceSet(), content,
				result.isConstant(), result.isStatement(), importArray);
	}
}
 
Example #2
Source Project: sarl   Author: sarl   File: SarlSpecificTypeSelectionExtension.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ImageDescriptor getImageDescriptor(ITypeInfoRequestor typeInfoRequestor) {
	QualifiedName qualifiedName;
	final String enclosing = typeInfoRequestor.getEnclosingName();
	if (Strings.isEmpty(enclosing)) {
		final String packageName = typeInfoRequestor.getPackageName();
		if (Strings.isEmpty(packageName)) {
			qualifiedName = null;
		} else {
			qualifiedName = this.converter.toQualifiedName(packageName);
		}
	} else {
		qualifiedName = this.converter.toQualifiedName(enclosing);
	}
	final QualifiedName qn = this.converter.toQualifiedName(typeInfoRequestor.getTypeName());
	if (qualifiedName == null) {
		qualifiedName = qn;
	} else {
		qualifiedName = qualifiedName.append(qn);
	}
	return this.imageProvider.getImageDescriptorForQualifiedName(qualifiedName, this.typeProvider.getResourceSet(),
			this.typeProvider);
}
 
Example #3
Source Project: n4js   Author: eclipse   File: OctalIntValueConverter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public BigDecimal toValue(String string, INode node) {
	if (Strings.isEmpty(string))
		throw new N4JSValueConverterException(IssueCodes.getMessageForVCO_OCTALINT_CONVERT_EMPTY_STR(),
				IssueCodes.VCO_OCTALINT_CONVERT_EMPTY_STR, node, null);
	if (string.length() <= 2) {
		throw new N4JSValueConverterWithValueException(
				IssueCodes.getMessageForVCO_OCTALINT_CONVERT_TOO_SHORT(string),
				IssueCodes.VCO_OCTALINT_CONVERT_TOO_SHORT, node,
				BigDecimal.ZERO, null);
	}
	try {
		return new BigDecimal(new BigInteger(string.substring(2), 8));
	} catch (NumberFormatException e) {
		throw new N4JSValueConverterException(IssueCodes.getMessageForVCO_OCTALINT_CONVERT_STR(string),
				IssueCodes.VCO_OCTALINT_CONVERT_STR, node, null);
	}
}
 
Example #4
Source Project: n4js   Author: eclipse   File: BinaryIntValueConverter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public BigDecimal toValue(String string, INode node) {
	if (Strings.isEmpty(string))
		throw new N4JSValueConverterException(IssueCodes.getMessageForVCO_BINARYINT_CONVERT_EMPTY_STR(),
				IssueCodes.VCO_BINARYINT_CONVERT_EMPTY_STR, node, null);
	if (string.length() <= 2) {
		throw new N4JSValueConverterWithValueException(
				IssueCodes.getMessageForVCO_BINARYINT_CONVERT_TOO_SHORT(string),
				IssueCodes.VCO_BINARYINT_CONVERT_TOO_SHORT, node,
				BigDecimal.ZERO, null);
	}
	try {
		return new BigDecimal(new BigInteger(string.substring(2), 2));
	} catch (NumberFormatException e) {
		throw new N4JSValueConverterException(IssueCodes.getMessageForVCO_HEXINT_CONVERT_STR(string),
				IssueCodes.VCO_HEXINT_CONVERT_STR, node, null);
	}
}
 
Example #5
Source Project: xtext-extras   Author: eclipse   File: XbaseImportedNamespaceScopeProvider.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Create a new {@link ImportNormalizer} for the given namespace.
 * @param namespace the namespace.
 * @param ignoreCase <code>true</code> if the resolver should be case insensitive.
 * @return a new {@link ImportNormalizer} or <code>null</code> if the namespace cannot be converted to a valid
 * qualified name.
 */
protected ImportNormalizer createImportedNamespaceResolver(final String namespace, boolean ignoreCase) {
	if (Strings.isEmpty(namespace))
		return null;
	QualifiedName importedNamespace = qualifiedNameConverter.toQualifiedName(namespace);
	if (importedNamespace == null || importedNamespace.isEmpty()) {
		return null;
	}
	boolean hasWildCard = ignoreCase ? 
			importedNamespace.getLastSegment().equalsIgnoreCase(getWildCard()) :
			importedNamespace.getLastSegment().equals(getWildCard());
	if (hasWildCard) {
		if (importedNamespace.getSegmentCount() <= 1)
			return null;
		return doCreateImportNormalizer(importedNamespace.skipLast(1), true, ignoreCase);
	} else {
		return doCreateImportNormalizer(importedNamespace, false, ignoreCase);
	}
}
 
Example #6
Source Project: sarl   Author: sarl   File: SARLJvmGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void _internalDoGenerate(JvmDeclaredType type, IFileSystemAccess fsa) {
	if (DisableCodeGenerationAdapter.isDisabled(type)) {
		return;
	}
	final String qn = type.getQualifiedName();
	if (!Strings.isEmpty(qn)) {
		final String fn = qn.replace('.', '/') + ".java"; //$NON-NLS-1$
		final CharSequence content = generateType(type, this.generatorConfigProvider.get(type));
		final String outputConfigurationName;
		final Boolean isTest = this.resourceTypeDetector.isTestResource(type.eResource());
		if (isTest != null && isTest.booleanValue()) {
			outputConfigurationName = SARLConfig.TEST_OUTPUT_CONFIGURATION;
		} else {
			outputConfigurationName = IFileSystemAccess.DEFAULT_OUTPUT;
		}
		fsa.generateFile(fn, outputConfigurationName, content);
	}
}
 
Example #7
Source Project: xtext-xtend   Author: eclipse   File: Bug440858Test.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test_02() throws Exception {
  ContentAssistProcessorTestBuilder _newBuilder = this.newBuilder();
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("annotation MyTest {");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("static class MyInner {");
  _builder.newLine();
  _builder.append("\t\t");
  _builder.append("<|>");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("}");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  _newBuilder.append(_builder.toString()).assertProposalAtCursor(Strings.toPlatformLineSeparator("\n\t\toverride toString() {\n\t\t\tsuper.toString()\n\t\t}\n\t\t"));
}
 
Example #8
Source Project: xtext-xtend   Author: eclipse   File: WorkingCopyOwnerProviderTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testWorkingCopyOwner_02() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package foo");
    _builder.newLine();
    _builder.append("class MyClass {");
    _builder.newLine();
    _builder.append("\t");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    this.workbenchTestHelper.createFile("foo/MyClass.xtend", _builder.toString());
    IResourcesSetupUtil.waitForBuild();
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("package foo;");
    _builder_1.newLine();
    _builder_1.append("public class MyClass{");
    _builder_1.newLine();
    _builder_1.append("}");
    Assert.assertEquals(Strings.toUnixLineSeparator(_builder_1).toString(), this.newWorkingCopyOwner().findSource("MyClass", "foo"));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #9
Source Project: sarl   Author: sarl   File: IssueInformationPage.java    License: Apache License 2.0 6 votes vote down vote up
/** Update the page status and change the "finish" state button.
 */
protected void updatePageStatus() {
	final boolean ok;
	if (Strings.isEmpty(this.titleField.getText())) {
		ok = false;
		setMessage(Messages.IssueInformationPage_5, IMessageProvider.ERROR);
	} else if (Strings.isEmpty(this.trackerLogin.getText())) {
		ok = false;
		setMessage(Messages.IssueInformationPage_6, IMessageProvider.ERROR);
	} else if (Strings.isEmpty(this.trackerPassword.getText())) {
		ok = false;
		setMessage(Messages.IssueInformationPage_7, IMessageProvider.ERROR);
	} else {
		ok = true;
		if (Strings.isEmpty(this.descriptionField.getText())) {
			setMessage(Messages.IssueInformationPage_8, IMessageProvider.WARNING);
		} else {
			setMessage(null, IMessageProvider.NONE);
		}
	}
	setPageComplete(ok);
}
 
Example #10
Source Project: sarl   Author: sarl   File: SarlBehaviorImplCustom.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isStrictFloatingPoint() {
	for (final String modifier : getModifiers()) {
		if (Strings.equal(modifier, "strictfp")) {  //$NON-NLS-1$
			return true;
		}
	}
	return false;
}
 
Example #11
Source Project: sarl   Author: sarl   File: AbstractConversionTable.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue(Object element, String property) {
	final ConversionMapping pair = (ConversionMapping) element;
	if (Strings.equal(this.targetColumnPropertyName, property)) {
		return pair.getTarget();
	}
	if (Strings.equal(this.sourceColumnPropertyName, property)) {
		return pair.getSource();
	}
	return createDefaultValue();
}
 
Example #12
Source Project: xtext-xtend   Author: eclipse   File: XtendBatchCompiler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected List<String> getDirectories(String path) {
	if (Strings.isEmpty(path)) {
		return Lists.newArrayList();
	}
	final List<String> split = split(emptyIfNull(path), File.pathSeparator);
	return transform(split, new Function<String, String>() {
		@Override
		public String apply(String from) {
			return new File(new File(from).getAbsoluteFile().toURI().normalize()).getAbsolutePath();
		}
	});
}
 
Example #13
Source Project: sarl   Author: sarl   File: MarkdownParser.java    License: Apache License 2.0 5 votes vote down vote up
/** Create the id of a section header.
 *
 * <p>The ID format follows the ReadCarpet standards.
 *
 * @param header the section header text.
 * @return the identifier.
 * @since 0.12
 */
private String computeHeaderIdForText(String header) {
	String id = header.replaceAll("[^a-zA-Z0-9]+", "-"); //$NON-NLS-1$ //$NON-NLS-2$
	id = id.toLowerCase();
	id = id.replaceFirst("^[^a-zA-Z0-9]+", ""); //$NON-NLS-1$ //$NON-NLS-2$
	id = id.replaceFirst("[^a-zA-Z0-9]+$", ""); //$NON-NLS-1$ //$NON-NLS-2$
	if (Strings.isEmpty(id)) {
		return "section"; //$NON-NLS-1$
	}
	return id;
}
 
Example #14
Source Project: sarl   Author: sarl   File: DynamicValidationContext.java    License: Apache License 2.0 5 votes vote down vote up
private static void appendSafeFileExistenceTest(ITreeAppendable receiver, File fileInResource) {
	receiver.newLine();
	receiver.append("{"); //$NON-NLS-1$
	receiver.increaseIndentation().newLine();
	receiver.append(File.class).append(" file = new ").append(File.class); //$NON-NLS-1$
	receiver.append("(\"").append(Strings.convertToJavaString(fileInResource.toString())).append("\");"); //$NON-NLS-1$ //$NON-NLS-2$
	receiver.newLine();
	receiver.append("if (file.exists()) {"); //$NON-NLS-1$
	receiver.increaseIndentation().newLine();
	receiver.append("return;"); //$NON-NLS-1$
	receiver.decreaseIndentation().newLine();
	receiver.append("}"); //$NON-NLS-1$
	receiver.decreaseIndentation().newLine();
	receiver.append("}"); //$NON-NLS-1$
}
 
Example #15
Source Project: bonita-studio   Author: bonitasoft   File: ProcQualifiedNameConverter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Splits the given string into segments and returns them as a {@link QualifiedName}.
 * 
 * @exception IllegalArgumentException
 *                if the input is empty or null.
 */
public QualifiedName toQualifiedName(String qualifiedNameAsString) {
	if (qualifiedNameAsString == null)
		throw new IllegalArgumentException("Qualified name cannot be null");
	if (qualifiedNameAsString.equals(""))
		throw new IllegalArgumentException("Qualified name cannot be empty");
	if (Strings.isEmpty(getDelimiter()))
		return QualifiedName.create(qualifiedNameAsString);
	List<String> segs = getDelimiter().length() == 1 ? Strings.split(qualifiedNameAsString, getDelimiter()
			.charAt(0)) : Strings.split(qualifiedNameAsString, getDelimiter());
	return QualifiedName.create(segs);
}
 
Example #16
Source Project: xtext-extras   Author: eclipse   File: FormatterFragment.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String[] getExportedPackagesRt(Grammar grammar) {
	if(isGenerateStub())
		return new String[] { Strings.skipLastToken(getFormatterName(grammar, getNaming()), ".") };
	else
		return null;
}
 
Example #17
Source Project: sarl   Author: sarl   File: BindingFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static String formatFunctionName(String name) {
	String formattedName = name;
	if (formattedName.startsWith(CONFIGURE_PREFIX)) {
		formattedName = formattedName.substring(CONFIGURE_PREFIX.length());
	} else if (formattedName.startsWith(BIND_PREFIX)) {
		formattedName = formattedName.substring(BIND_PREFIX.length());
	}
	return Strings.toFirstUpper(formattedName);
}
 
Example #18
Source Project: dsl-devkit   Author: dsldevkit   File: CheckProposalProvider.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the name assigned feature in an Assignment rule call.
 *
 * @param call
 *          a rule call
 * @return the assigned feature
 */
private String getAssignedFeature(final RuleCall call) {
  Assignment ass = GrammarUtil.containingAssignment(call);
  if (ass != null) {
    String result = ass.getFeature();
    if (result.equals(result.toLowerCase())) { // NOPMD
      result = Strings.toFirstUpper(result);
    }
    return result;
  }
  return null;
}
 
Example #19
Source Project: sarl   Author: sarl   File: SarlSkillImplCustom.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isStrictFloatingPoint() {
	for (final String modifier : getModifiers()) {
		if (Strings.equal(modifier, "strictfp")) {  //$NON-NLS-1$
			return true;
		}
	}
	return false;
}
 
Example #20
Source Project: xtext-extras   Author: eclipse   File: TypeReferenceFormatterTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void assertFormattedTypeRef(Consumer<? super FormatterTestRequest> test) {
	tester.assertFormatted(it -> {
		test.accept(it);
		// @formatter:off
		String model = 
				"{" + Strings.newLine() +
				"\tvar " + it.getToBeFormatted() + " x" + Strings.newLine() +
				"}";
		// @formatter:on
		it.setToBeFormatted(model);
	});
}
 
Example #21
Source Project: xtext-core   Author: eclipse   File: ElementTypeCalculator.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public EClassifier caseTypeRef(TypeRef object) {
	if (object.getClassifier() == null) {
		if (object.getMetamodel() == null || object.getMetamodel().getEPackage() == null)
			return null;
		String name = GrammarUtil.getTypeRefName(object);
		if (Strings.isEmpty(name))
			return null;
		EClassifierInfo info = classifierInfos.getInfo(object.getMetamodel(), name);
		if (info != null)
			object.setClassifier(info.getEClassifier());
	}
	return object.getClassifier();
}
 
Example #22
Source Project: n4js   Author: eclipse   File: N4JSNameValidator.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private boolean holdsDoesNotStartWithLowerCaseLetter(N4TypeDeclaration declaration) {
	if (Character.isLowerCase(declaration.getName().charAt(0))) {
		final String msg = getMessageForCLF_NAME_DOES_NOT_START_UPPERCASE(keywordProvider.keyword(declaration));
		addIssue(
				Strings.toFirstUpper(msg),
				declaration,
				N4_TYPE_DECLARATION__NAME,
				CLF_NAME_DOES_NOT_START_UPPERCASE);
		return false;
	}
	return true;
}
 
Example #23
@Override
public void completeAssignment(Assignment assignment, ContentAssistContext contentAssistContext,
		ICompletionProposalAcceptor acceptor) {
	ParserRule parserRule = GrammarUtil.containingParserRule(assignment);
	String methodName = "complete" + Strings.toFirstUpper(parserRule.getName()) + "_"
			+ Strings.toFirstUpper(assignment.getFeature());
	invokeMethod(methodName, acceptor, contentAssistContext.getCurrentModel(), assignment, contentAssistContext);
}
 
Example #24
Source Project: dsl-devkit   Author: dsldevkit   File: BuiltInTypeModelAccess.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Load the concrete meta model instance from modelLocation.
 */
private synchronized void load() {
  if (model == null) {
    URI modelURI = getBuiltInElementsResourceURI();
    try {
      ResourceSet rs = new ResourceSetImpl();
      Resource resource = rs.createResource(modelURI);
      // Stand-alone builder cannot handle platform:/plugin/ URIs...
      final InputStream is = BuiltInTypeModelAccess.class.getClassLoader().getResourceAsStream(MODEL_LOCATION);
      resource.load(is, null);
      EcoreUtil.resolveAll(resource);
      model = (BuiltInTypeModel) resource.getContents().get(0);
      // CHECKSTYLE:CHECK-OFF IllegalCatch
      // We *do* want to catch any exception here because we are in construction and need to initialize with something
    } catch (Exception ex) {
      // CHECKSTYLE:CHECK-ON IllegalCatch
      LOGGER.error("Error loading metamodel from " + modelURI, ex); //$NON-NLS-1$
      // Create an empty model...
      model = BuiltInTypeModelPackage.eINSTANCE.getBuiltInTypeModelFactory().createBuiltInTypeModel();
    }
  }
  GlobalResources.INSTANCE.addResource(model.eResource());
  for (InternalType type : model.getInternalTypes()) {
    String typeName = type.getName();
    if (!Strings.isEmpty(typeName)) {
      internalTypesByName.put(typeName, type);
    } else {
      LOGGER.error("incomplete internal type in " + MODEL_LOCATION); //$NON-NLS-1$
    }
  }
}
 
Example #25
Source Project: xtext-core   Author: eclipse   File: Xtext2EcoreTransformer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void checkParameterLists(ParserRule rule, ParserRule overridden) throws TransformationException {
	int inherited = overridden.getParameters().size();
	if (inherited == rule.getParameters().size()) {
		boolean ok = true;
		for(int i = 0; ok && i < inherited; i++) {
			if (!Strings.equal(rule.getParameters().get(i).getName(), overridden.getParameters().get(i).getName())) {
				ok = false;
			}
		}
		if (ok) {
			return;
		}
	}
	if (inherited == 0) {
		throw new TransformationException(TransformationErrorCode.InvalidRuleOverride,
				"Overridden rule " + rule.getName() + " does not declare any parameters", rule);
	}
	StringBuilder message = new StringBuilder("Parameter list is incompatible with inherited ");
	message.append(rule.getName()).append("<");
	for(int i = 0; i < overridden.getParameters().size(); i++) {
		if (i != 0) {
			message.append(", ");
		}
		message.append(overridden.getParameters().get(i).getName());
	}
	message.append(">");
	throw new TransformationException(TransformationErrorCode.InvalidRuleOverride,
			message.toString(), rule);
}
 
Example #26
Source Project: xtext-eclipse   Author: eclipse   File: XtextProposalProvider.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void createAliasProposal(ContentAssistContext context, ICompletionProposalAcceptor acceptor,
		EPackage ePackage, String proposal) {
	if (!Strings.isEmpty(proposal)) {
		ConfigurableCompletionProposal completionProposal = (ConfigurableCompletionProposal) createCompletionProposal(
				proposal, proposal + " - alias", ePackage != null ? getImage(ePackage) : null, context);
		if (completionProposal != null) {
			completionProposal.setPriority(completionProposal.getPriority() * 2);
			acceptor.accept(completionProposal);
		}
	}
}
 
Example #27
Source Project: sarl   Author: sarl   File: AbstractExternalHighlightingFragment2.java    License: Apache License 2.0 5 votes vote down vote up
/** Change the basename of the file to generate.
 *
 * @param basename the basename.
 */
@Pure
public void setBasename(String basename) {
	if (!Strings.isEmpty(basename)) {
		this.basename = basename;
	}
}
 
Example #28
Source Project: n4js   Author: eclipse   File: CompositeSyntaxErrorMessages.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static void encode(SyntaxErrorMessage message, List<String> result) {
	result.add(message.getMessage());
	result.add(message.getIssueCode());
	String[] issueData = message.getIssueData();
	if (issueData != null && issueData.length > 0) {
		result.add(Strings.pack(issueData));
	} else {
		result.add("");
	}
}
 
Example #29
Source Project: xtext-core   Author: eclipse   File: LazyURIEncoder.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.4
 */
public INode getNode(EObject object, String fragment) {
	if (isUseIndexFragment(object.eResource())) {
		return decode(object.eResource(), fragment).getThird();
	}
	INode compositeNode = NodeModelUtils.getNode(object);
	if (compositeNode == null)
		throw new IllegalStateException("Couldn't resolve lazy link, because no node model is attached.");
	List<String> split = Strings.split(fragment, LazyURIEncoder.SEP);
	INode node = getNode(compositeNode, split.get(3));
	return node;
}
 
Example #30
Source Project: sarl   Author: sarl   File: SarlBatchCompiler.java    License: Apache License 2.0 5 votes vote down vote up
/** Change the classpath.
 *
 * <p>The classpath is a list the names of folders or jar files that are separated by {@link File#pathSeparator}.
 *
 * @param classpath the new classpath.
 */
public void setClassPath(String classpath) {
	this.classpath = new ArrayList<>();
	for (final String path : Strings.split(classpath, File.pathSeparator)) {
		this.classpath.add(normalizeFile(path));
	}
}