Skip to content

Instantly share code, notes, and snippets.

@dherges
Created December 13, 2014 12:39
Show Gist options
  • Save dherges/5d8f3c6b6821759cfa1c to your computer and use it in GitHub Desktop.
Save dherges/5d8f3c6b6821759cfa1c to your computer and use it in GitHub Desktop.
SlingModelEnumValueMapInjector
/*
* Copyright 2014 David Herges <[email protected]>
* Licensed under MIT (http://opensource.org/licenses/MIT)
*/
package org.apache.sling.models.extensions.injector;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.adapter.Adaptable;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.models.spi.DisposalCallbackRegistry;
import org.apache.sling.models.spi.Injector;
import org.osgi.framework.Constants;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Type;
@Component
@Service
@Property(name = Constants.SERVICE_RANKING, intValue = 9999)
public class SlingModelEnumValueMapInjector implements Injector {
@Override
public String getName() {
return "enums";
}
@Override
public Object getValue(Object adaptable, String name, Type declaredType, AnnotatedElement annotatedElement,
DisposalCallbackRegistry disposalCallbackRegistry) {
// sanity check
if (!(declaredType instanceof Class<?>)) {
return null;
}
String value = getValueFor(adaptable, name);
Class<?> cls = (Class<?>) declaredType;
if (cls.isEnum()) {
Enum[] enumConstants = (Enum[]) cls.getEnumConstants();
for (Enum enumConstant : enumConstants) {
if (enumConstant.name().equals(value)) {
return enumConstant;
}
}
}
return null;
}
private String getValueFor(Object adaptable, String name) {
ValueMap map = null;
if (adaptable instanceof ValueMap) {
map = (ValueMap) adaptable;
} else if (adaptable instanceof Adaptable) {
map = ((Adaptable) adaptable).adaptTo(ValueMap.class);
}
return (map != null) ? map.get(name, String.class) : null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment