001/* 002 * (C) Copyright 2006-2010 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * bstefanescu 018 */ 019package org.nuxeo.shell.impl; 020 021import org.nuxeo.shell.CommandRegistry; 022import org.nuxeo.shell.CommandType; 023import org.nuxeo.shell.Shell; 024import org.nuxeo.shell.ShellException; 025import org.nuxeo.shell.ValueAdapter; 026 027/** 028 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 029 */ 030public class DefaultValueAdapter implements ValueAdapter { 031 032 @SuppressWarnings("unchecked") 033 public <T> T getValue(Shell shell, Class<T> type, String value) { 034 if (type == CharSequence.class || type == String.class) { 035 return (T) value; 036 } 037 if (type.isPrimitive()) { 038 if (type == Boolean.TYPE) { 039 return (T) Boolean.valueOf(value); 040 } else if (type == Integer.TYPE) { 041 return (T) Integer.valueOf(value); 042 } else if (type == Float.TYPE) { 043 return (T) Float.valueOf(value); 044 } else if (type == Long.TYPE) { 045 return (T) Long.valueOf(value); 046 } else if (type == Double.TYPE) { 047 return (T) Double.valueOf(value); 048 } else if (type == Character.TYPE) { 049 return (T) (Character.valueOf(value == null || value.length() == 0 ? '\0' : value.charAt(0))); 050 } 051 } else if (type == Boolean.class) { 052 return (T) Boolean.valueOf(value); 053 } else if (Number.class.isAssignableFrom(type)) { 054 if (type == Integer.class) { 055 return (T) Integer.valueOf(value); 056 } else if (type == Float.class) { 057 return (T) Float.valueOf(value); 058 } else if (type == Long.class) { 059 return (T) Long.valueOf(value); 060 } else if (type == Double.class) { 061 return (T) Double.valueOf(value); 062 } 063 } else if (type == Character.class) { 064 return (T) (Character.valueOf(value == null || value.length() == 0 ? '\0' : value.charAt(0))); 065 } else if (CommandType.class.isAssignableFrom(type)) { 066 CommandType cmd = shell.getActiveRegistry().getCommandType(value); 067 if (cmd == null) { 068 throw new ShellException("Unknown command: " + value); 069 } 070 return (T) cmd; 071 } else if (CommandRegistry.class.isAssignableFrom(type)) { 072 CommandRegistry reg = shell.getRegistry(value); 073 if (reg == null) { 074 throw new ShellException("Unknown namespace: " + value); 075 } 076 return (T) reg; 077 } 078 return null; 079 080 } 081 082}