Search in sources :

Example 1 with PackageJsonProperties

use of org.eclipse.n4js.packagejson.PackageJsonProperties 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 2 with PackageJsonProperties

use of org.eclipse.n4js.packagejson.PackageJsonProperties in project n4js by eclipse.

the class JSONIdeContentProposalProvider method createNameValueProposals.

private void createNameValueProposals(ContentAssistContext context, IIdeContentProposalAcceptor acceptor) {
    EObject model = context.getCurrentModel();
    List<String> namePath = CompletionUtils.getJsonPathNames(model);
    Set<String> alreadyUsedNames = CompletionUtils.getAlreadyUsedNames(model);
    List<PackageJsonProperties> pathProps = PackageJsonProperties.valuesOfPath(namePath);
    for (PackageJsonProperties pathProp : pathProps) {
        String name = pathProp.name;
        String label = name;
        if (!alreadyUsedNames.contains(name) && this.isMatchingPairPrefix(context, name)) {
            if (context.getPrefix().startsWith("\"")) {
                label = '"' + name + '"';
            }
            String proposal = null;
            String kind = null;
            if (pathProp.valueType == JSONStringLiteral.class) {
                proposal = String.format("\"%s\": \"$1\"$0", name);
                kind = ContentAssistEntry.KIND_PROPERTY;
            } else if (pathProp.valueType == JSONArray.class) {
                proposal = String.format("\"%s\": [\n\t$1\n]$0", name);
                kind = ContentAssistEntry.KIND_VALUE;
            } else if (pathProp.valueType == JSONObject.class) {
                proposal = String.format("\"%s\": {\n\t$1\n}$0", name);
                kind = ContentAssistEntry.KIND_CLASS;
            }
            if (proposal != null) {
                addTemplateProposal(proposal, label, pathProp.description, kind, context, acceptor);
            }
        }
    }
    if (pathProps.isEmpty()) {
        addTemplateProposal("\"${1:name}\": \"$2\"$0", "<value>", "Generic name value pair", ContentAssistEntry.KIND_PROPERTY, context, acceptor);
        addTemplateProposal("\"${1:name}\": [\n\t$2\n]$0", "<array>", "Generic name array pair", ContentAssistEntry.KIND_VALUE, context, acceptor);
        addTemplateProposal("\"${1:name}\": {\n\t$2\n}$0", "<object>", "Generic name object pair", ContentAssistEntry.KIND_CLASS, context, acceptor);
    }
}
Also used : EObject(org.eclipse.emf.ecore.EObject) JSONArray(org.eclipse.n4js.json.JSON.JSONArray) PackageJsonProperties(org.eclipse.n4js.packagejson.PackageJsonProperties)

Aggregations

EObject (org.eclipse.emf.ecore.EObject)2 PackageJsonProperties (org.eclipse.n4js.packagejson.PackageJsonProperties)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 Multimap (com.google.common.collect.Multimap)1 Inject (com.google.inject.Inject)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 Collectors (java.util.stream.Collectors)1 Logger (org.apache.log4j.Logger)1 DiagnosticChain (org.eclipse.emf.common.util.DiagnosticChain)1 URI (org.eclipse.emf.common.util.URI)1 EClass (org.eclipse.emf.ecore.EClass)1