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.nuxeo.ecm.automation.OperationContext;
027import org.nuxeo.ecm.automation.TypeAdaptException;
028import org.nuxeo.ecm.automation.TypeAdapter;
029import org.nuxeo.ecm.automation.core.util.Properties;
030
031import com.fasterxml.jackson.databind.JsonNode;
032
033public class JsonNodeToProperties implements TypeAdapter {
034
035    @Override
036    public Object getAdaptedValue(OperationContext ctx, Object objectToAdapt) throws TypeAdaptException {
037
038        JsonNode json = (JsonNode) objectToAdapt;
039        Map<String, String> map = new HashMap<String, String>();
040
041        Iterator<Entry<String, JsonNode>> it = json.fields();
042        while (it.hasNext()) {
043            Entry<String, JsonNode> entry = it.next();
044            String key = entry.getKey();
045            JsonNode value = entry.getValue();
046            if (value.isArray()) {
047                int size = value.size();
048                if (size == 0) {
049                    map.put(key, null);
050                } else if (size == 1) {
051                    map.put(key, value.get(0).asText());
052                } else {
053                    StringBuilder buf = new StringBuilder(size * 32);
054                    buf.append(value.get(0).asText());
055                    for (int i = 1; i < size; i++) {
056                        buf.append(',').append(value.get(i).asText());
057                    }
058                    map.put(key, buf.toString());
059                }
060            } else {
061                if (value.isTextual()) {
062                    map.put(key, value.textValue());
063                } else {
064                    map.put(key, value.toString());
065                }
066            }
067        }
068        return new Properties(map);
069    }
070
071}