001 /** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018 package org.apache.geronimo.common.propertyeditor; 019 020 import java.beans.PropertyEditor; 021 import java.beans.PropertyEditorSupport; 022 import java.lang.reflect.Array; 023 import java.util.LinkedList; 024 import java.util.List; 025 import java.util.StringTokenizer; 026 027 /** 028 * Adapter for editing array types. 029 * 030 * @version $Rev: 706640 $ $Date: 2008-10-21 14:44:05 +0000 (Tue, 21 Oct 2008) $ 031 */ 032 public final class ArrayPropertyEditorAdapter extends PropertyEditorSupport { 033 private Class type; 034 private PropertyEditor editor; 035 036 public ArrayPropertyEditorAdapter(final Class type, final PropertyEditor editor) { 037 if (type == null) { 038 throw new IllegalArgumentException("Type is null"); 039 } 040 if (editor == null) { 041 throw new IllegalArgumentException("Editor is null"); 042 } 043 044 this.type = type; 045 this.editor = editor; 046 } 047 048 public void setAsText(String text) { 049 if (text == null || text.length() == 0) { 050 setValue(null); 051 } else { 052 StringTokenizer stok = new StringTokenizer(text, ","); 053 final List list = new LinkedList(); 054 055 while (stok.hasMoreTokens()) { 056 editor.setAsText(stok.nextToken()); 057 list.add(editor.getValue()); 058 } 059 060 Object array = Array.newInstance(type, list.size()); 061 for (int i = 0; i < list.size(); i++) { 062 Array.set(array, i, list.get(i)); 063 } 064 065 setValue(array); 066 } 067 } 068 069 public String getAsText() { 070 Object[] objects = (Object[]) getValue(); 071 if (objects == null || objects.length == 0) { 072 return null; 073 } 074 075 StringBuffer result = new StringBuffer(String.valueOf(objects[0])); 076 for (int i = 1; i < objects.length; i++) { 077 result.append(",").append(objects[i]); 078 } 079 080 return result.toString(); 081 082 } 083 }