001// Copyright 2004, 2005 The Apache Software Foundation 002// 003// Licensed under the Apache License, Version 2.0 (the "License"); 004// you may not use this file except in compliance with the License. 005// You may obtain a copy of the License at 006// 007// http://www.apache.org/licenses/LICENSE-2.0 008// 009// Unless required by applicable law or agreed to in writing, software 010// distributed under the License is distributed on an "AS IS" BASIS, 011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012// See the License for the specific language governing permissions and 013// limitations under the License. 014 015package org.apache.hivemind.schema.rules; 016 017import java.beans.PropertyEditor; 018import java.beans.PropertyEditorManager; 019import java.util.Map; 020 021import org.apache.hivemind.ApplicationRuntimeException; 022import org.apache.hivemind.Location; 023import org.apache.hivemind.internal.Module; 024import org.apache.hivemind.schema.Translator; 025 026/** 027 * A "smart" translator that attempts to automatically convert from string types to object or 028 * wrapper types, using {@link java.beans.PropertyEditor}s. 029 * 030 * @author Howard Lewis Ship 031 */ 032public class SmartTranslator implements Translator 033{ 034 private String _default; 035 036 public SmartTranslator() 037 { 038 } 039 040 /** 041 * Initializers: 042 * <ul> 043 * <li>default: default value for empty input 044 * </ul> 045 */ 046 public SmartTranslator(String initializer) 047 { 048 Map m = RuleUtils.convertInitializer(initializer); 049 050 _default = (String) m.get("default"); 051 } 052 053 public Object translate(Module contributingModule, Class propertyType, String inputValue, 054 Location location) 055 { 056 // HIVEMIND-10: Inside JavaWebStart you (strangely) can't rely on 057 // a PropertyEditor for String (even though it is trivial). 058 059 if (inputValue == null) 060 { 061 if (_default == null) 062 return null; 063 064 inputValue = _default; 065 } 066 067 if (propertyType.equals(String.class) || propertyType.equals(Object.class)) 068 return inputValue; 069 070 // TODO: This duplicates logic inside PropertyAdaptor. 071 072 try 073 { 074 PropertyEditor e = PropertyEditorManager.findEditor(propertyType); 075 076 if (e == null) 077 throw new ApplicationRuntimeException(RulesMessages.noPropertyEditor(propertyType), 078 location, null); 079 080 e.setAsText(inputValue); 081 082 return e.getValue(); 083 } 084 catch (Exception ex) 085 { 086 throw new ApplicationRuntimeException(RulesMessages.smartTranslatorError( 087 inputValue, 088 propertyType, 089 ex), location, ex); 090 091 } 092 } 093 094}