1   /*
2    * Copyright 2017 LINE Corporation
3    *
4    * LINE Corporation licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  /*
17   * Copyright (c) 2014, Francis Galiegue (fgaliegue@gmail.com)
18   *
19   * This software is dual-licensed under:
20   *
21   * - the Lesser General Public License (LGPL) version 3.0 or, at your option, any
22   *   later version;
23   * - the Apache Software License (ASL) version 2.0.
24   *
25   * The text of this file and of both licenses is available at the root of this
26   * project or, if you have the jar distribution, in directory META-INF/, under
27   * the names LGPL-3.0.txt and ASL-2.0.txt respectively.
28   *
29   * Direct link to the sources:
30   *
31   * - LGPL 3.0: https://www.gnu.org/licenses/lgpl-3.0.txt
32   * - ASL 2.0: https://www.apache.org/licenses/LICENSE-2.0.txt
33   */
34  
35  package com.linecorp.centraldogma.internal.jsonpatch;
36  
37  import com.fasterxml.jackson.annotation.JsonCreator;
38  import com.fasterxml.jackson.annotation.JsonProperty;
39  import com.fasterxml.jackson.core.JsonPointer;
40  import com.fasterxml.jackson.databind.JsonNode;
41  import com.fasterxml.jackson.databind.node.ArrayNode;
42  import com.fasterxml.jackson.databind.node.ObjectNode;
43  
44  /**
45   * JSON Patch {@code add} operation.
46   *
47   * <p>For this operation, {@code path} is the JSON Pointer where the value
48   * should be added, and {@code value} is the value to add.</p>
49   *
50   * <p>Note that if the target value pointed to by {@code path} already exists,
51   * it is replaced. In this case, {@code add} is equivalent to {@code replace}.
52   * </p>
53   *
54   * <p>Note also that a value will be created at the target path <b>if and only
55   * if</b> the immediate parent of that value exists (and is of the correct
56   * type).</p>
57   *
58   * <p>Finally, if the last reference token of the JSON Pointer is {@code -} and
59   * the immediate parent is an array, the given value is added at the end of the
60   * array. For instance, applying:</p>
61   *
62   * <pre>
63   *     { "op": "add", "path": "/-", "value": 3 }
64   * </pre>
65   *
66   * <p>to:</p>
67   *
68   * <pre>
69   *     [ 1, 2 ]
70   * </pre>
71   *
72   * <p>will give:</p>
73   *
74   * <pre>
75   *     [ 1, 2, 3 ]
76   * </pre>
77   */
78  public final class AddOperation extends PathValueOperation {
79  
80      private static final String LAST_ARRAY_ELEMENT = "-";
81  
82      @JsonCreator
83      public AddOperation(@JsonProperty("path") final JsonPointer path,
84                          @JsonProperty("value") final JsonNode value) {
85          super("add", path, value);
86      }
87  
88      @Override
89      JsonNode apply(final JsonNode node) {
90          if (path.toString().isEmpty()) {
91              return valueCopy();
92          }
93  
94          final JsonNode targetParent = ensureTargetParent(node, path);
95          return targetParent.isArray() ? addToArray(path, node, valueCopy())
96                                        : addToObject(path, node, valueCopy());
97      }
98  
99      static JsonNode addToArray(final JsonPointer path, final JsonNode node, final JsonNode value) {
100         final ArrayNode target = (ArrayNode) node.at(path.head());
101         final String rawToken = path.last().getMatchingProperty();
102 
103         if (rawToken.equals(LAST_ARRAY_ELEMENT)) {
104             target.add(value);
105             return node;
106         }
107 
108         final int size = target.size();
109         final int index;
110         try {
111             index = Integer.parseInt(rawToken);
112         } catch (NumberFormatException ignored) {
113             throw new JsonPatchException("not an index: " + rawToken + " (expected: a non-negative integer)");
114         }
115 
116         if (index < 0 || index > size) {
117             throw new JsonPatchException("index out of bounds: " + index +
118                                          " (expected: >= 0 && <= " + size + ')');
119         }
120 
121         target.insert(index, value);
122         return node;
123     }
124 
125     static JsonNode addToObject(final JsonPointer path, final JsonNode node, final JsonNode value) {
126         final ObjectNode target = (ObjectNode) node.at(path.head());
127         target.set(path.last().getMatchingProperty(), value);
128         return node;
129     }
130 }