Search in sources :

Example 71 with CheckForNull

use of javax.annotation.CheckForNull in project sling by apache.

the class ModelAdapterFactory method injectElement.

@CheckForNull
private RuntimeException injectElement(final InjectableElement element, final Object adaptable, @Nonnull final DisposalCallbackRegistry registry, final InjectCallback callback, @Nonnull final Map<ValuePreparer, Object> preparedValues) {
    InjectAnnotationProcessor annotationProcessor = null;
    String source = element.getSource();
    boolean wasInjectionSuccessful = false;
    // find an appropriate annotation processor
    for (InjectAnnotationProcessorFactory2 factory : injectAnnotationProcessorFactories2) {
        annotationProcessor = factory.createAnnotationProcessor(adaptable, element.getAnnotatedElement());
        if (annotationProcessor != null) {
            break;
        }
    }
    if (annotationProcessor == null) {
        for (InjectAnnotationProcessorFactory factory : injectAnnotationProcessorFactories) {
            annotationProcessor = factory.createAnnotationProcessor(adaptable, element.getAnnotatedElement());
            if (annotationProcessor != null) {
                break;
            }
        }
    }
    String name = getName(element, annotationProcessor);
    final Object injectionAdaptable = getAdaptable(adaptable, element, annotationProcessor);
    RuntimeException lastInjectionException = null;
    if (injectionAdaptable != null) {
        // prepare the set of injectors to process. if a source is given only use injectors with this name.
        final RankedServices<Injector> injectorsToProcess;
        if (StringUtils.isEmpty(source)) {
            injectorsToProcess = sortedInjectors;
        } else {
            injectorsToProcess = injectors.get(source);
            if (injectorsToProcess == null) {
                throw new IllegalArgumentException("No Sling Models Injector registered for source '" + source + "'.");
            }
        }
        // find the right injector
        for (Injector injector : injectorsToProcess) {
            if (name != null || injector instanceof AcceptsNullName) {
                Object preparedValue = injectionAdaptable;
                // only do the ValuePreparer optimization for the original adaptable
                if (injector instanceof ValuePreparer && adaptable == injectionAdaptable) {
                    final ValuePreparer preparer = (ValuePreparer) injector;
                    Object fromMap = preparedValues.get(preparer);
                    if (fromMap != null) {
                        preparedValue = fromMap;
                    } else {
                        preparedValue = preparer.prepareValue(injectionAdaptable);
                        preparedValues.put(preparer, preparedValue);
                    }
                }
                Object value = injector.getValue(preparedValue, name, element.getType(), element.getAnnotatedElement(), registry);
                if (value != null) {
                    lastInjectionException = callback.inject(element, value);
                    if (lastInjectionException == null) {
                        wasInjectionSuccessful = true;
                        break;
                    }
                }
            }
        }
    }
    // if injection failed, use default
    if (!wasInjectionSuccessful) {
        Result<Boolean> defaultInjectionResult = injectDefaultValue(element, annotationProcessor, callback);
        if (defaultInjectionResult.wasSuccessful()) {
            wasInjectionSuccessful = defaultInjectionResult.getValue();
            // log previous injection error, if there was any
            if (lastInjectionException != null && wasInjectionSuccessful) {
                log.debug("Although falling back to default value worked, injection into {} failed because of: " + lastInjectionException.getMessage(), element.getAnnotatedElement(), lastInjectionException);
            }
        } else {
            return defaultInjectionResult.getThrowable();
        }
    }
    // if default is not set, check if mandatory
    if (!wasInjectionSuccessful) {
        if (element.isOptional(annotationProcessor)) {
            // log previous injection error, if there was any
            if (lastInjectionException != null) {
                log.debug("Injection into optional element {} failed because of: " + lastInjectionException.getMessage(), element.getAnnotatedElement(), lastInjectionException);
            }
            if (element.isPrimitive()) {
                RuntimeException throwable = injectPrimitiveInitialValue(element, callback);
                if (throwable != null) {
                    return throwable;
                }
            }
        } else {
            if (lastInjectionException != null) {
                return lastInjectionException;
            } else {
                return new ModelClassException("No injector returned a non-null value!");
            }
        }
    }
    return null;
}
Also used : InjectAnnotationProcessorFactory2(org.apache.sling.models.spi.injectorspecific.InjectAnnotationProcessorFactory2) ValuePreparer(org.apache.sling.models.spi.ValuePreparer) InjectAnnotationProcessor(org.apache.sling.models.spi.injectorspecific.InjectAnnotationProcessor) Injector(org.apache.sling.models.spi.Injector) ModelClassException(org.apache.sling.models.factory.ModelClassException) AcceptsNullName(org.apache.sling.models.spi.AcceptsNullName) InjectAnnotationProcessorFactory(org.apache.sling.models.spi.injectorspecific.InjectAnnotationProcessorFactory) StaticInjectAnnotationProcessorFactory(org.apache.sling.models.spi.injectorspecific.StaticInjectAnnotationProcessorFactory) CheckForNull(javax.annotation.CheckForNull)

Example 72 with CheckForNull

use of javax.annotation.CheckForNull in project sling by apache.

the class ModelAdapterFactory method adapt.

/**
     * Preferably adapt via the {@link ModelFactory} in case the target type is a Sling Model itself, otherwise use regular {@link Adaptable#adaptTo(Class)}.
     * @param value the object from which to adapt
     * @param type the target type
     * @param isWithinCollection
     * @return a Result either encapsulating an exception or the adapted value
     */
@CheckForNull
private Result<Object> adapt(final Object value, final Class<?> type, boolean isWithinCollection) {
    Object adaptedValue = null;
    final String messageSuffix = isWithinCollection ? " in collection" : "";
    if (isModelClass(type) && canCreateFromAdaptable(value, type)) {
        Result<?> result = internalCreateModel(value, type);
        if (result.wasSuccessful()) {
            adaptedValue = result.getValue();
        } else {
            return new Result<Object>(new ModelClassException(String.format("Could not create model from %s: %s%s", value.getClass(), result.getThrowable().getMessage(), messageSuffix), result.getThrowable()));
        }
    } else if (value instanceof Adaptable) {
        adaptedValue = ((Adaptable) value).adaptTo(type);
        if (adaptedValue == null) {
            return new Result<Object>(new ModelClassException(String.format("Could not adapt from %s to %s%s", value.getClass(), type, messageSuffix)));
        }
    }
    if (adaptedValue != null) {
        return new Result<Object>(adaptedValue);
    } else {
        return new Result<Object>(new ModelClassException(String.format("Could not adapt from %s to %s%s, because this class is not adaptable!", value.getClass(), type, messageSuffix)));
    }
}
Also used : ModelClassException(org.apache.sling.models.factory.ModelClassException) Adaptable(org.apache.sling.api.adapter.Adaptable) CheckForNull(javax.annotation.CheckForNull)

Example 73 with CheckForNull

use of javax.annotation.CheckForNull in project sling by apache.

the class ValidationModelRetrieverImpl method getValidationModel.

/*
     * (non-Javadoc)
     * 
     * @see org.apache.sling.validation.impl.ValidationModelRetriever#getModels(java.lang.String, java.lang.String)
     */
@CheckForNull
public ValidationModel getValidationModel(@Nonnull String resourceType, String resourcePath, boolean considerResourceSuperTypeModels) {
    // first get model for exactly the requested resource type
    ValidationModel baseModel = getModel(resourceType, resourcePath);
    String currentResourceType = resourceType;
    if (considerResourceSuperTypeModels) {
        Collection<ValidationModel> modelsToMerge = new ArrayList<ValidationModel>();
        ResourceResolver resourceResolver = null;
        try {
            resourceResolver = resourceResolverFactory.getServiceResourceResolver(null);
            while ((currentResourceType = resourceResolver.getParentResourceType(currentResourceType)) != null) {
                LOG.debug("Retrieving validation models for resource super type {}...", currentResourceType);
                ValidationModel modelToMerge = getModel(currentResourceType, resourcePath);
                if (modelToMerge != null) {
                    if (baseModel == null) {
                        baseModel = modelToMerge;
                    } else {
                        modelsToMerge.add(modelToMerge);
                    }
                }
            }
            if (!modelsToMerge.isEmpty()) {
                return new MergedValidationModel(baseModel, modelsToMerge.toArray(new ValidationModel[modelsToMerge.size()]));
            }
        } catch (LoginException e) {
            throw new IllegalStateException("Could not get service resource resolver", e);
        } finally {
            if (resourceResolver != null) {
                resourceResolver.close();
            }
        }
    }
    return baseModel;
}
Also used : MergedValidationModel(org.apache.sling.validation.impl.model.MergedValidationModel) ValidationModel(org.apache.sling.validation.model.ValidationModel) MergedValidationModel(org.apache.sling.validation.impl.model.MergedValidationModel) ArrayList(java.util.ArrayList) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) LoginException(org.apache.sling.api.resource.LoginException) CheckForNull(javax.annotation.CheckForNull)

Example 74 with CheckForNull

use of javax.annotation.CheckForNull in project sling by apache.

the class ValidationModelRetrieverImpl method getModel.

@CheckForNull
private ValidationModel getModel(@Nonnull String resourceType, String resourcePath) {
    PatriciaTrie<ValidationModel> modelsForResourceType = fillTrieForResourceType(resourceType);
    ValidationModel model = null;
    // for empty/null resource paths, always return the entry stored for ""
    if (StringUtils.isEmpty(resourcePath)) {
        model = modelsForResourceType.get("");
    } else {
        // get longest prefix entry, which still matches
        SortedMap<String, ValidationModel> modelMap = modelsForResourceType.subMap("", resourcePath + "/");
        if (!modelMap.isEmpty()) {
            model = modelMap.get(modelMap.lastKey());
        }
    }
    if (model == null && !modelsForResourceType.isEmpty()) {
        LOG.warn("Although at least one model for resource type '{}' is available, none of them are allowed to be applied to path {}", resourceType, resourcePath);
    }
    return model;
}
Also used : MergedValidationModel(org.apache.sling.validation.impl.model.MergedValidationModel) ValidationModel(org.apache.sling.validation.model.ValidationModel) CheckForNull(javax.annotation.CheckForNull)

Example 75 with CheckForNull

use of javax.annotation.CheckForNull in project sling by apache.

the class ValidationServiceImplTest method testValidateResourceRecursively.

@Test()
public void testValidateResourceRecursively() throws Exception {
    modelBuilder.resourceProperty(propertyBuilder.build("field1"));
    final ValidationModel vm1 = modelBuilder.build("resourcetype1", "some source");
    modelBuilder = new ValidationModelBuilder();
    modelBuilder.resourceProperty(propertyBuilder.build("field2"));
    final ValidationModel vm2 = modelBuilder.build("resourcetype2", "some source");
    // set model retriever
    validationService.modelRetriever = new ValidationModelRetriever() {

        @Override
        @CheckForNull
        public ValidationModel getValidationModel(@Nonnull String resourceType, String resourcePath, boolean considerResourceSuperTypeModels) {
            if (resourceType.equals("resourcetype1")) {
                return vm1;
            } else if (resourceType.equals("resourcetype2")) {
                return vm2;
            } else {
                return null;
            }
        }
    };
    ResourceResolver rr = context.resourceResolver();
    // resource is lacking the required field (is invalid)
    Resource testResource = ResourceUtil.getOrCreateResource(rr, "/content/validation/1/resource", "resourcetype1", JcrConstants.NT_UNSTRUCTURED, true);
    // child1 is valid
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "resourcetype2");
    properties.put("field2", "test");
    rr.create(testResource, "child1", properties);
    // child2 is invalid
    properties.clear();
    properties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "resourcetype2");
    rr.create(testResource, "child2", properties);
    // child3 has no model (but its resource type is ignored)
    properties.clear();
    properties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "resourcetype3");
    rr.create(testResource, "child3", properties);
    final Predicate<Resource> ignoreResourceType3Filter = new Predicate<Resource>() {

        @Override
        public boolean test(final Resource resource) {
            return !"resourcetype3".equals(resource.getResourceType());
        }
    };
    ValidationResult vr = validationService.validateResourceRecursively(testResource, true, ignoreResourceType3Filter, false);
    Assert.assertFalse("resource should have been considered invalid", vr.isValid());
    Assert.assertThat(vr.getFailures(), Matchers.<ValidationFailure>contains(new DefaultValidationFailure("", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, "field1"), new DefaultValidationFailure("child2", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, "field2")));
}
Also used : HashMap(java.util.HashMap) ValidationModelRetriever(org.apache.sling.validation.model.spi.ValidationModelRetriever) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) Resource(org.apache.sling.api.resource.Resource) ChildResource(org.apache.sling.validation.model.ChildResource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) Predicate(java.util.function.Predicate) ValidationModel(org.apache.sling.validation.model.ValidationModel) CheckForNull(javax.annotation.CheckForNull) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) DefaultValidationFailure(org.apache.sling.validation.spi.support.DefaultValidationFailure) ValidationModelBuilder(org.apache.sling.validation.impl.model.ValidationModelBuilder) Test(org.junit.Test)

Aggregations

CheckForNull (javax.annotation.CheckForNull)158 IOException (java.io.IOException)21 Tree (org.apache.jackrabbit.oak.api.Tree)16 PropertyState (org.apache.jackrabbit.oak.api.PropertyState)12 ArrayList (java.util.ArrayList)9 NodeState (org.apache.jackrabbit.oak.spi.state.NodeState)9 Stopwatch (com.google.common.base.Stopwatch)8 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)8 Date (java.util.Date)7 SnapshotDto (org.sonar.db.component.SnapshotDto)7 Period (org.sonar.server.computation.task.projectanalysis.period.Period)7 File (java.io.File)6 SQLException (java.sql.SQLException)6 DocumentStoreException (org.apache.jackrabbit.oak.plugins.document.DocumentStoreException)6 ExecutionException (java.util.concurrent.ExecutionException)5 ValidationModel (org.apache.sling.validation.model.ValidationModel)5 InputStream (java.io.InputStream)4 CommitFailedException (org.apache.jackrabbit.oak.api.CommitFailedException)4 Root (org.apache.jackrabbit.oak.api.Root)4 Utils.resolveCommitRevision (org.apache.jackrabbit.oak.plugins.document.util.Utils.resolveCommitRevision)4