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.tree; 021 022import java.util.Collection; 023 024import net.sf.json.JSONArray; 025import net.sf.json.JSONObject; 026 027/** 028 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 029 */ 030public class JSonTreeSerializer implements TreeItemVisitor { 031 032 /** 033 * Must be overridden to provide real URLs 034 */ 035 public String getUrl(TreeItem item) { 036 return item.getPath().toString(); 037 } 038 039 public JSONArray toJSON(Collection<TreeItem> items) { 040 JSONArray ar = new JSONArray(); 041 for (TreeItem item : items) { 042 ar.add(toJSON(item)); 043 } 044 return ar; 045 } 046 047 public JSONArray toJSON(TreeItem[] items) { 048 JSONArray ar = new JSONArray(); 049 for (TreeItem item : items) { 050 ar.add(toJSON(item)); 051 } 052 return ar; 053 } 054 055 public JSONObject toJSON(TreeItem root) { 056 return (JSONObject) root.accept(this); 057 } 058 059 public Object visit(TreeItem item) { 060 JSONArray jsons = null; 061 if (item.isExpanded()) { 062 TreeItem[] children = item.getChildren(); 063 if (children != null && children.length > 0) { 064 jsons = new JSONArray(); 065 for (TreeItem child : children) { 066 JSONObject childJson = (JSONObject) visit(child); 067 jsons.add(childJson); 068 } 069 } 070 } 071 return item2JSON(item, jsons); 072 } 073 074 /** 075 * You may override this method to change the output JSON. 076 */ 077 protected JSONObject item2JSON(TreeItem item, JSONArray children) { 078 JSONObject json = new JSONObject(); 079 json.element("text", item.getLabel()).element("id", item.getPath().toString()).element("href", getUrl(item)); 080 json.element("expanded", item.isExpanded()); 081 if (item.isContainer()) { 082 if (item.isContainer()) { 083 if (item.hasChildren()) { 084 json.element("children", children); 085 } else { 086 json.element("hasChildren", true); 087 } 088 } else { 089 json.element("hasChildren", false); 090 } 091 } 092 return json; 093 } 094 095}