001/*
002 * Copyright (c) 2006-2011 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 Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     tdelprat
011 */
012package org.nuxeo.ecm.automation.core.impl.adapters;
013
014import java.util.HashMap;
015import java.util.Iterator;
016import java.util.Map;
017import java.util.Map.Entry;
018
019import org.codehaus.jackson.JsonNode;
020import org.nuxeo.ecm.automation.OperationContext;
021import org.nuxeo.ecm.automation.TypeAdaptException;
022import org.nuxeo.ecm.automation.TypeAdapter;
023import org.nuxeo.ecm.automation.core.util.Properties;
024
025public class JsonNodeToProperties implements TypeAdapter {
026
027    @Override
028    public Object getAdaptedValue(OperationContext ctx, Object objectToAdapt) throws TypeAdaptException {
029
030        JsonNode json = (JsonNode) objectToAdapt;
031        Map<String, String> map = new HashMap<String, String>();
032
033        Iterator<Entry<String, JsonNode>> it = json.getFields();
034        while (it.hasNext()) {
035            Entry<String, JsonNode> entry = it.next();
036            String key = entry.getKey();
037            JsonNode value = entry.getValue();
038            if (value.isArray()) {
039                int size = value.size();
040                if (size == 0) {
041                    map.put(key, null);
042                } else if (size == 1) {
043                    map.put(key, value.get(0).getValueAsText());
044                } else {
045                    StringBuilder buf = new StringBuilder(size * 32);
046                    buf.append(value.get(0).getValueAsText());
047                    for (int i = 1; i < size; i++) {
048                        buf.append(',').append(value.get(i).getValueAsText());
049                    }
050                    map.put(key, buf.toString());
051                }
052            } else {
053                if (value.isTextual()) {
054                    map.put(key, value.getTextValue());
055                } else {
056                    map.put(key, value.toString());
057                }
058            }
059        }
060        return new Properties(map);
061    }
062
063}