001/*
002 * (C) Copyright 2016 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 *     Antoine Taillefer <ataillefer@nuxeo.com>
018 */
019package org.nuxeo.drive.adapter.impl;
020
021import java.io.IOException;
022import java.util.ArrayList;
023import java.util.List;
024
025import org.nuxeo.drive.adapter.FileSystemItem;
026import org.nuxeo.drive.adapter.ScrollFileSystemItemList;
027
028import com.fasterxml.jackson.core.JsonParser;
029import com.fasterxml.jackson.databind.DeserializationContext;
030import com.fasterxml.jackson.databind.JsonDeserializer;
031import com.fasterxml.jackson.databind.JsonNode;
032import com.fasterxml.jackson.databind.ObjectMapper;
033import com.fasterxml.jackson.databind.node.ArrayNode;
034import com.fasterxml.jackson.databind.node.BooleanNode;
035import com.fasterxml.jackson.databind.node.TextNode;
036
037/**
038 * {@link JsonDeserializer} for a {@link ScrollFileSystemItemList}.
039 *
040 * @since 8.3
041 */
042public class ScrollFileSystemItemListDeserializer extends JsonDeserializer<ScrollFileSystemItemList> {
043
044    @Override
045    public ScrollFileSystemItemList deserialize(JsonParser jp, DeserializationContext dc) throws IOException {
046        JsonNode rootNode = jp.readValueAsTree();
047        String scrollId = ((TextNode) rootNode.get("scrollId")).textValue();
048        ObjectMapper mapper = new ObjectMapper();
049        ArrayNode fileSystemItemNodes = (ArrayNode) rootNode.get("fileSystemItems");
050        List<FileSystemItem> fileSystemItems = new ArrayList<>(fileSystemItemNodes.size());
051        for (JsonNode fileSystemItemNode : fileSystemItemNodes) {
052            boolean folderish = ((BooleanNode) fileSystemItemNode.get("folder")).booleanValue();
053            if (folderish) {
054                fileSystemItems.add(readValue(mapper, fileSystemItemNode, DocumentBackedFolderItem.class));
055            } else {
056                fileSystemItems.add(readValue(mapper, fileSystemItemNode, DocumentBackedFileItem.class));
057            }
058        }
059        return new ScrollFileSystemItemListImpl(scrollId, fileSystemItems);
060    }
061
062    protected <T> T readValue(ObjectMapper mapper, JsonNode node, Class<T> klass) throws IOException {
063        try (JsonParser tokens = mapper.treeAsTokens(node)) {
064            return mapper.readValue(tokens, klass);
065        }
066    }
067
068}