001/* 002 * (C) Copyright 2006-2008 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 * 019 * $Id$ 020 */ 021 022package org.nuxeo.ecm.webengine.ui.json; 023 024import java.util.ArrayList; 025import java.util.Collection; 026import java.util.List; 027import java.util.Map; 028 029import org.nuxeo.common.utils.StringUtils; 030 031/** 032 * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> 033 */ 034public abstract class JQueryTreeBuilder<T> { 035 036 public static final String CHILDREN = "children"; 037 038 public List<Map<String, Object>> buildTree(T root, String path) { 039 if (path == null || path.length() == 0 || "/".equals(path)) { 040 return buildChildren(root); 041 } 042 String[] ar = StringUtils.split(path, '/', false); 043 if (ar.length > 1) { 044 String name = getName(root); 045 if (name.equals(ar[0])) { 046 return buildChildren(root, ar, 1); 047 } 048 } 049 050 return buildChildren(root); 051 } 052 053 public List<Map<String, Object>> buildChildren(T parent) { 054 List<Map<String, Object>> json = new ArrayList<>(); 055 Collection<T> children = getChildren(parent); 056 if (children != null) { 057 for (T obj : children) { 058 Map<String, Object> map = toJson(obj); 059 json.add(map); 060 } 061 } 062 return json; 063 } 064 065 public List<Map<String, Object>> buildChildren(T parent, String[] path, int off) { 066 List<Map<String, Object>> json = new ArrayList<>(); 067 String expandName = path[off]; 068 Collection<T> children = getChildren(parent); 069 if (children != null) { 070 for (T obj : children) { 071 Map<String, Object> map = toJson(obj); 072 String childName = getName(obj); 073 if (expandName.equals(childName)) { 074 List<Map<String, Object>> jsonChildren; 075 if (off < path.length - 1) { 076 jsonChildren = buildChildren(obj, path, off + 1); 077 } else { 078 jsonChildren = buildChildren(obj); 079 } 080 map.put(CHILDREN, jsonChildren); 081 } 082 json.add(map); 083 } 084 } 085 return json; 086 } 087 088 protected abstract T getObject(String name); 089 090 protected abstract String getName(T obj); 091 092 protected abstract Collection<T> getChildren(T obj); 093 094 protected abstract Map<String, Object> toJson(T obj); 095 096}