001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.bean.jsonapi;
018
019import java.util.*;
020
021import org.apache.juneau.marshall.*;
022import org.apache.juneau.marshall.parser.*;
023import org.apache.juneau.marshall.serializer.*;
024import org.apache.juneau.marshall.swap.spi.*;
025
026/**
027 * Per-property {@link ObjectSwap} applied to JSON:API {@code links} maps so that each map entry round-trips
028 * as either a JSON string URL or a {@link JsonApiLink} JSON object per the spec.
029 *
030 * <p>
031 * The swap operates on the whole {@code Map<String,Object>} bean property and walks the entries:
032 * <ul class='spaced-list'>
033 *   <li>On <b>serialize</b> ({@link #swap}): identity - {@code String} values and {@link JsonApiLink} values
034 *     serialize directly as JSON strings and JSON objects respectively.
035 *   <li>On <b>parse</b> ({@link #unswap}): each value that came back as a parsed map (i.e. originally a JSON
036 *     object) is converted to a {@link JsonApiLink}; all other values pass through unchanged.
037 *   <li>{@code null} input ⇒ {@code null} output.
038 * </ul>
039 */
040public class JsonApiLinkOrStringSwap extends ObjectSwap<Object,Object> {
041
042   @Override /* Overridden from ObjectSwap */
043   public Object swap(MarshallingSession session, Object o) throws SerializeException {
044      return o;
045   }
046
047   @Override /* Overridden from ObjectSwap */
048   public Object unswap(MarshallingSession session, Object o, ClassMeta<?> hint) throws ParseException {
049      if (o == null)
050         return null;
051      if (o instanceof Map<?,?> raw) {
052         var out = new LinkedHashMap<String,Object>();
053         var linkCm = session.getClassMeta(JsonApiLink.class);
054         for (var e : raw.entrySet()) {
055            var key = String.valueOf(e.getKey());
056            var v = e.getValue();
057            if (v instanceof Map<?,?>) {
058               out.put(key, session.convertToType(v, linkCm));
059            } else {
060               out.put(key, v);
061            }
062         }
063         return out;
064      }
065      return o;
066   }
067}