001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.runtime.net.rpc;
020
021import java.lang.reflect.Method;
022import java.util.Iterator;
023
024import lucee.commons.lang.ExceptionUtil;
025import lucee.commons.lang.Pair;
026import lucee.runtime.exp.PageRuntimeException;
027import lucee.runtime.op.Caster;
028import lucee.runtime.reflection.Reflector;
029import lucee.runtime.type.Collection;
030import lucee.runtime.type.KeyImpl;
031
032public class PojoIterator implements Iterator<Pair<Collection.Key,Object>> {
033        
034        private static final Object[] EMPTY_ARG = new Object[]{}; 
035        
036        private Pojo pojo;
037        private Method[] getters;
038        private Class<? extends Pojo> clazz;
039        private int index=-1;
040
041        public PojoIterator(Pojo pojo) {
042                this.pojo=pojo;
043                this.clazz=pojo.getClass();
044                getters = Reflector.getGetters(pojo.getClass());
045        }
046        
047        public int size() {
048                return getters.length;
049        }
050
051        @Override
052        public boolean hasNext() {
053                return (index+1)<getters.length;
054        }
055
056        @Override
057        public Pair<Collection.Key, Object> next() {
058                Method g = getters[++index];
059                try {
060                        
061                        return new Pair<Collection.Key, Object>(KeyImpl.init(g.getName().substring(3)), g.invoke(pojo, EMPTY_ARG));
062                }
063                catch (Throwable t) {
064                        ExceptionUtil.rethrowIfNecessary(t);
065                        throw new PageRuntimeException(Caster.toPageException(t));
066                }
067        }
068
069        @Override
070        public void remove() {
071                throw new RuntimeException("method remove is not supported!");
072        }
073
074}