001 /* $Id: SetPropertiesRuleProvider.java 992060 2010-09-02 19:09:47Z simonetripodi $ 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one or more 004 * contributor license agreements. See the NOTICE file distributed with 005 * this work for additional information regarding copyright ownership. 006 * The ASF licenses this file to You under the Apache License, Version 2.0 007 * (the "License"); you may not use this file except in compliance with 008 * the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018 package org.apache.commons.digester.annotations.providers; 019 020 import java.lang.reflect.Field; 021 import java.util.HashMap; 022 import java.util.Map; 023 import java.util.Map.Entry; 024 025 import org.apache.commons.digester.SetPropertiesRule; 026 import org.apache.commons.digester.annotations.AnnotationRuleProvider; 027 import org.apache.commons.digester.annotations.rules.SetProperty; 028 029 /** 030 * Provides instances of {@code SetPropertiesRule}. 031 * 032 * @since 2.1 033 */ 034 public final class SetPropertiesRuleProvider implements AnnotationRuleProvider<SetProperty, Field, SetPropertiesRule> { 035 036 /** 037 * The data structure that stores the aliases. 038 */ 039 private final Map<String, String> aliases = new HashMap<String, String>(); 040 041 /** 042 * {@inheritDoc} 043 */ 044 public void init(SetProperty annotation, Field element) { 045 this.addAlias(annotation, element); 046 } 047 048 /** 049 * Adds a new alias attribute/property name; if the attribute name is not 050 * specified, the alias will be considered as property name identity. 051 * 052 * @param annotation the {@link SetProperty} reference. 053 * @param element the annotated element reference. 054 */ 055 public void addAlias(SetProperty annotation, Field element) { 056 String attributeName = annotation.attributeName(); 057 String propertyName = element.getName(); 058 059 if (attributeName.length() > 0) { 060 this.aliases.put(attributeName, propertyName); 061 } else { 062 this.aliases.put(propertyName, propertyName); 063 } 064 } 065 066 /** 067 * {@inheritDoc} 068 */ 069 public SetPropertiesRule get() { 070 String[] attributeNames = new String[this.aliases.size()]; 071 String[] propertyNames = new String[this.aliases.size()]; 072 073 int i = 0; 074 for (Entry<String, String> alias : this.aliases.entrySet()) { 075 attributeNames[i] = alias.getKey(); 076 propertyNames[i++] = alias.getValue(); 077 } 078 079 return new SetPropertiesRule(attributeNames, propertyNames); 080 } 081 082 }