View Javadoc
1   package ca.uhn.fhir.jpa.util.jsonpatch;
2   
3   /*
4    * #%L
5    * HAPI FHIR JPA Server
6    * %%
7    * Copyright (C) 2014 - 2018 University Health Network
8    * %%
9    * Licensed under the Apache License, Version 2.0 (the "License");
10   * you may not use this file except in compliance with the License.
11   * You may obtain a copy of the License at
12   * 
13   *      http://www.apache.org/licenses/LICENSE-2.0
14   * 
15   * Unless required by applicable law or agreed to in writing, software
16   * distributed under the License is distributed on an "AS IS" BASIS,
17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   * See the License for the specific language governing permissions and
19   * limitations under the License.
20   * #L%
21   */
22  
23  import com.google.gson.JsonArray;
24  import com.google.gson.JsonElement;
25  import net.riotopsys.json_patch.JsonPath;
26  import net.riotopsys.json_patch.operation.AbsOperation;
27  
28  import java.util.ArrayList;
29  import java.util.Iterator;
30  import java.util.List;
31  
32  public class CopyOperation extends AbsOperation {
33  
34  	public JsonPath mySourcePath;
35  
36  	public CopyOperation(JsonPath theTargetPath, JsonPath theSourcePath) {
37  		mySourcePath = theSourcePath;
38  		this.path = theTargetPath;
39  	}
40  
41  	@Override
42  	public String getOperationName() {
43  		return "copy";
44  	}
45  
46  	@Override
47  	public JsonElement apply(JsonElement original) {
48  		JsonElement result = duplicate(original);
49  
50  		JsonElement item = path.head().navigate(result);
51  		JsonElement data = mySourcePath.head().navigate(original);
52  
53  		if (item.isJsonObject()) {
54  			item.getAsJsonObject().add(path.tail(), data);
55  		} else if (item.isJsonArray()) {
56  
57  			JsonArray array = item.getAsJsonArray();
58  
59  			int index = (path.tail().equals("-")) ? array.size() : Integer.valueOf(path.tail());
60  
61  			List<JsonElement> temp = new ArrayList<JsonElement>();
62  
63  			Iterator<JsonElement> iter = array.iterator();
64  			while (iter.hasNext()) {
65  				JsonElement stuff = iter.next();
66  				iter.remove();
67  				temp.add(stuff);
68  			}
69  
70  			temp.add(index, data);
71  
72  			for (JsonElement stuff : temp) {
73  				array.add(stuff);
74  			}
75  
76  		}
77  
78  		return result;
79  	}
80  
81  }