Search in sources :

Example 11 with JSONValue

use of org.eclipse.n4js.json.JSON.JSONValue in project n4js by eclipse.

the class AbstractPackageJSONValidatorExtension method checkUsingCheckPropertyMethods.

/**
 * Collects all {@link CheckProperty} methods of this class and invokes them on the corresponding properties in the
 * given JSON document
 */
@Check
public void checkUsingCheckPropertyMethods(JSONDocument document) {
    final List<Method> allMethods = Arrays.asList(this.getClass().getDeclaredMethods());
    final List<Pair<CheckProperty, Method>> checkKeyMethods = allMethods.stream().filter(m -> m.getAnnotationsByType(CheckProperty.class).length != 0).filter(m -> isValidCheckKeyMethod(m)).map(m -> Pair.of(m.getAnnotationsByType(CheckProperty.class)[0], m)).collect(Collectors.toList());
    final Multimap<String, JSONValue> documentValues = collectDocumentValues(document);
    for (Pair<CheckProperty, Method> methodPair : checkKeyMethods) {
        final CheckProperty annotation = methodPair.getKey();
        final Method method = methodPair.getValue();
        final PackageJsonProperties property = annotation.property();
        final Collection<JSONValue> values = documentValues.get(property.getPath());
        final DataCollector dcCheckMethod = N4JSDataCollectors.createDataCollectorForCheckMethod(method.getName());
        // check each value that has been specified for keyPath
        for (JSONValue value : values) {
            if (value != null) {
                try (Measurement m = dcCheckMethod.getMeasurement()) {
                    // invoke method without any or with value as single argument
                    if (method.getParameterTypes().length == 0) {
                        method.invoke(this);
                    } else {
                        method.invoke(this, value);
                    }
                } catch (IllegalAccessException | IllegalArgumentException e) {
                    throw new IllegalStateException("Failed to invoke @CheckProperty method " + method + ": " + e);
                } catch (InvocationTargetException e) {
                    // GH-2002: TEMPORARY DEBUG LOGGING
                    // Only passing the exception to Logger#error(String,Throwable) does not emit the stack trace of
                    // the caught exception in all logger configurations; we therefore include the stack trace in
                    // the main message:
                    LOGGER.error("Failed to invoke @CheckProperty method " + method + ": " + e.getTargetException().getMessage() + "\n" + Throwables.getStackTraceAsString(e.getTargetException()));
                    e.getTargetException().printStackTrace();
                }
            }
        }
    }
}
Also used : Arrays(java.util.Arrays) IJSONValidatorExtension(org.eclipse.n4js.json.validation.extension.IJSONValidatorExtension) JSONStringLiteral(org.eclipse.n4js.json.JSON.JSONStringLiteral) Inject(com.google.inject.Inject) EStructuralFeature(org.eclipse.emf.ecore.EStructuralFeature) DiagnosticChain(org.eclipse.emf.common.util.DiagnosticChain) Logger(org.apache.log4j.Logger) Map(java.util.Map) ProjectDescriptionBuilder(org.eclipse.n4js.packagejson.projectDescription.ProjectDescriptionBuilder) Check(org.eclipse.xtext.validation.Check) Method(java.lang.reflect.Method) PackageJsonProperties(org.eclipse.n4js.packagejson.PackageJsonProperties) LinkedHashMultimap(com.google.common.collect.LinkedHashMultimap) JSONPackage(org.eclipse.n4js.json.JSON.JSONPackage) ProjectType(org.eclipse.n4js.packagejson.projectDescription.ProjectType) DataCollector(org.eclipse.n4js.smith.DataCollector) Collection(java.util.Collection) OperationCanceledManager(org.eclipse.xtext.service.OperationCanceledManager) N4JSDataCollectors(org.eclipse.n4js.smith.N4JSDataCollectors) EObject(org.eclipse.emf.ecore.EObject) Collectors(java.util.stream.Collectors) Measurement(org.eclipse.n4js.smith.Measurement) InvocationTargetException(java.lang.reflect.InvocationTargetException) EPackage(org.eclipse.emf.ecore.EPackage) List(java.util.List) Resource(org.eclipse.emf.ecore.resource.Resource) PackageJsonHelper(org.eclipse.n4js.packagejson.PackageJsonHelper) Pair(org.eclipse.xtext.xbase.lib.Pair) XpectAwareFileExtensionCalculator(org.eclipse.n4js.resource.XpectAwareFileExtensionCalculator) AbstractDeclarativeValidator(org.eclipse.xtext.validation.AbstractDeclarativeValidator) N4JSMethodWrapperCancelable(org.eclipse.n4js.validation.N4JSValidator.N4JSMethodWrapperCancelable) URI(org.eclipse.emf.common.util.URI) Supplier(com.google.common.base.Supplier) JSONValue(org.eclipse.n4js.json.JSON.JSONValue) JSONIssueCodes(org.eclipse.n4js.json.validation.JSONIssueCodes) N4JSProjectConfigSnapshot(org.eclipse.n4js.workspace.N4JSProjectConfigSnapshot) HashMap(java.util.HashMap) Multimap(com.google.common.collect.Multimap) EClass(org.eclipse.emf.ecore.EClass) N4JSGlobals(org.eclipse.n4js.N4JSGlobals) WorkspaceAccess(org.eclipse.n4js.workspace.WorkspaceAccess) JSONDocument(org.eclipse.n4js.json.JSON.JSONDocument) EcoreUtil2(org.eclipse.xtext.EcoreUtil2) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) Severity(org.eclipse.xtext.diagnostics.Severity) Throwables(com.google.common.base.Throwables) IssueSeverities(org.eclipse.xtext.validation.IssueSeverities) JSONObject(org.eclipse.n4js.json.JSON.JSONObject) NameValuePair(org.eclipse.n4js.json.JSON.NameValuePair) EValidatorRegistrar(org.eclipse.xtext.validation.EValidatorRegistrar) Measurement(org.eclipse.n4js.smith.Measurement) Method(java.lang.reflect.Method) DataCollector(org.eclipse.n4js.smith.DataCollector) InvocationTargetException(java.lang.reflect.InvocationTargetException) JSONValue(org.eclipse.n4js.json.JSON.JSONValue) PackageJsonProperties(org.eclipse.n4js.packagejson.PackageJsonProperties) Pair(org.eclipse.xtext.xbase.lib.Pair) NameValuePair(org.eclipse.n4js.json.JSON.NameValuePair) Check(org.eclipse.xtext.validation.Check)

Example 12 with JSONValue

use of org.eclipse.n4js.json.JSON.JSONValue in project n4js by eclipse.

the class AbstractPackageJSONValidatorExtension method getSingleDocumentValue.

/**
 * Returns one of the {@link JSONValue}s that have been associated with the given key-path (ignores duplicates).
 *
 * The {@link JSONValue} at the given key-path must be of type {@code expectedClass}. If this is not the case, this
 * method returns {@code null}.
 *
 * Returns {@code null} if no value has been associated with the given {@code keyPath}.
 */
protected <T extends JSONValue> T getSingleDocumentValue(PackageJsonProperties property, Class<T> expectedClass) {
    Collection<JSONValue> values = getDocumentValues().get(property.getPath());
    final JSONValue value = !values.isEmpty() ? values.iterator().next() : null;
    if (!expectedClass.isInstance(value)) {
        return null;
    }
    return expectedClass.cast(value);
}
Also used : JSONValue(org.eclipse.n4js.json.JSON.JSONValue)

Example 13 with JSONValue

use of org.eclipse.n4js.json.JSON.JSONValue in project n4js by eclipse.

the class PackageJsonValidatorExtension method checkN4JSSection.

/**
 * Checks basic structural properties of the 'n4js' section (e.g. mandatory properties).
 */
@CheckProperty(property = N4JS)
public void checkN4JSSection(JSONValue n4jsSection) {
    // make sure n4js section is an object
    if (!checkIsType(n4jsSection, JSONPackage.Literals.JSON_OBJECT, "as package.json n4js section.")) {
        return;
    }
    JSONObject n4jsSectionJO = (JSONObject) n4jsSection;
    final Multimap<String, JSONValue> n4jsValues = collectObjectValues(n4jsSectionJO);
    // Check for correct types (null-values (non-existent) will not lead to issues)
    // Properties that are not checked here, have their own check-method which also validates their types.
    checkIsType(n4jsValues.get(VENDOR_ID.name), JSONPackage.Literals.JSON_STRING_LITERAL, "as vendor ID");
    checkIsType(n4jsValues.get(VENDOR_NAME.name), JSONPackage.Literals.JSON_STRING_LITERAL, "as vendor name");
    checkIsType(n4jsValues.get(OUTPUT.name), JSONPackage.Literals.JSON_STRING_LITERAL, "as output folder path");
    checkIsType(n4jsValues.get(EXTENDED_RUNTIME_ENVIRONMENT.name), JSONPackage.Literals.JSON_STRING_LITERAL, "as reference to extended runtime environment");
    checkIsArrayOfType(n4jsValues.get(PROVIDED_RUNTIME_LIBRARIES.name), JSONPackage.Literals.JSON_STRING_LITERAL, "as provided runtime libraries", "as library reference");
    checkIsArrayOfType(n4jsValues.get(REQUIRED_RUNTIME_LIBRARIES.name), JSONPackage.Literals.JSON_STRING_LITERAL, "as required runtime libraries", "as library reference");
    // Check for empty strings
    checkIsNonEmptyString(n4jsValues.get(VENDOR_ID.name), VENDOR_ID);
    checkIsNonEmptyString(n4jsValues.get(VENDOR_NAME.name), VENDOR_NAME);
    Set<String> allN4JSPropertyNames = PackageJsonProperties.getAllN4JSPropertyNames();
    for (NameValuePair nameValuePair : n4jsSectionJO.getNameValuePairs()) {
        String nvpName = nameValuePair.getName();
        if (!allN4JSPropertyNames.contains(nvpName)) {
            String msg = IssueCodes.getMessageForPKGJ_PROPERTY_UNKNOWN(nvpName);
            addIssue(msg, nameValuePair, JSONPackage.Literals.NAME_VALUE_PAIR__NAME, IssueCodes.PKGJ_PROPERTY_UNKNOWN);
        }
    }
}
Also used : JSONValue(org.eclipse.n4js.json.JSON.JSONValue) NameValuePair(org.eclipse.n4js.json.JSON.NameValuePair) JSONObject(org.eclipse.n4js.json.JSON.JSONObject)

Example 14 with JSONValue

use of org.eclipse.n4js.json.JSON.JSONValue in project n4js by eclipse.

the class PackageJsonValidatorExtension method checkRewriteModuleSpecifiers.

/**
 * Checks 'rewriteModuleSpecifiers'.
 */
@CheckProperty(property = GENERATOR_REWRITE_MODULE_SPECIFIERS)
public void checkRewriteModuleSpecifiers(JSONValue value) {
    if (!checkIsType(value, JSONPackage.Literals.JSON_OBJECT, "(map from module specifier in N4JS source code to specifier used in output code)")) {
        return;
    }
    for (NameValuePair nvp : ((JSONObject) value).getNameValuePairs()) {
        String n = nvp.getName();
        JSONValue v = nvp.getValue();
        if (n == null || v == null) {
            // syntax error
            continue;
        }
        if (n.isEmpty()) {
            addIssue(IssueCodes.getMessageForPKGJ_REWRITE_MODULE_SPECIFIERS__EMPTY_SPECIFIER("Source"), nvp, JSONPackage.eINSTANCE.getNameValuePair_Name(), IssueCodes.PKGJ_REWRITE_MODULE_SPECIFIERS__EMPTY_SPECIFIER);
        } else if (!(v instanceof JSONStringLiteral)) {
            addIssue(IssueCodes.getMessageForPKGJ_REWRITE_MODULE_SPECIFIERS__INVALID_VALUE(), v, IssueCodes.PKGJ_REWRITE_MODULE_SPECIFIERS__INVALID_VALUE);
        } else if (((JSONStringLiteral) v).getValue().isEmpty()) {
            addIssue(IssueCodes.getMessageForPKGJ_REWRITE_MODULE_SPECIFIERS__EMPTY_SPECIFIER("Output code"), v, IssueCodes.PKGJ_REWRITE_MODULE_SPECIFIERS__EMPTY_SPECIFIER);
        }
    }
}
Also used : JSONValue(org.eclipse.n4js.json.JSON.JSONValue) NameValuePair(org.eclipse.n4js.json.JSON.NameValuePair) JSONObject(org.eclipse.n4js.json.JSON.JSONObject) JSONStringLiteral(org.eclipse.n4js.json.JSON.JSONStringLiteral)

Example 15 with JSONValue

use of org.eclipse.n4js.json.JSON.JSONValue in project n4js by eclipse.

the class PackageJsonValidatorExtension method checkIsDependenciesSection.

/**
 * Checks whether the given {@code sectionValue} is a structurally valid package.json dependency section (including
 * the version constraints).
 */
private void checkIsDependenciesSection(JSONValue sectionValue) {
    if (!checkIsType(sectionValue, JSONPackage.Literals.JSON_OBJECT, "as list of dependencies")) {
        return;
    }
    final JSONObject dependenciesObject = (JSONObject) sectionValue;
    for (NameValuePair entry : dependenciesObject.getNameValuePairs()) {
        final JSONValue versionRequirement = entry.getValue();
        if (checkIsType(versionRequirement, JSONPackage.Literals.JSON_STRING_LITERAL, "as version specifier")) {
            JSONStringLiteral jsonStringVersionRequirement = (JSONStringLiteral) versionRequirement;
            String constraintValue = jsonStringVersionRequirement.getValue();
            validateSemver(jsonStringVersionRequirement, constraintValue);
        }
    }
}
Also used : JSONValue(org.eclipse.n4js.json.JSON.JSONValue) NameValuePair(org.eclipse.n4js.json.JSON.NameValuePair) JSONObject(org.eclipse.n4js.json.JSON.JSONObject) JSONStringLiteral(org.eclipse.n4js.json.JSON.JSONStringLiteral)

Aggregations

JSONValue (org.eclipse.n4js.json.JSON.JSONValue)27 NameValuePair (org.eclipse.n4js.json.JSON.NameValuePair)19 JSONObject (org.eclipse.n4js.json.JSON.JSONObject)17 EObject (org.eclipse.emf.ecore.EObject)7 JSONStringLiteral (org.eclipse.n4js.json.JSON.JSONStringLiteral)7 JSONDocument (org.eclipse.n4js.json.JSON.JSONDocument)6 ArrayList (java.util.ArrayList)4 List (java.util.List)4 URI (org.eclipse.emf.common.util.URI)4 ImmutableMultimap (com.google.common.collect.ImmutableMultimap)3 Multimap (com.google.common.collect.Multimap)3 Inject (com.google.inject.Inject)3 Collection (java.util.Collection)3 HashSet (java.util.HashSet)3 Map (java.util.Map)3 Collectors (java.util.stream.Collectors)3 EClass (org.eclipse.emf.ecore.EClass)3 Resource (org.eclipse.emf.ecore.resource.Resource)3 N4JSGlobals (org.eclipse.n4js.N4JSGlobals)3 JSONArray (org.eclipse.n4js.json.JSON.JSONArray)3