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.util; 020 021import java.util.Enumeration; 022import java.util.Iterator; 023import java.util.Map; 024 025import lucee.runtime.exp.CasterException; 026import lucee.runtime.exp.PageException; 027import lucee.runtime.op.Caster; 028import lucee.runtime.op.Decision; 029import lucee.runtime.text.xml.XMLCaster; 030import lucee.runtime.type.ForEachIteratorable; 031import lucee.runtime.type.ObjectWrap; 032import lucee.runtime.type.it.EnumAsIt; 033import lucee.runtime.type.it.ForEachQueryIterator; 034import lucee.runtime.type.util.ListUtil; 035import lucee.runtime.type.wrap.MapAsStruct; 036 037import org.w3c.dom.Node; 038 039public class ForEachUtil { 040 041 public static Iterator toIterator(Object o) throws PageException { 042 043 044 if(o instanceof ForEachIteratorable) 045 return ((ForEachIteratorable)o).getIterator(); 046 047 else if(o instanceof Node)return XMLCaster.toXMLStruct((Node)o,false).getIterator(); 048 else if(o instanceof Map) { 049 return MapAsStruct.toStruct((Map)o,true).getIterator(); 050 } 051 else if(o instanceof ObjectWrap) { 052 return toIterator(((ObjectWrap)o).getEmbededObject()); 053 } 054 else if(Decision.isArray(o)) { 055 return Caster.toArray(o).getIterator(); 056 } 057 else if(o instanceof Iterator) { 058 return (Iterator)o; 059 } 060 else if(o instanceof Enumeration) { 061 return new EnumAsIt((Enumeration)o); 062 } 063 else if(o instanceof CharSequence) { 064 return ListUtil.listToArray(o.toString(), ',').getIterator(); 065 } 066 throw new CasterException(o,"collection"); 067 } 068 069 public static void reset(Iterator it) throws PageException { 070 071 if(it instanceof ForEachQueryIterator) { 072 ((ForEachQueryIterator)it).reset(); 073 } 074 } 075 076}