001/* 002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others. 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-2.1.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 * Thierry Delprat <tdelprat@nuxeo.com> 016 */ 017package org.nuxeo.automation.scripting.internals; 018 019import java.util.ArrayList; 020import java.util.HashMap; 021import java.util.List; 022import java.util.Map; 023 024import jdk.nashorn.api.scripting.ScriptObjectMirror; 025 026/** 027 * @since 7.2 028 */ 029public class MarshalingHelper { 030 031 @SuppressWarnings("unchecked") 032 public static Map<String, Object> unwrapMap(ScriptObjectMirror jso) { 033 if (jso.isArray()) { 034 throw new UnsupportedOperationException("JavaScript input is an Array!"); 035 } 036 return (Map<String, Object>) unwrap(jso); 037 } 038 039 public static Object unwrap(ScriptObjectMirror jso) { 040 if (jso.isArray()) { 041 List<Object> l = new ArrayList<>(); 042 for (Object o : jso.values()) { 043 if (o instanceof ScriptObjectMirror) { 044 l.add(unwrap((ScriptObjectMirror) o)); 045 } else { 046 l.add(o); 047 } 048 } 049 return l; 050 } else { 051 Map<String, Object> result = new HashMap<>(); 052 for (String k : jso.keySet()) { 053 Object o = jso.get(k); 054 if (o instanceof ScriptObjectMirror) { 055 result.put(k, unwrap((ScriptObjectMirror) o)); 056 } else { 057 result.put(k, o); 058 } 059 } 060 return result; 061 } 062 } 063 064 public static Object wrap(Map<String, Object> map) { 065 return ScriptObjectMirror.wrap(map, null); 066 } 067 068}