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