001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with 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, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 * 019 */ 020package org.apache.mina.integration.beans; 021 022import java.beans.PropertyEditor; 023import java.util.EnumSet; 024import java.util.Set; 025import java.util.regex.Pattern; 026 027/** 028 * A {@link PropertyEditor} which converts a {@link String} into 029 * an {@link Enum} and vice versa. 030 * 031 * @author <a href="http://mina.apache.org">Apache MINA Project</a> 032 */ 033@SuppressWarnings("unchecked") 034public class EnumEditor extends AbstractPropertyEditor { 035 private static final Pattern ORDINAL = Pattern.compile("[0-9]+"); 036 037 private final Class enumType; 038 039 private final Set<Enum<?>> enums; 040 041 public EnumEditor(Class enumType) { 042 if (enumType == null) { 043 throw new IllegalArgumentException("enumType"); 044 } 045 046 this.enumType = enumType; 047 this.enums = EnumSet.allOf(enumType); 048 } 049 050 @Override 051 protected String toText(Object value) { 052 return (value == null ? "" : value.toString()); 053 } 054 055 @Override 056 protected Object toValue(String text) throws IllegalArgumentException { 057 if (ORDINAL.matcher(text).matches()) { 058 int ordinal = Integer.parseInt(text); 059 for (Enum<?> e : enums) { 060 if (e.ordinal() == ordinal) { 061 return e; 062 } 063 } 064 065 throw new IllegalArgumentException("wrong ordinal: " + ordinal); 066 } 067 068 for (Enum<?> e : enums) { 069 if (text.equalsIgnoreCase(e.toString())) { 070 return e; 071 } 072 } 073 074 return Enum.valueOf(enumType, text); 075 } 076}