View Javadoc
1   package ca.uhn.fhir.jpa.util.xmlpatch;
2   
3   import java.io.*;
4   
5   import org.hl7.fhir.instance.model.api.IBaseResource;
6   
7   import com.github.dnault.xmlpatch.Patcher;
8   
9   import ca.uhn.fhir.context.FhirContext;
10  
11  /*
12   * #%L
13   * HAPI FHIR JPA Server
14   * %%
15   * Copyright (C) 2014 - 2018 University Health Network
16   * %%
17   * Licensed under the Apache License, Version 2.0 (the "License");
18   * you may not use this file except in compliance with the License.
19   * You may obtain a copy of the License at
20   * 
21   *      http://www.apache.org/licenses/LICENSE-2.0
22   * 
23   * Unless required by applicable law or agreed to in writing, software
24   * distributed under the License is distributed on an "AS IS" BASIS,
25   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
26   * See the License for the specific language governing permissions and
27   * limitations under the License.
28   * #L%
29   */
30  
31  import ca.uhn.fhir.rest.api.Constants;
32  import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
33  
34  public class XmlPatchUtils {
35  
36  	public static <T extends IBaseResource> T apply(FhirContext theCtx, T theResourceToUpdate, String thePatchBody) {
37  		
38  		@SuppressWarnings("unchecked")
39  		Class<T> clazz = (Class<T>) theResourceToUpdate.getClass();
40  		
41  		String inputResource = theCtx.newXmlParser().encodeResourceToString(theResourceToUpdate);
42  		
43  		ByteArrayOutputStream result = new ByteArrayOutputStream();
44  		try {
45  			Patcher.patch(new ByteArrayInputStream(inputResource.getBytes(Constants.CHARSET_UTF8)), new ByteArrayInputStream(thePatchBody.getBytes(Constants.CHARSET_UTF8)), result);
46  		} catch (IOException e) {
47  			throw new InternalErrorException(e);
48  		}
49  		
50  		String resultString = new String(result.toByteArray(), Constants.CHARSET_UTF8);
51  		T retVal = theCtx.newXmlParser().parseResource(clazz, resultString);
52  		
53  		return retVal;
54  	}
55  
56  	
57  }