001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the
004 * License.
005 *
006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
007 * specific language governing permission and limitations under the License.
008 *
009 * When distributing Covered Software, include this CDDL Header Notice in each file and include
010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
011 * Header, with the fields enclosed by brackets [] replaced by your own identifying
012 * information: "Portions copyright [year] [name of copyright owner]".
013 *
014 * Copyright 2016 ForgeRock AS.
015 */
016package org.forgerock.api.jackson;
017
018import java.io.IOException;
019
020import org.forgerock.api.models.Paths;
021import org.forgerock.util.Reject;
022
023import com.fasterxml.jackson.core.JsonGenerator;
024import com.fasterxml.jackson.databind.BeanDescription;
025import com.fasterxml.jackson.databind.JsonSerializer;
026import com.fasterxml.jackson.databind.SerializationConfig;
027import com.fasterxml.jackson.databind.SerializerProvider;
028import com.fasterxml.jackson.databind.module.SimpleModule;
029import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
030
031/** Jackson Module that adds a serializer modifier for {@link Paths}. */
032public final class PathsModule extends SimpleModule {
033    /** Default constructor. */
034    public PathsModule() {
035        setSerializerModifier(new PathsModifier());
036    }
037
038    private static final class PathsSerializer extends JsonSerializer<Paths> {
039        private final JsonSerializer<Object> defaultSerializer;
040
041        private PathsSerializer(JsonSerializer<Object> defaultSerializer) {
042            this.defaultSerializer = Reject.checkNotNull(defaultSerializer);
043        }
044
045        @Override
046        public void serialize(Paths value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
047            defaultSerializer.serialize(value, gen, serializers);
048        }
049
050        @Override
051        public boolean isEmpty(SerializerProvider provider, Paths value) {
052            return value.getNames().isEmpty();
053        }
054    }
055
056    private static final class PathsModifier extends BeanSerializerModifier {
057        @Override
058        public JsonSerializer<?> modifySerializer(
059                SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
060            if (beanDesc.getBeanClass() == Paths.class) {
061                // reuse the provided serializer by injecting it
062                return new PathsSerializer((JsonSerializer<Object>) serializer);
063            }
064            return serializer;
065        }
066    }
067}