001/* 002 * (C) Copyright 2006-2011 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 * tdelprat 018 */ 019package org.nuxeo.ecm.automation.core.impl.adapters; 020 021import java.util.HashMap; 022import java.util.Iterator; 023import java.util.Map; 024import java.util.Map.Entry; 025 026import org.codehaus.jackson.JsonNode; 027import org.nuxeo.ecm.automation.OperationContext; 028import org.nuxeo.ecm.automation.TypeAdaptException; 029import org.nuxeo.ecm.automation.TypeAdapter; 030import org.nuxeo.ecm.automation.core.util.Properties; 031 032public class JsonNodeToProperties implements TypeAdapter { 033 034 @Override 035 public Object getAdaptedValue(OperationContext ctx, Object objectToAdapt) throws TypeAdaptException { 036 037 JsonNode json = (JsonNode) objectToAdapt; 038 Map<String, String> map = new HashMap<String, String>(); 039 040 Iterator<Entry<String, JsonNode>> it = json.getFields(); 041 while (it.hasNext()) { 042 Entry<String, JsonNode> entry = it.next(); 043 String key = entry.getKey(); 044 JsonNode value = entry.getValue(); 045 if (value.isArray()) { 046 int size = value.size(); 047 if (size == 0) { 048 map.put(key, null); 049 } else if (size == 1) { 050 map.put(key, value.get(0).getValueAsText()); 051 } else { 052 StringBuilder buf = new StringBuilder(size * 32); 053 buf.append(value.get(0).getValueAsText()); 054 for (int i = 1; i < size; i++) { 055 buf.append(',').append(value.get(i).getValueAsText()); 056 } 057 map.put(key, buf.toString()); 058 } 059 } else { 060 if (value.isTextual()) { 061 map.put(key, value.getTextValue()); 062 } else { 063 map.put(key, value.toString()); 064 } 065 } 066 } 067 return new Properties(map); 068 } 069 070}