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;
}
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)));
}
}
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;
}
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;
}
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")));
}
Aggregations