org.eclipse.xtext.conversion.ValueConverterException Java Examples

The following examples show how to use org.eclipse.xtext.conversion.ValueConverterException. 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: NewFeatureNameUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public void checkNewFeatureName(String newFeatureName, boolean isLookupInScope, RefactoringStatus status) {
	if (isEmpty(newFeatureName)) { 
		status.addFatalError("Choose a name");
		return;
	}
	try {
		Object value = valueConverterService.toValue(newFeatureName, "ValidID", null);
		valueConverterService.toString(value, "ValidID");
	} catch(ValueConverterException exc) {
		status.addFatalError(exc.getMessage());
	}
	if (Character.isUpperCase(newFeatureName.charAt(0))) 
		status.addError("Discouraged name '" + newFeatureName + "'. Name should start with a lowercase letter. ");
	if (isKeyword(newFeatureName)) 
		status.addFatalError("'" + newFeatureName + "' is keyword.");
	@SuppressWarnings("restriction")
	Class<?> asPrimitive = org.eclipse.xtext.common.types.access.impl.Primitives.forName(newFeatureName);
	if(asPrimitive != null) 
		status.addFatalError("'" + newFeatureName + "' is reserved.");
	if (isLookupInScope && featureCallScope != null && isAlreadyDefined(newFeatureName)) 
		status.addError("The name '" + newFeatureName + "' is already defined in this scope.");
}
 
Example #2
Source File: AssignmentFinderTestLanguageRuntimeModule.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@ValueConverter(rule = "DatEnum")
public IValueConverter<TestEnum> DatEnum() {
	return new IValueConverter<TestEnum>() {

		@Override
		public TestEnum toValue(String string, INode node) throws ValueConverterException {
			if ("lit3".equals(string))
				return TestEnum.LIT3;
			else
				throw new ValueConverterException(null, null, null);
		}

		@Override
		public String toString(TestEnum value) throws ValueConverterException {
			if (value == TestEnum.LIT3)
				return TestEnum.LIT3.getName();
			else
				throw new ValueConverterException(null, null, null);
		}
	};
}
 
Example #3
Source File: SitemapConverters.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@ValueConverter(rule = "Icon")
public IValueConverter<String> Icon() {

    return new IValueConverter<String>() {

        @Override
        public String toValue(String string, INode node) throws ValueConverterException {
            if (string != null && string.startsWith("\"")) {
                return string.substring(1, string.length() - 1);
            }
            return string;
        }

        @Override
        public String toString(String value) throws ValueConverterException {
            if (containsWhiteSpace(value)) {
                return "\"" + value + "\"";
            }
            return value;
        }

    };
}
 
Example #4
Source File: DotDoubleOnlyGrammarConverters.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * A value converter for the ID data type rule.
 *
 * @return A {@link DotIDValueConverter}.
 */
@ValueConverter(rule = "DOUBLE")
public IValueConverter<Double> doubleConverter() {
	return new AbstractNullSafeConverter<Double>() {

		@Override
		protected String internalToString(Double value) {
			return value.toString();
		}

		@Override
		protected Double internalToValue(String string, INode node)
				throws ValueConverterException {
			return DotDoubleUtil.parseDotDouble(string);
		}
	};
}
 
Example #5
Source File: SitemapConverters.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@ValueConverter(rule = "Icon")
public IValueConverter<String> Icon() {

    return new IValueConverter<String>() {

        @Override
        public String toValue(String string, INode node) throws ValueConverterException {
            if (string != null && string.startsWith("\"")) {
                return string.substring(1, string.length() - 1);
            }
            return string;
        }

        @Override
        public String toString(String value) throws ValueConverterException {
            if (containsWhiteSpace(value)) {
                return "\"" + value + "\"";
            }
            return value;
        }

    };
}
 
Example #6
Source File: DotFontNameConverters.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
@ValueConverter(rule = "Variant")
public IValueConverter<Variant> variant() {
	return new AbstractNullSafeConverter<Variant>() {

		@Override
		protected String internalToString(Variant value) {
			return value.getLiteral();
		}

		@Override
		protected Variant internalToValue(String string, INode node)
				throws ValueConverterException {
			switch (string.toLowerCase(Locale.ENGLISH)) {
			case "small-caps":
				return Variant.SMALL_CAPS;
			default:
				return Variant.NORMAL;
			}
		}
	};
}
 
Example #7
Source File: DotFontNameConverters.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
@ValueConverter(rule = "Style")
public IValueConverter<Style> style() {
	return new AbstractNullSafeConverter<Style>() {

		@Override
		protected String internalToString(Style value) {
			return value.getLiteral();
		}

		@Override
		protected Style internalToValue(String string, INode node)
				throws ValueConverterException {
			switch (string.toLowerCase(Locale.ENGLISH)) {
			case "oblique":
				return Style.OBLIQUE;
			case "italic":
				return Style.ITALIC;
			case "roman":
			default:
				return Style.NORMAL;
			}
		}
	};
}
 
Example #8
Source File: AbstractRichTextValueConverter.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String toValue(String string, INode node) {
	if (string == null)
		return null;
	try {
		String leadingTerminal = getLeadingTerminal();
		if (string.length() <= leadingTerminal.length()) {
			throw stringLiteralIsNotClosed(node, "");
		}
		String withoutLeadingTerminal = getWithoutLeadingTerminal(string);
		String trailingTerminal = getTrailingTerminal();
		if (withoutLeadingTerminal.endsWith(trailingTerminal)) {
			String result = withoutLeadingTerminal.substring(0, withoutLeadingTerminal.length() - trailingTerminal.length());
			return result;	
		}
		List<String> trailingSubsequences = getTrailingSubsequences();
		for(String subsequence: trailingSubsequences) {
			if (withoutLeadingTerminal.endsWith(subsequence)) {
				throw stringLiteralIsNotClosed(node, withoutLeadingTerminal.substring(0, withoutLeadingTerminal.length() - subsequence.length()));
			}
		}
		throw stringLiteralIsNotClosed(node, withoutLeadingTerminal.substring(0, withoutLeadingTerminal.length()));
	} catch (StringIndexOutOfBoundsException e) {
		throw new ValueConverterException(e.getMessage(), node, e);
	}
}
 
Example #9
Source File: DotFontNameConverters.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * A value converter for the PostScriptAlias datatype rule
 *
 * @return An IValueConverter<PostScriptFontAlias>
 */
@ValueConverter(rule = "PostScriptAlias")
public IValueConverter<PostScriptFontAlias> postScriptFontAlias() {
	return new AbstractNullSafeConverter<PostScriptFontAlias>() {

		@Override
		protected String internalToString(PostScriptFontAlias value) {
			return value.toString();
		}

		@Override
		protected PostScriptFontAlias internalToValue(String string,
				INode node) throws ValueConverterException {
			String postscriptComparator = string.toUpperCase(Locale.ENGLISH)
					.replaceAll("-", "_");
			return PostScriptFontAlias.valueOf(postscriptComparator);
		}
	};
}
 
Example #10
Source File: UIDtoStringConverter.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String toValue(final String string, INode node) throws ValueConverterException {
    if (string == null) {
        return null;
    }
    String[] ids = string.split(SEPERATOR);
    for (int i = 0; i < ids.length; i++) {
        String id = ids[i];
        if (id != null && id.startsWith("\"") && id.endsWith("\"")) {
            try {
                ids[i] = Strings.convertFromJavaString(id.substring(1, id.length() - 1), true);
            } catch (IllegalArgumentException e) {
                throw new ValueConverterException(e.getMessage(), node, e);
            }
        }
    }
    return Arrays.stream(ids).collect(Collectors.joining(SEPERATOR));
}
 
Example #11
Source File: UIDtoStringConverter.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String toString(String value) throws ValueConverterException {
    if (value == null) {
        throw new ValueConverterException("Value may not be null.", null, null);
    }
    String[] ids = value.split(SEPERATOR);
    for (int i = 0; i < ids.length; i++) {
        String id = ids[i];
        if (id != null && !id.matches("[A-Za-z0-9_]*")) {
            // string escapes each segment which doesn't match:
            // terminal ID: '^'?('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*;
            ids[i] = toEscapedString(id);
        }
    }
    return Arrays.stream(ids).collect(Collectors.joining(SEPERATOR));
}
 
Example #12
Source File: Bug362902ValueConverters.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
@ValueConverter(rule = "MyId")
public IValueConverter<String> ID() {
	return new IValueConverter<String>() {

		@Override
		public String toValue(String string, INode node) throws ValueConverterException {
			if (string != null && string.length() > 3) {
				throw new ValueConverterException("ID too long", node, null);
			}
			return string;
		}

		@Override
		public String toString(String value) throws ValueConverterException {
			return value;
		}
	};
}
 
Example #13
Source File: DefaultRenameStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public RefactoringStatus validateNewName(String newName) {
	RefactoringStatus status = super.validateNewName(newName);
	if(nameRuleName != null) {
		try {
			String value = getNameAsValue(newName);
			String text = getNameAsText(value);
			if(!equal(text, newName)) {
				status.addError("Illegal name: '" + newName + "'. Consider using '" + text + "' instead.");
			}
		} catch(ValueConverterException vce) {
			status.addFatalError("Illegal name: " + notNull(vce.getMessage()));
		}
	}
	return status;
}
 
Example #14
Source File: DotIDValueConverter.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ID toValue(String string, INode node)
		throws ValueConverterException {
	if (string == null) {
		return null;
	}
	if (node == null) {
		return ID.fromString(string);
	}

	for (ILeafNode leaf : node.getLeafNodes()) {
		Object grammarElement = leaf.getGrammarElement();
		if (grammarElement instanceof RuleCall) {
			RuleCall lexerRuleCall = (RuleCall) grammarElement;
			AbstractRule nestedLexerRule = lexerRuleCall.getRule();
			String nestedLexerRuleName = nestedLexerRule.getName();
			if ("COMPASS_PT".equals(nestedLexerRuleName)) {
				nestedLexerRuleName = "STRING";
			}
			return ID.fromString(string, Type.valueOf(nestedLexerRuleName));
		}
	}
	throw new IllegalArgumentException("Invalid ID string " + string);
}
 
Example #15
Source File: ValueTypeToStringConverter.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String toString(Object value) throws ValueConverterException {
    if (value == null) {
        throw new ValueConverterException("Value may not be null.", null, null);
    }
    if (value instanceof String) {
        return toEscapedString((String) value);
    }
    if (value instanceof BigDecimal) {
        BigDecimal decimalValue = (BigDecimal) value;
        return decimalValue.toPlainString();
    }
    if (value instanceof Boolean) {
        return ((Boolean) value).toString();
    }
    throw new ValueConverterException("Unknown value type: " + value.getClass().getSimpleName(), null, null);
}
 
Example #16
Source File: MSESTRINGConverter.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
@ValueConverter(rule = "MSESTRING")
	public IValueConverter<String> MSESTRING() {
		return new IValueConverter<String>() {
			public String toValue(String string, INode node) {
				if (Strings.isEmpty(string))
					throw new ValueConverterException(
							"Couldn't convert empty MSESTRING to String.",
							node, null);
				else {
					//return "\'" + string + "\'";
//					return string.replaceAll("'", "");
					return StringUtils.remove(string, "'");
				}

			}

			public String toString(String value) {
				//return value.replaceAll("'", "");
				return "\'" + value + "\'";
			}

		};

	}
 
Example #17
Source File: XtextValidator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Check
public void checkReferencedMetamodel(ReferencedMetamodel metamodel) throws ValueConverterException {
	if (metamodel.getEPackage() == null)
		return;
	String nsURI = metamodel.getEPackage().getNsURI();
	List<GeneratedMetamodel> allGeneratedMetamodels = getInheritedGeneratedMetamodels(metamodel);
	String text = getUsedUri(metamodel);
	for (GeneratedMetamodel generatedMetamodel : allGeneratedMetamodels) {
		EPackage generatedPackage = generatedMetamodel.getEPackage();
		if (generatedPackage != null && nsURI.equals((generatedPackage.getNsURI()))) {
			if (!text.equals(nsURI)) {
				addIssue("Metamodels that have been generated by a super grammar must be referenced by nsURI: " + nsURI,
						metamodel,
						XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE,
						INVALID_PACKAGE_REFERENCE_INHERITED,
						nsURI);
				return;
			}
			return;
		}
	}
	checkExternalPackage(metamodel, text);
}
 
Example #18
Source File: MSESTRINGConverter.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
@ValueConverter(rule = "MSESTRING")
	public IValueConverter<String> MSESTRING() {
		return new IValueConverter<String>() {
			public String toValue(String string, INode node) {
				if (Strings.isEmpty(string))
					throw new ValueConverterException(
							"Couldn't convert empty MSESTRING to String.",
							node, null);
				else {
					//return "\'" + string + "\'";
//					return string.replaceAll("'", "");
					return StringUtils.remove(string, "'");
				}

			}

			public String toString(String value) {
				//return value.replaceAll("'", "");
				return "\'" + value + "\'";
			}

		};

	}
 
Example #19
Source File: ImportsVariableResolver.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void validateParameters(Variable variable, ValidationMessageAcceptor validationMessageAcceptor) {
	if (variable.getParameters().isEmpty()) {
		validationMessageAcceptor.acceptError(getType() + "-variables have mandatory parameters.", variable,
				TemplatesPackage.Literals.VARIABLE__TYPE, ValidationMessageAcceptor.INSIGNIFICANT_INDEX, null);
	} else {
		EList<String> parameters = variable.getParameters();
		for (int i = 0; i < parameters.size(); i++) {
			String param = parameters.get(i);
			try {
				IValueConverter<String> converter = ((XbaseValueConverterService) valueConverterService)
						.getQualifiedNameWithWildCardValueConverter();
				converter.toString(param);
			} catch (ValueConverterException e) {
				validationMessageAcceptor.acceptError(getType() + " - parameter " + param
						+ " is not a valid qualifier.", variable, TemplatesPackage.Literals.VARIABLE__PARAMETERS,
						i, null);
			}
		}
	}
}
 
Example #20
Source File: GH1462TestLanguageRuntimeModule.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object toValue(String string, String lexerRule, INode node) throws ValueConverterException {
	if (string == null) {
		string = node.getText().trim();
	}
	return super.toValue(string, lexerRule, node);
}
 
Example #21
Source File: CardinalityAwareSyntaxErrorMessageProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public SyntaxErrorMessage getSyntaxErrorMessage(IValueConverterErrorContext context) {
	ValueConverterException cause = context.getValueConverterException();
	if (cause instanceof MoreThanOneCardinalityException) {
		return new SyntaxErrorMessage(context.getDefaultMessage(), CARDINALITY_ISSUE);
	}
	return super.getSyntaxErrorMessage(context);
}
 
Example #22
Source File: AbstractInternalAntlrParser.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void set(EObject _this, String feature, Object value, String lexerRule, INode node) {
	try {
		semanticModelBuilder.set(_this, feature, value, lexerRule, node);
	} catch(ValueConverterException vce) {
		handleValueConverterException(vce);
	}
}
 
Example #23
Source File: XtextLinkingService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private String getMetamodelNsURI(ILeafNode text) {
	try {
		return (String) valueConverterService.toValue(text.getText(), getLinkingHelper().getRuleNameFrom(text
				.getGrammarElement()), text);
	} catch (ValueConverterException e) {
		log.debug("Exception on leaf '" + text.getText() + "'", e);
		return null;
	}
}
 
Example #24
Source File: XtextValueConverters.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@ValueConverter(rule = "LiteralValue")
public IValueConverter<Boolean> LiteralValue() {
	return new AbstractNullSafeConverter<Boolean>() {
		@Override
		protected Boolean internalToValue(String string, INode node) throws ValueConverterException {
			return "+".equals(string);
		}

		@Override
		protected String internalToString(Boolean value) {
			return value.booleanValue() ? "+" : "!";
		}
	};
}
 
Example #25
Source File: JavaIDValueConverter.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void assertValidValue(String value) {
	super.assertValidValue(value);
	if (!isValidIdentifierStart(value.charAt(0))) {
		throw new ValueConverterException(value + " is not a valid identifier.", null, null);
	}
	for(int i = 1, length = value.length(); i < length; i++) {
		if (!isValidIdentifierPart(value.charAt(i))) {
			throw new ValueConverterException(value + " is not a valid identifier.", null, null);
		}
	}
}
 
Example #26
Source File: SyntaxErrorMessageProvider.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public SyntaxErrorMessage getSyntaxErrorMessage(IValueConverterErrorContext context) {
	ValueConverterException cause = context.getValueConverterException();
	if (cause instanceof ValueConverterException) {
		return new SyntaxErrorMessage(cause.getMessage(), SYNTAX_DIAGNOSTIC);
	}
	return super.getSyntaxErrorMessage(context);
}
 
Example #27
Source File: INTValueConverter.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Integer toValue(String string, INode node) {
	if (Strings.isEmpty(string))
		throw new ValueConverterException("Couldn't convert empty string to an int value.", node, null);
	try {
		int intValue = Integer.parseInt(string, 10);
		return Integer.valueOf(intValue);
	} catch (NumberFormatException e) {
		throw new ValueConverterException("Couldn't convert '" + string + "' to an int value.", node, e);
	}
}
 
Example #28
Source File: IDValueConverterTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testInvalidChar2() throws Exception {
		try {
			idConverter.toString("foo%bar[]");
			fail("Empty value not detected.");
		} catch (ValueConverterException e) {
			// normal operation
//			System.out.println(e.getMessage());
		}
	}
 
Example #29
Source File: DotIDValueConverter.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String toString(ID value) throws ValueConverterException {
	if (value == null) {
		return null;
	}
	return value.toString();
}
 
Example #30
Source File: IDValueConverterTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testNull() throws Exception {
		try {
			idConverter.toString(null);
			fail("Null value not detected.");
		} catch (ValueConverterException e) {
			// normal operation
//			System.out.println(e.getMessage());
		}
	}