001/* 002 * (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * bstefanescu 016 * 017 * $Id$ 018 */ 019 020package org.nuxeo.ecm.webengine.ui.json; 021 022import java.util.Collection; 023 024import net.sf.json.JSONArray; 025import net.sf.json.JSONObject; 026 027import org.nuxeo.common.utils.StringUtils; 028 029/** 030 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 031 */ 032public abstract class JQueryTreeBuilder<T> { 033 034 public static final String CHILDREN = "children"; 035 036 public JSONArray buildTree(String rootName, String path) { 037 return buildTree(rootName, path); 038 } 039 040 public JSONArray buildTree(T root, String path) { 041 if (path == null || path.length() == 0 || "/".equals(path)) { 042 return buildChildren(root); 043 } 044 String[] ar = StringUtils.split(path, '/', false); 045 if (ar.length > 1) { 046 String name = getName(root); 047 if (name.equals(ar[0])) { 048 return buildChildren(root, ar, 1); 049 } 050 } 051 052 return buildChildren(root); 053 } 054 055 public JSONArray buildChildren(T parent) { 056 JSONArray json = new JSONArray(); 057 Collection<T> children = getChildren(parent); 058 if (children != null) { 059 for (T obj : children) { 060 JSONObject map = toJson(obj); 061 json.add(map); 062 } 063 } 064 return json; 065 } 066 067 public JSONArray buildChildren(T parent, String[] path, int off) { 068 JSONArray json = new JSONArray(); 069 String expandName = path[off]; 070 Collection<T> children = getChildren(parent); 071 if (children != null) { 072 for (T obj : children) { 073 JSONObject map = toJson(obj); 074 String childName = getName(obj); 075 if (expandName.equals(childName)) { 076 JSONArray jsonChildren = null; 077 if (off < path.length - 1) { 078 jsonChildren = buildChildren(obj, path, off + 1); 079 } else { 080 jsonChildren = buildChildren(obj); 081 } 082 map.element(CHILDREN, jsonChildren); 083 } 084 json.add(map); 085 } 086 } 087 return json; 088 } 089 090 protected abstract T getObject(String name); 091 092 protected abstract String getName(T obj); 093 094 protected abstract Collection<T> getChildren(T obj); 095 096 protected abstract JSONObject toJson(T obj); 097 098}