Search in sources :

Example 1 with JSONDocument

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

the class CompletionUtils method getJsonPathNames.

/**
 * Return the property names on the path towards the current model.
 */
public static List<String> getJsonPathNames(EObject model) {
    List<String> namePath = new LinkedList<>();
    EObject eobj = model;
    while (!(eobj instanceof JSONDocument)) {
        if (eobj instanceof NameValuePair) {
            NameValuePair nvp = (NameValuePair) eobj;
            namePath.add(0, nvp.getName());
        }
        eobj = eobj.eContainer();
    }
    return namePath;
}
Also used : NameValuePair(org.eclipse.n4js.json.JSON.NameValuePair) EObject(org.eclipse.emf.ecore.EObject) JSONDocument(org.eclipse.n4js.json.JSON.JSONDocument) LinkedList(java.util.LinkedList)

Example 2 with JSONDocument

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

the class JSONValidator method checkDocumentForComments.

/**
 * Checks the document for comments (single or multi-line) which are not valid JSON constructs but accepted by our
 * parser.
 */
@Check
public void checkDocumentForComments(JSONDocument document) {
    ICompositeNode documentNode = NodeModelUtils.findActualNodeFor(document);
    ICompositeNode rootNode = documentNode.getRootNode();
    // find hidden leaf nodes that fulfill #isCommentNode criteria and add an issue
    StreamSupport.stream(rootNode.getAsTreeIterable().spliterator(), false).filter(n -> n instanceof HiddenLeafNode).filter(n -> isCommentNode(n)).forEach(n -> {
        addIssue(JSONIssueCodes.getMessageForJSON_COMMENT_UNSUPPORTED(), document, n.getOffset(), n.getLength(), JSONIssueCodes.JSON_COMMENT_UNSUPPORTED);
    });
}
Also used : JSONPackage(org.eclipse.n4js.json.JSON.JSONPackage) HiddenLeafNode(org.eclipse.xtext.nodemodel.impl.HiddenLeafNode) IJSONValidatorExtension(org.eclipse.n4js.json.validation.extension.IJSONValidatorExtension) Inject(com.google.inject.Inject) DiagnosticChain(org.eclipse.emf.common.util.DiagnosticChain) JSONValue(org.eclipse.n4js.json.JSON.JSONValue) JSONExtensionRegistry(org.eclipse.n4js.json.extension.JSONExtensionRegistry) HashMap(java.util.HashMap) EObject(org.eclipse.emf.ecore.EObject) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) NodeModelUtils(org.eclipse.xtext.nodemodel.util.NodeModelUtils) JSONObject(org.eclipse.n4js.json.JSON.JSONObject) TerminalRule(org.eclipse.xtext.TerminalRule) JSONDocument(org.eclipse.n4js.json.JSON.JSONDocument) Map(java.util.Map) NameValuePair(org.eclipse.n4js.json.JSON.NameValuePair) JSONGrammarAccess(org.eclipse.n4js.json.services.JSONGrammarAccess) StreamSupport(java.util.stream.StreamSupport) INode(org.eclipse.xtext.nodemodel.INode) Check(org.eclipse.xtext.validation.Check) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) HiddenLeafNode(org.eclipse.xtext.nodemodel.impl.HiddenLeafNode) Check(org.eclipse.xtext.validation.Check)

Example 3 with JSONDocument

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

the class ProjectDescriptionLoader method loadPackageJSONAtLocation.

private JSONDocument loadPackageJSONAtLocation(SafeURI<?> location) {
    Path path = location.appendSegment(N4JSGlobals.PACKAGE_JSON).toFileSystemPath();
    if (!Files.isReadable(path)) {
        path = location.appendSegment(N4JSGlobals.PACKAGE_JSON + "." + N4JSGlobals.XT_FILE_EXTENSION).toFileSystemPath();
        if (!Files.isReadable(path)) {
            return null;
        }
    }
    try {
        String jsonString = Files.readString(path, StandardCharsets.UTF_8);
        try {
            JSONDocument doc = JSONFactory.eINSTANCE.createJSONDocument();
            JsonElement jsonElement = JsonParser.parseString(jsonString);
            doc.setContent(copy(jsonElement));
            return doc;
        } catch (JsonParseException e) {
            JSONDocument packageJSON = loadXtextFileAtLocation(location, N4JSGlobals.PACKAGE_JSON, jsonString, JSONDocument.class);
            return packageJSON;
        }
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    }
}
Also used : Path(java.nio.file.Path) RuntimeIOException(org.eclipse.xtext.util.RuntimeIOException) JsonElement(com.google.gson.JsonElement) JSONDocument(org.eclipse.n4js.json.JSON.JSONDocument) RuntimeIOException(org.eclipse.xtext.util.RuntimeIOException) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException)

Example 4 with JSONDocument

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

the class ProjectDescriptionLoader method loadVersionAndN4JSNatureFromProjectDescriptionAtLocation.

/**
 * Loads the project description of the N4JS project at the given {@code location} and returns the version string or
 * <code>null</code> if undefined or in case of error.
 */
public Pair<String, Boolean> loadVersionAndN4JSNatureFromProjectDescriptionAtLocation(SafeURI<?> location) {
    JSONDocument packageJSON = loadPackageJSONAtLocation(location);
    JSONValue versionValue = null;
    boolean hasN4JSNature = false;
    if (packageJSON != null) {
        versionValue = JSONModelUtils.getProperty(packageJSON, VERSION.name).orElse(null);
        hasN4JSNature = JSONModelUtils.getProperty(packageJSON, N4JS.name).isPresent();
    }
    Pair<String, Boolean> result = Tuples.create(asNonEmptyStringOrNull(versionValue), hasN4JSNature);
    return result;
}
Also used : JSONValue(org.eclipse.n4js.json.JSON.JSONValue) JSONDocument(org.eclipse.n4js.json.JSON.JSONDocument)

Example 5 with JSONDocument

use of org.eclipse.n4js.json.JSON.JSONDocument 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)

Aggregations

JSONDocument (org.eclipse.n4js.json.JSON.JSONDocument)11 EObject (org.eclipse.emf.ecore.EObject)5 JSONValue (org.eclipse.n4js.json.JSON.JSONValue)5 NameValuePair (org.eclipse.n4js.json.JSON.NameValuePair)5 JSONObject (org.eclipse.n4js.json.JSON.JSONObject)4 Inject (com.google.inject.Inject)2 HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 Map (java.util.Map)2 DiagnosticChain (org.eclipse.emf.common.util.DiagnosticChain)2 URI (org.eclipse.emf.common.util.URI)2 EPackage (org.eclipse.emf.ecore.EPackage)2 JSONPackage (org.eclipse.n4js.json.JSON.JSONPackage)2 JSONStringLiteral (org.eclipse.n4js.json.JSON.JSONStringLiteral)2 IJSONValidatorExtension (org.eclipse.n4js.json.validation.extension.IJSONValidatorExtension)2 Check (org.eclipse.xtext.validation.Check)2 Supplier (com.google.common.base.Supplier)1 Throwables (com.google.common.base.Throwables)1 ImmutableMultimap (com.google.common.collect.ImmutableMultimap)1 LinkedHashMultimap (com.google.common.collect.LinkedHashMultimap)1