下面列出了怎么用org.springframework.beans.PropertyAccessor的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Handle Spring-initialization of resoures produced by the UIMA framework.
*/
public static Resource initResource(Resource aResource, ApplicationContext aApplicationContext) {
AutowireCapableBeanFactory beanFactory = aApplicationContext.getAutowireCapableBeanFactory();
if (aResource instanceof PrimitiveAnalysisEngine_impl) {
PropertyAccessor pa = PropertyAccessorFactory.forDirectFieldAccess(aResource);
// Access the actual AnalysisComponent and initialize it
AnalysisComponent analysisComponent = (AnalysisComponent) pa
.getPropertyValue("mAnalysisComponent");
initializeBean(beanFactory, analysisComponent, aResource.getMetaData().getName());
pa.setPropertyValue("mAnalysisComponent", analysisComponent);
return aResource;
} else {
return (Resource) beanFactory.initializeBean(aResource, aResource.getMetaData().getName());
}
}
public void autobind(Object view) {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(getModel());
PropertyAccessor viewPropertyAccessor = new DirectFieldAccessor(view);
// iterate on model properties
for (PropertyDescriptor pd : bw.getPropertyDescriptors()) {
String propertyName = pd.getName();
if ( !ignoredProperties.contains(propertyName) && viewPropertyAccessor.isReadableProperty(propertyName)) {
Object control = viewPropertyAccessor.getPropertyValue(propertyName);
if (control != null) {
if (log.isDebugEnabled())
log.debug("Found control: " + control.getClass().getSimpleName() +
" for property: " + propertyName);
bind(control, propertyName);
}
}
}
}
/**
* Set the path that this tag should apply.
* <p>E.g. "customer" to allow bind paths like "address.street"
* rather than "customer.address.street".
* @see BindTag#setPath
*/
public void setPath(@Nullable String path) {
if (path == null) {
path = "";
}
if (path.length() > 0 && !path.endsWith(PropertyAccessor.NESTED_PROPERTY_SEPARATOR)) {
path += PropertyAccessor.NESTED_PROPERTY_SEPARATOR;
}
this.path = path;
}
/**
* Get the {@link BindStatus} for this tag.
*/
protected BindStatus getBindStatus() throws JspException {
if (this.bindStatus == null) {
// HTML escaping in tags is performed by the ValueFormatter class.
String nestedPath = getNestedPath();
String pathToUse = (nestedPath != null ? nestedPath + getPath() : getPath());
if (pathToUse.endsWith(PropertyAccessor.NESTED_PROPERTY_SEPARATOR)) {
pathToUse = pathToUse.substring(0, pathToUse.length() - 1);
}
this.bindStatus = new BindStatus(getRequestContext(), pathToUse, false);
}
return this.bindStatus;
}
/**
* Set the path that this tag should apply.
* <p>E.g. "customer" to allow bind paths like "address.street"
* rather than "customer.address.street".
* @see BindTag#setPath
*/
public void setPath(@Nullable String path) {
if (path == null) {
path = "";
}
if (path.length() > 0 && !path.endsWith(PropertyAccessor.NESTED_PROPERTY_SEPARATOR)) {
path += PropertyAccessor.NESTED_PROPERTY_SEPARATOR;
}
this.path = path;
}
/**
* Get the {@link BindStatus} for this tag.
*/
protected BindStatus getBindStatus() throws JspException {
if (this.bindStatus == null) {
// HTML escaping in tags is performed by the ValueFormatter class.
String nestedPath = getNestedPath();
String pathToUse = (nestedPath != null ? nestedPath + getPath() : getPath());
if (pathToUse.endsWith(PropertyAccessor.NESTED_PROPERTY_SEPARATOR)) {
pathToUse = pathToUse.substring(0, pathToUse.length() - 1);
}
this.bindStatus = new BindStatus(getRequestContext(), pathToUse, false);
}
return this.bindStatus;
}
@Override
public boolean isValid(final WithId<?> value, final ConstraintValidatorContext context) {
if (value == null) {
return true;
}
final PropertyAccessor bean = new BeanWrapperImpl(value);
final String propertyValue = String.valueOf(bean.getPropertyValue(property));
@SuppressWarnings({"rawtypes", "unchecked"})
final Class<WithId> modelClass = (Class) value.getKind().modelClass;
@SuppressWarnings("unchecked")
final Set<String> ids = dataManager.fetchIdsByPropertyValue(modelClass, property, propertyValue);
final boolean isUnique = ids.isEmpty() || value.getId().map(id -> ids.contains(id)).orElse(false);
if (!isUnique) {
context.disableDefaultConstraintViolation();
context.unwrap(HibernateConstraintValidatorContext.class).addExpressionVariable("nonUnique", propertyValue)
.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
.addPropertyNode(property).addConstraintViolation();
}
return isUnique;
}
/**
* Set the path that this tag should apply.
* <p>E.g. "customer" to allow bind paths like "address.street"
* rather than "customer.address.street".
* @see BindTag#setPath
*/
public void setPath(String path) {
if (path == null) {
path = "";
}
if (path.length() > 0 && !path.endsWith(PropertyAccessor.NESTED_PROPERTY_SEPARATOR)) {
path += PropertyAccessor.NESTED_PROPERTY_SEPARATOR;
}
this.path = path;
}
/**
* Get the {@link BindStatus} for this tag.
*/
protected BindStatus getBindStatus() throws JspException {
if (this.bindStatus == null) {
// HTML escaping in tags is performed by the ValueFormatter class.
String nestedPath = getNestedPath();
String pathToUse = (nestedPath != null ? nestedPath + getPath() : getPath());
if (pathToUse.endsWith(PropertyAccessor.NESTED_PROPERTY_SEPARATOR)) {
pathToUse = pathToUse.substring(0, pathToUse.length() - 1);
}
this.bindStatus = new BindStatus(getRequestContext(), pathToUse, false);
}
return this.bindStatus;
}
/**
* Set the path that this tag should apply.
* <p>E.g. "customer" to allow bind paths like "address.street"
* rather than "customer.address.street".
* @see BindTag#setPath
*/
public void setPath(String path) {
if (path == null) {
path = "";
}
if (path.length() > 0 && !path.endsWith(PropertyAccessor.NESTED_PROPERTY_SEPARATOR)) {
path += PropertyAccessor.NESTED_PROPERTY_SEPARATOR;
}
this.path = path;
}
/**
* Get the {@link BindStatus} for this tag.
*/
protected BindStatus getBindStatus() throws JspException {
if (this.bindStatus == null) {
// HTML escaping in tags is performed by the ValueFormatter class.
String nestedPath = getNestedPath();
String pathToUse = (nestedPath != null ? nestedPath + getPath() : getPath());
if (pathToUse.endsWith(PropertyAccessor.NESTED_PROPERTY_SEPARATOR)) {
pathToUse = pathToUse.substring(0, pathToUse.length() - 1);
}
this.bindStatus = new BindStatus(getRequestContext(), pathToUse, false);
}
return this.bindStatus;
}
private Directory getDirectoryService() {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jacksonFactory = new JacksonFactory();
GoogleCredential credential = getGoogleCredential();
PropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(credential);
accessor.setPropertyValue("serviceAccountUser", config.getAdminUsername());
accessor.setPropertyValue("serviceAccountScopes", SERVICE_ACCOUNT_SCOPES);
return new Directory.Builder(httpTransport, jacksonFactory, credential)
.setApplicationName("Spinnaker-Fiat")
.build();
}
/**
* Gets index of property name.
*
* <p>
* Returns the index number of the location of the given property name.
* </p>
*
* @param propertyName name of property to find index of.
* @return index number representing location of property name.
*/
private Integer extractIndex(String propertyName) {
int firstIndex = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR);
int lastIndex = propertyName.lastIndexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR);
if (firstIndex != -1 && lastIndex != -1) {
String indexValue = propertyName.substring(firstIndex + 1, lastIndex);
try {
int index = Integer.parseInt(indexValue);
return Integer.valueOf(index);
} catch (NumberFormatException e) {
// if we encounter this then it wasn't really an index, ignore
}
}
return null;
}
/**
* Initialize collection
* @param em
* @param entity
* @param a
* @param i
*/
@SuppressWarnings("rawtypes")
private static void intializeCollection(EntityManager em, Object entity, Object attached,
Attribute a, int depth) {
PropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(attached);
Collection c = (Collection) accessor.getPropertyValue(a.getName());
for (Object o : c)
initialize(em, o, depth -1);
PropertyAccessorFactory.forDirectFieldAccess(entity).setPropertyValue(a.getName(), c);
}
/**
* Test if entity is New
* @param entity
* @return true if entity is new, ie not detached
*/
@SuppressWarnings("unchecked")
protected boolean isNew(T entity) {
SingularAttribute<?, ?> id = getIdAttribute(entity.getClass());
// try field
PropertyAccessor pa = PropertyAccessorFactory.forDirectFieldAccess(entity);
PK key = (PK) pa.getPropertyValue(id.getName());
if (key == null)
key = (PK) PropertyAccessorFactory.forBeanPropertyAccess(entity).getPropertyValue(id.getName());
return key == null || !exists(key, entity.getClass());
}
/**
* Writes the opening part of the block '{@code form}' tag and exposes
* the form object name in the {@link javax.servlet.jsp.PageContext}.
* @param tagWriter the {@link TagWriter} to which the form content is to be written
* @return {@link javax.servlet.jsp.tagext.Tag#EVAL_BODY_INCLUDE}
*/
@Override
protected int writeTagContent(TagWriter tagWriter) throws JspException {
this.tagWriter = tagWriter;
tagWriter.startTag(FORM_TAG);
writeDefaultAttributes(tagWriter);
tagWriter.writeAttribute(ACTION_ATTRIBUTE, resolveAction());
writeOptionalAttribute(tagWriter, METHOD_ATTRIBUTE, getHttpMethod());
writeOptionalAttribute(tagWriter, TARGET_ATTRIBUTE, getTarget());
writeOptionalAttribute(tagWriter, ENCTYPE_ATTRIBUTE, getEnctype());
writeOptionalAttribute(tagWriter, ACCEPT_CHARSET_ATTRIBUTE, getAcceptCharset());
writeOptionalAttribute(tagWriter, ONSUBMIT_ATTRIBUTE, getOnsubmit());
writeOptionalAttribute(tagWriter, ONRESET_ATTRIBUTE, getOnreset());
writeOptionalAttribute(tagWriter, AUTOCOMPLETE_ATTRIBUTE, getAutocomplete());
tagWriter.forceBlock();
if (!isMethodBrowserSupported(getMethod())) {
assertHttpMethod(getMethod());
String inputName = getMethodParam();
String inputType = "hidden";
tagWriter.startTag(INPUT_TAG);
writeOptionalAttribute(tagWriter, TYPE_ATTRIBUTE, inputType);
writeOptionalAttribute(tagWriter, NAME_ATTRIBUTE, inputName);
writeOptionalAttribute(tagWriter, VALUE_ATTRIBUTE, processFieldValue(inputName, getMethod(), inputType));
tagWriter.endTag();
}
// Expose the form object name for nested tags...
String modelAttribute = resolveModelAttribute();
this.pageContext.setAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, modelAttribute, PageContext.REQUEST_SCOPE);
// Save previous nestedPath value, build and expose current nestedPath value.
// Use request scope to expose nestedPath to included pages too.
this.previousNestedPath =
(String) this.pageContext.getAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME,
modelAttribute + PropertyAccessor.NESTED_PROPERTY_SEPARATOR, PageContext.REQUEST_SCOPE);
return EVAL_BODY_INCLUDE;
}
/**
* Register bean definitions contained in a Map.
* Ignore ineligible properties.
* @param map a map of {@code name} to {@code property} (String or Object). Property
* values will be strings if coming from a Properties file etc. Property names
* (keys) <b>must</b> be Strings. Class keys must be Strings.
* @param prefix a filter within the keys in the map: e.g. 'beans.'
* (can be empty or {@code null})
* @param resourceDescription description of the resource that the
* Map came from (for logging purposes)
* @return the number of bean definitions found
* @throws BeansException in case of loading or parsing errors
* @see #registerBeanDefinitions(Map, String)
*/
public int registerBeanDefinitions(Map<?, ?> map, @Nullable String prefix, String resourceDescription)
throws BeansException {
if (prefix == null) {
prefix = "";
}
int beanCount = 0;
for (Object key : map.keySet()) {
if (!(key instanceof String)) {
throw new IllegalArgumentException("Illegal key [" + key + "]: only Strings allowed");
}
String keyString = (String) key;
if (keyString.startsWith(prefix)) {
// Key is of form: prefix<name>.property
String nameAndProperty = keyString.substring(prefix.length());
// Find dot before property name, ignoring dots in property keys.
int sepIdx = -1;
int propKeyIdx = nameAndProperty.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX);
if (propKeyIdx != -1) {
sepIdx = nameAndProperty.lastIndexOf(SEPARATOR, propKeyIdx);
}
else {
sepIdx = nameAndProperty.lastIndexOf(SEPARATOR);
}
if (sepIdx != -1) {
String beanName = nameAndProperty.substring(0, sepIdx);
if (logger.isTraceEnabled()) {
logger.trace("Found bean name '" + beanName + "'");
}
if (!getRegistry().containsBeanDefinition(beanName)) {
// If we haven't already registered it...
registerBeanDefinition(beanName, map, prefix + beanName, resourceDescription);
++beanCount;
}
}
else {
// Ignore it: It wasn't a valid bean name and property,
// although it did start with the required prefix.
if (logger.isDebugEnabled()) {
logger.debug("Invalid bean name and property [" + nameAndProperty + "]");
}
}
}
}
return beanCount;
}
/**
* Writes the opening part of the block '{@code form}' tag and exposes
* the form object name in the {@link javax.servlet.jsp.PageContext}.
* @param tagWriter the {@link TagWriter} to which the form content is to be written
* @return {@link javax.servlet.jsp.tagext.Tag#EVAL_BODY_INCLUDE}
*/
@Override
protected int writeTagContent(TagWriter tagWriter) throws JspException {
this.tagWriter = tagWriter;
tagWriter.startTag(FORM_TAG);
writeDefaultAttributes(tagWriter);
tagWriter.writeAttribute(ACTION_ATTRIBUTE, resolveAction());
writeOptionalAttribute(tagWriter, METHOD_ATTRIBUTE, getHttpMethod());
writeOptionalAttribute(tagWriter, TARGET_ATTRIBUTE, getTarget());
writeOptionalAttribute(tagWriter, ENCTYPE_ATTRIBUTE, getEnctype());
writeOptionalAttribute(tagWriter, ACCEPT_CHARSET_ATTRIBUTE, getAcceptCharset());
writeOptionalAttribute(tagWriter, ONSUBMIT_ATTRIBUTE, getOnsubmit());
writeOptionalAttribute(tagWriter, ONRESET_ATTRIBUTE, getOnreset());
writeOptionalAttribute(tagWriter, AUTOCOMPLETE_ATTRIBUTE, getAutocomplete());
tagWriter.forceBlock();
if (!isMethodBrowserSupported(getMethod())) {
assertHttpMethod(getMethod());
String inputName = getMethodParam();
String inputType = "hidden";
tagWriter.startTag(INPUT_TAG);
writeOptionalAttribute(tagWriter, TYPE_ATTRIBUTE, inputType);
writeOptionalAttribute(tagWriter, NAME_ATTRIBUTE, inputName);
writeOptionalAttribute(tagWriter, VALUE_ATTRIBUTE, processFieldValue(inputName, getMethod(), inputType));
tagWriter.endTag();
}
// Expose the form object name for nested tags...
String modelAttribute = resolveModelAttribute();
this.pageContext.setAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, modelAttribute, PageContext.REQUEST_SCOPE);
// Save previous nestedPath value, build and expose current nestedPath value.
// Use request scope to expose nestedPath to included pages too.
this.previousNestedPath =
(String) this.pageContext.getAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME,
modelAttribute + PropertyAccessor.NESTED_PROPERTY_SEPARATOR, PageContext.REQUEST_SCOPE);
return EVAL_BODY_INCLUDE;
}
/**
* Register bean definitions contained in a Map.
* Ignore ineligible properties.
* @param map a map of {@code name} to {@code property} (String or Object). Property
* values will be strings if coming from a Properties file etc. Property names
* (keys) <b>must</b> be Strings. Class keys must be Strings.
* @param prefix a filter within the keys in the map: e.g. 'beans.'
* (can be empty or {@code null})
* @param resourceDescription description of the resource that the
* Map came from (for logging purposes)
* @return the number of bean definitions found
* @throws BeansException in case of loading or parsing errors
* @see #registerBeanDefinitions(Map, String)
*/
public int registerBeanDefinitions(Map<?, ?> map, @Nullable String prefix, String resourceDescription)
throws BeansException {
if (prefix == null) {
prefix = "";
}
int beanCount = 0;
for (Object key : map.keySet()) {
if (!(key instanceof String)) {
throw new IllegalArgumentException("Illegal key [" + key + "]: only Strings allowed");
}
String keyString = (String) key;
if (keyString.startsWith(prefix)) {
// Key is of form: prefix<name>.property
String nameAndProperty = keyString.substring(prefix.length());
// Find dot before property name, ignoring dots in property keys.
int sepIdx = -1;
int propKeyIdx = nameAndProperty.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX);
if (propKeyIdx != -1) {
sepIdx = nameAndProperty.lastIndexOf(SEPARATOR, propKeyIdx);
}
else {
sepIdx = nameAndProperty.lastIndexOf(SEPARATOR);
}
if (sepIdx != -1) {
String beanName = nameAndProperty.substring(0, sepIdx);
if (logger.isTraceEnabled()) {
logger.trace("Found bean name '" + beanName + "'");
}
if (!getRegistry().containsBeanDefinition(beanName)) {
// If we haven't already registered it...
registerBeanDefinition(beanName, map, prefix + beanName, resourceDescription);
++beanCount;
}
}
else {
// Ignore it: It wasn't a valid bean name and property,
// although it did start with the required prefix.
if (logger.isDebugEnabled()) {
logger.debug("Invalid bean name and property [" + nameAndProperty + "]");
}
}
}
}
return beanCount;
}
/**
* Writes the opening part of the block '{@code form}' tag and exposes
* the form object name in the {@link javax.servlet.jsp.PageContext}.
* @param tagWriter the {@link TagWriter} to which the form content is to be written
* @return {@link javax.servlet.jsp.tagext.Tag#EVAL_BODY_INCLUDE}
*/
@Override
protected int writeTagContent(TagWriter tagWriter) throws JspException {
this.tagWriter = tagWriter;
tagWriter.startTag(FORM_TAG);
writeDefaultAttributes(tagWriter);
tagWriter.writeAttribute(ACTION_ATTRIBUTE, resolveAction());
writeOptionalAttribute(tagWriter, METHOD_ATTRIBUTE, getHttpMethod());
writeOptionalAttribute(tagWriter, TARGET_ATTRIBUTE, getTarget());
writeOptionalAttribute(tagWriter, ENCTYPE_ATTRIBUTE, getEnctype());
writeOptionalAttribute(tagWriter, ACCEPT_CHARSET_ATTRIBUTE, getAcceptCharset());
writeOptionalAttribute(tagWriter, ONSUBMIT_ATTRIBUTE, getOnsubmit());
writeOptionalAttribute(tagWriter, ONRESET_ATTRIBUTE, getOnreset());
writeOptionalAttribute(tagWriter, AUTOCOMPLETE_ATTRIBUTE, getAutocomplete());
tagWriter.forceBlock();
if (!isMethodBrowserSupported(getMethod())) {
assertHttpMethod(getMethod());
String inputName = getMethodParam();
String inputType = "hidden";
tagWriter.startTag(INPUT_TAG);
writeOptionalAttribute(tagWriter, TYPE_ATTRIBUTE, inputType);
writeOptionalAttribute(tagWriter, NAME_ATTRIBUTE, inputName);
writeOptionalAttribute(tagWriter, VALUE_ATTRIBUTE, processFieldValue(inputName, getMethod(), inputType));
tagWriter.endTag();
}
// Expose the form object name for nested tags...
String modelAttribute = resolveModelAttribute();
this.pageContext.setAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, modelAttribute, PageContext.REQUEST_SCOPE);
// Save previous nestedPath value, build and expose current nestedPath value.
// Use request scope to expose nestedPath to included pages too.
this.previousNestedPath =
(String) this.pageContext.getAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME,
modelAttribute + PropertyAccessor.NESTED_PROPERTY_SEPARATOR, PageContext.REQUEST_SCOPE);
return EVAL_BODY_INCLUDE;
}
/**
* Register bean definitions contained in a Map.
* Ignore ineligible properties.
* @param map Map name -> property (String or Object). Property values
* will be strings if coming from a Properties file etc. Property names
* (keys) <b>must</b> be strings. Class keys must be Strings.
* @param prefix a filter within the keys in the map: e.g. 'beans.'
* (can be empty or {@code null})
* @param resourceDescription description of the resource that the
* Map came from (for logging purposes)
* @return the number of bean definitions found
* @throws BeansException in case of loading or parsing errors
* @see #registerBeanDefinitions(Map, String)
*/
public int registerBeanDefinitions(Map<?, ?> map, String prefix, String resourceDescription)
throws BeansException {
if (prefix == null) {
prefix = "";
}
int beanCount = 0;
for (Object key : map.keySet()) {
if (!(key instanceof String)) {
throw new IllegalArgumentException("Illegal key [" + key + "]: only Strings allowed");
}
String keyString = (String) key;
if (keyString.startsWith(prefix)) {
// Key is of form: prefix<name>.property
String nameAndProperty = keyString.substring(prefix.length());
// Find dot before property name, ignoring dots in property keys.
int sepIdx = -1;
int propKeyIdx = nameAndProperty.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX);
if (propKeyIdx != -1) {
sepIdx = nameAndProperty.lastIndexOf(SEPARATOR, propKeyIdx);
}
else {
sepIdx = nameAndProperty.lastIndexOf(SEPARATOR);
}
if (sepIdx != -1) {
String beanName = nameAndProperty.substring(0, sepIdx);
if (logger.isDebugEnabled()) {
logger.debug("Found bean name '" + beanName + "'");
}
if (!getRegistry().containsBeanDefinition(beanName)) {
// If we haven't already registered it...
registerBeanDefinition(beanName, map, prefix + beanName, resourceDescription);
++beanCount;
}
}
else {
// Ignore it: It wasn't a valid bean name and property,
// although it did start with the required prefix.
if (logger.isDebugEnabled()) {
logger.debug("Invalid bean name and property [" + nameAndProperty + "]");
}
}
}
}
return beanCount;
}
/**
* Register bean definitions contained in a Map.
* Ignore ineligible properties.
* @param map Map name -> property (String or Object). Property values
* will be strings if coming from a Properties file etc. Property names
* (keys) <b>must</b> be strings. Class keys must be Strings.
* @param prefix a filter within the keys in the map: e.g. 'beans.'
* (can be empty or {@code null})
* @param resourceDescription description of the resource that the
* Map came from (for logging purposes)
* @return the number of bean definitions found
* @throws BeansException in case of loading or parsing errors
* @see #registerBeanDefinitions(Map, String)
*/
public int registerBeanDefinitions(Map<?, ?> map, String prefix, String resourceDescription)
throws BeansException {
if (prefix == null) {
prefix = "";
}
int beanCount = 0;
for (Object key : map.keySet()) {
if (!(key instanceof String)) {
throw new IllegalArgumentException("Illegal key [" + key + "]: only Strings allowed");
}
String keyString = (String) key;
if (keyString.startsWith(prefix)) {
// Key is of form: prefix<name>.property
String nameAndProperty = keyString.substring(prefix.length());
// Find dot before property name, ignoring dots in property keys.
int sepIdx = -1;
int propKeyIdx = nameAndProperty.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX);
if (propKeyIdx != -1) {
sepIdx = nameAndProperty.lastIndexOf(SEPARATOR, propKeyIdx);
}
else {
sepIdx = nameAndProperty.lastIndexOf(SEPARATOR);
}
if (sepIdx != -1) {
String beanName = nameAndProperty.substring(0, sepIdx);
if (logger.isDebugEnabled()) {
logger.debug("Found bean name '" + beanName + "'");
}
if (!getRegistry().containsBeanDefinition(beanName)) {
// If we haven't already registered it...
registerBeanDefinition(beanName, map, prefix + beanName, resourceDescription);
++beanCount;
}
}
else {
// Ignore it: It wasn't a valid bean name and property,
// although it did start with the required prefix.
if (logger.isDebugEnabled()) {
logger.debug("Invalid bean name and property [" + nameAndProperty + "]");
}
}
}
}
return beanCount;
}
/**
* Writes the opening part of the block '{@code form}' tag and exposes
* the form object name in the {@link javax.servlet.jsp.PageContext}.
* @param tagWriter the {@link TagWriter} to which the form content is to be written
* @return {@link javax.servlet.jsp.tagext.Tag#EVAL_BODY_INCLUDE}
*/
@Override
protected int writeTagContent(TagWriter tagWriter) throws JspException {
this.tagWriter = tagWriter;
tagWriter.startTag(FORM_TAG);
writeDefaultAttributes(tagWriter);
tagWriter.writeAttribute(ACTION_ATTRIBUTE, resolveAction());
writeOptionalAttribute(tagWriter, METHOD_ATTRIBUTE, getHttpMethod());
writeOptionalAttribute(tagWriter, TARGET_ATTRIBUTE, getTarget());
writeOptionalAttribute(tagWriter, ENCTYPE_ATTRIBUTE, getEnctype());
writeOptionalAttribute(tagWriter, ACCEPT_CHARSET_ATTRIBUTE, getAcceptCharset());
writeOptionalAttribute(tagWriter, ONSUBMIT_ATTRIBUTE, getOnsubmit());
writeOptionalAttribute(tagWriter, ONRESET_ATTRIBUTE, getOnreset());
writeOptionalAttribute(tagWriter, AUTOCOMPLETE_ATTRIBUTE, getAutocomplete());
tagWriter.forceBlock();
if (!isMethodBrowserSupported(getMethod())) {
assertHttpMethod(getMethod());
String inputName = getMethodParam();
String inputType = "hidden";
tagWriter.startTag(INPUT_TAG);
writeOptionalAttribute(tagWriter, TYPE_ATTRIBUTE, inputType);
writeOptionalAttribute(tagWriter, NAME_ATTRIBUTE, inputName);
writeOptionalAttribute(tagWriter, VALUE_ATTRIBUTE, processFieldValue(inputName, getMethod(), inputType));
tagWriter.endTag();
}
// Expose the form object name for nested tags...
String modelAttribute = resolveModelAttribute();
this.pageContext.setAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, modelAttribute, PageContext.REQUEST_SCOPE);
// Save previous nestedPath value, build and expose current nestedPath value.
// Use request scope to expose nestedPath to included pages too.
this.previousNestedPath =
(String) this.pageContext.getAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME,
modelAttribute + PropertyAccessor.NESTED_PROPERTY_SEPARATOR, PageContext.REQUEST_SCOPE);
return EVAL_BODY_INCLUDE;
}
/**
* Register bean definitions contained in a Map.
* Ignore ineligible properties.
* @param map Map name -> property (String or Object). Property values
* will be strings if coming from a Properties file etc. Property names
* (keys) <b>must</b> be strings. Class keys must be Strings.
* @param prefix a filter within the keys in the map: e.g. 'beans.'
* (can be empty or {@code null})
* @param resourceDescription description of the resource that the
* Map came from (for logging purposes)
* @return the number of bean definitions found
* @throws BeansException in case of loading or parsing errors
* @see #registerBeanDefinitions(Map, String)
*/
public int registerBeanDefinitions(Map<?, ?> map, String prefix, String resourceDescription)
throws BeansException {
if (prefix == null) {
prefix = "";
}
int beanCount = 0;
for (Object key : map.keySet()) {
if (!(key instanceof String)) {
throw new IllegalArgumentException("Illegal key [" + key + "]: only Strings allowed");
}
String keyString = (String) key;
if (keyString.startsWith(prefix)) {
// Key is of form: prefix<name>.property
String nameAndProperty = keyString.substring(prefix.length());
// Find dot before property name, ignoring dots in property keys.
int sepIdx = -1;
int propKeyIdx = nameAndProperty.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX);
if (propKeyIdx != -1) {
sepIdx = nameAndProperty.lastIndexOf(SEPARATOR, propKeyIdx);
}
else {
sepIdx = nameAndProperty.lastIndexOf(SEPARATOR);
}
if (sepIdx != -1) {
String beanName = nameAndProperty.substring(0, sepIdx);
if (logger.isDebugEnabled()) {
logger.debug("Found bean name '" + beanName + "'");
}
if (!getRegistry().containsBeanDefinition(beanName)) {
// If we haven't already registered it...
registerBeanDefinition(beanName, map, prefix + beanName, resourceDescription);
++beanCount;
}
}
else {
// Ignore it: It wasn't a valid bean name and property,
// although it did start with the required prefix.
if (logger.isDebugEnabled()) {
logger.debug("Invalid bean name and property [" + nameAndProperty + "]");
}
}
}
}
return beanCount;
}
/**
* Create Order from criteria and property path
* @param criteria the hibernate criteria to apply order on
* @param propertyPath the property path
* @return Order
*/
protected Order createOrder(Criteria criteria, String propertyPath, boolean ascending) {
Order order = null;
if (propertyPath != null) {
String sortProperty = PropertyUtils.getPropertyName(propertyPath);
try {
if (PropertyUtils.isNested(propertyPath)) {
String alias = PropertyUtils.getPropertyName(PropertyUtils.getPath(propertyPath));
// Need to create alias?
// String alias = HibernateUtils.findAliasForPropertyPath(criteria, propertyPath);
HibernateUtils.createAlias(criteria, PropertyUtils.getPath(propertyPath));
sortProperty = alias + PropertyUtils.PROPERTY_SEPARATOR + sortProperty;
}
else { // test if property is an entity class
Type sortType = getClassMetadata().getPropertyType(propertyPath);
if (sortType.isEntityType()) { // is entity, look for 'name' property
String[] propertyNames = getClassMetadata(sortType.getReturnedClass()).getPropertyNames();
for (String name : propertyNames) {
if ("name".equals(name)) {
log.info("Found property name on persistent class: " + sortType.getName());
String newPath = propertyPath + PropertyAccessor.NESTED_PROPERTY_SEPARATOR + "name";
return createOrder(criteria, newPath, ascending);
}
}
}
}
if (log.isDebugEnabled())
log.debug("Setting order as: " + sortProperty);
order = ascending ? Order.asc(sortProperty) : Order.desc(sortProperty);
}
catch(HibernateException he) {
log.error("Cannot to create Order for property: " + sortProperty + " for " +
getEntityClass().getSimpleName(), he);
}
}
else {
// add default order by id
ClassMetadata metadata = getClassMetadata();
if (metadata != null)
order = Order.asc(metadata.getIdentifierPropertyName());
}
return order;
}