/**
 * Copyright 2009-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.javacrumbs.jsonunit.core.internal;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.NullNode;
import net.javacrumbs.jsonunit.providers.Jackson2ObjectMapperProvider;

import java.io.IOException;
import java.io.Reader;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;

import static net.javacrumbs.jsonunit.core.internal.Utils.closeQuietly;

/**
 * Deserializes node using Jackson 2
 */
class Jackson2NodeFactory extends AbstractNodeFactory {
    private final ServiceLoader<Jackson2ObjectMapperProvider> serviceLoader = ServiceLoader.load(Jackson2ObjectMapperProvider.class);

    @Override
    protected Node doConvertValue(Object source) {
        if (source instanceof JsonNode) {
            return newNode((JsonNode) source);
        } else {
            return newNode(getMapper(false).convertValue(source, JsonNode.class));
        }
    }

    @Override
    protected Node nullNode() {
        return newNode(NullNode.getInstance());
    }

    protected Node readValue(Reader value, String label, boolean lenient) {
        try {
            return newNode(getMapper(lenient).readTree(value));
        } catch (IOException e) {
            throw new IllegalArgumentException("Can not parse " + label + " value.", e);
        } finally {
            closeQuietly(value);
        }
    }

    private ObjectMapper getMapper(boolean lenient) {
        return getMapperProvider().getObjectMapper(lenient);
    }

    private synchronized Jackson2ObjectMapperProvider getMapperProvider() {
        Iterator<Jackson2ObjectMapperProvider> iterator = serviceLoader.iterator();
        if (iterator.hasNext()) {
            return iterator.next();
        } else {
            return DefaultObjectMapperProvider.INSTANCE;
        }
    }

    private static Node newNode(JsonNode jsonNode) {
        if (jsonNode != null && !jsonNode.isMissingNode()) {
            return new Jackson2Node(jsonNode);
        } else {
            return Node.MISSING_NODE;
        }
    }

    public boolean isPreferredFor(Object source) {
        return source instanceof JsonNode;
    }

    static final class Jackson2Node extends AbstractNode {
        private final JsonNode jsonNode;

        Jackson2Node(JsonNode jsonNode) {
            this.jsonNode = jsonNode;
        }

        public Node element(int index) {
            return newNode(jsonNode.path(index));
        }

        public Iterator<KeyValue> fields() {
            final Iterator<Map.Entry<String, JsonNode>> iterator = jsonNode.fields();
            return new Iterator<KeyValue>() {
                public boolean hasNext() {
                    return iterator.hasNext();
                }

                public void remove() {
                    iterator.remove();
                }

                public KeyValue next() {
                    Map.Entry<String, JsonNode> entry = iterator.next();
                    return new KeyValue(entry.getKey(), newNode(entry.getValue()));
                }
            };
        }

        public Node get(String key) {
            return newNode(jsonNode.get(key));
        }

        public boolean isMissingNode() {
            return false;
        }

        public boolean isNull() {
            return jsonNode.isNull();
        }

        public Iterator<Node> arrayElements() {
            final Iterator<JsonNode> elements = jsonNode.elements();
            return new Iterator<Node>() {
                public boolean hasNext() {
                    return elements.hasNext();
                }

                public Node next() {
                    return newNode(elements.next());
                }

                public void remove() {
                    elements.remove();
                }
            };
        }

        public int size() {
           return jsonNode.size();
        }

        public String asText() {
            return jsonNode.asText();
        }

        public NodeType getNodeType() {
            if (jsonNode.isObject()) {
                return NodeType.OBJECT;
            } else if (jsonNode.isArray()) {
                return NodeType.ARRAY;
            } else if (jsonNode.isTextual()) {
                return NodeType.STRING;
            } else if (jsonNode.isNumber()) {
                return NodeType.NUMBER;
            } else if (jsonNode.isBoolean()) {
                return NodeType.BOOLEAN;
            } else if (jsonNode.isNull()) {
                return NodeType.NULL;
            } else if (jsonNode.isBinary()) {
                return NodeType.STRING;
            } else {
                throw new IllegalStateException("Unexpected node type " + jsonNode);
            }
        }

        public BigDecimal decimalValue() {
            return jsonNode.decimalValue();
        }

        public Boolean asBoolean() {
            return jsonNode.asBoolean();
        }

        @Override
        public String toString() {
            return jsonNode.toString();
        }
    }

    private static class DefaultObjectMapperProvider implements Jackson2ObjectMapperProvider {
        static final Jackson2ObjectMapperProvider INSTANCE = new DefaultObjectMapperProvider();

        private static final ObjectMapper mapper = new ObjectMapper();
        private static final ObjectMapper lenientMapper = new ObjectMapper();

        static {
            lenientMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            lenientMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            lenientMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        }
        @Override
        public ObjectMapper getObjectMapper(boolean lenient) {
            return lenient ? lenientMapper : mapper;
        }
    }
}

@@ -2262,21 +2262,8 @@
 ate 
-synchronized 
 Jack
@@ -2305,24 +2305,67 @@
 rovider() %7B%0A
+        synchronized (serviceLoader) %7B%0A    
         Iter
@@ -2440,24 +2440,28 @@
 ();%0A        
+    
 if (iterator
@@ -2478,32 +2478,36 @@
 ) %7B%0A            
+    
 return iterator.
@@ -2514,32 +2514,36 @@
 next();%0A        
+ 
+   
 %7D else %7B%0A       
@@ -2527,32 +2527,36 @@
        %7D else %7B%0A
+    
             retu
@@ -2596,16 +2596,30 @@
 STANCE;%0A
+            %7D%0A
         

Synchronize over serviceLoader