001package ca.uhn.fhir.jpa.util.xmlpatch;
002
003import ca.uhn.fhir.context.FhirContext;
004import ca.uhn.fhir.rest.api.Constants;
005import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
006import com.github.dnault.xmlpatch.Patcher;
007import org.hl7.fhir.instance.model.api.IBaseResource;
008
009import java.io.ByteArrayInputStream;
010import java.io.ByteArrayOutputStream;
011import java.io.IOException;
012
013/*
014 * #%L
015 * HAPI FHIR JPA Server
016 * %%
017 * Copyright (C) 2014 - 2021 Smile CDR, Inc.
018 * %%
019 * Licensed under the Apache License, Version 2.0 (the "License");
020 * you may not use this file except in compliance with the License.
021 * You may obtain a copy of the License at
022 *
023 *      http://www.apache.org/licenses/LICENSE-2.0
024 *
025 * Unless required by applicable law or agreed to in writing, software
026 * distributed under the License is distributed on an "AS IS" BASIS,
027 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
028 * See the License for the specific language governing permissions and
029 * limitations under the License.
030 * #L%
031 */
032
033public class XmlPatchUtils {
034
035        public static <T extends IBaseResource> T apply(FhirContext theCtx, T theResourceToUpdate, String thePatchBody) {
036                
037                @SuppressWarnings("unchecked")
038                Class<T> clazz = (Class<T>) theResourceToUpdate.getClass();
039                
040                String inputResource = theCtx.newXmlParser().encodeResourceToString(theResourceToUpdate);
041                
042                ByteArrayOutputStream result = new ByteArrayOutputStream();
043                try {
044                        Patcher.patch(new ByteArrayInputStream(inputResource.getBytes(Constants.CHARSET_UTF8)), new ByteArrayInputStream(thePatchBody.getBytes(Constants.CHARSET_UTF8)), result);
045                } catch (IOException e) {
046                        throw new InternalErrorException(e);
047                }
048                
049                String resultString = new String(result.toByteArray(), Constants.CHARSET_UTF8);
050                T retVal = theCtx.newXmlParser().parseResource(clazz, resultString);
051                
052                return retVal;
053        }
054
055        
056}