001package ca.uhn.fhir.rest.method;
002
003/*
004 * #%L
005 * HAPI FHIR - Core Library
006 * %%
007 * Copyright (C) 2014 - 2016 University Health Network
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 * 
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022import static org.apache.commons.lang3.StringUtils.isNotBlank;
023
024import java.lang.reflect.Method;
025import java.util.IdentityHashMap;
026import java.util.List;
027
028import org.hl7.fhir.instance.model.api.IBaseBundle;
029import org.hl7.fhir.instance.model.api.IBaseResource;
030
031import ca.uhn.fhir.context.ConfigurationException;
032import ca.uhn.fhir.context.FhirContext;
033import ca.uhn.fhir.model.api.Bundle;
034import ca.uhn.fhir.model.api.IResource;
035import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
036import ca.uhn.fhir.model.base.resource.BaseOperationOutcome;
037import ca.uhn.fhir.model.primitive.IdDt;
038import ca.uhn.fhir.model.valueset.BundleTypeEnum;
039import ca.uhn.fhir.rest.annotation.Transaction;
040import ca.uhn.fhir.rest.annotation.TransactionParam;
041import ca.uhn.fhir.rest.api.RequestTypeEnum;
042import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
043import ca.uhn.fhir.rest.client.BaseHttpClientInvocation;
044import ca.uhn.fhir.rest.param.TransactionParameter;
045import ca.uhn.fhir.rest.param.TransactionParameter.ParamStyle;
046import ca.uhn.fhir.rest.server.IBundleProvider;
047import ca.uhn.fhir.rest.server.IRestfulServer;
048import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
049import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
050
051public class TransactionMethodBinding extends BaseResourceReturningMethodBinding {
052
053        private int myTransactionParamIndex;
054        private ParamStyle myTransactionParamStyle;
055
056        public TransactionMethodBinding(Method theMethod, FhirContext theConetxt, Object theProvider) {
057                super(null, theMethod, theConetxt, theProvider);
058
059                myTransactionParamIndex = -1;
060                int index = 0;
061                for (IParameter next : getParameters()) {
062                        if (next instanceof TransactionParameter) {
063                                if (myTransactionParamIndex != -1) {
064                                        throw new ConfigurationException("Method '" + theMethod.getName() + "' in type " + theMethod.getDeclaringClass().getCanonicalName() + " has multiple parameters annotated with the @" + TransactionParam.class + " annotation, exactly one is required for @" + Transaction.class
065                                                        + " methods");
066                                }
067                                myTransactionParamIndex = index;
068                                myTransactionParamStyle = ((TransactionParameter) next).getParamStyle();
069                        }
070                        index++;
071                }
072
073                if (myTransactionParamIndex == -1) {
074                        throw new ConfigurationException("Method '" + theMethod.getName() + "' in type " + theMethod.getDeclaringClass().getCanonicalName() + " does not have a parameter annotated with the @" + TransactionParam.class + " annotation");
075                }
076        }
077
078        @Override
079        public RestOperationTypeEnum getRestOperationType() {
080                return RestOperationTypeEnum.TRANSACTION;
081        }
082
083        @Override
084        protected BundleTypeEnum getResponseBundleType() {
085                return BundleTypeEnum.TRANSACTION_RESPONSE;
086        }
087
088        @Override
089        public ReturnTypeEnum getReturnType() {
090                return ReturnTypeEnum.BUNDLE;
091        }
092
093        @Override
094        public boolean incomingServerRequestMatchesMethod(RequestDetails theRequest) {
095                if (theRequest.getRequestType() != RequestTypeEnum.POST) {
096                        return false;
097                }
098                if (isNotBlank(theRequest.getOperation())) {
099                        return false;
100                }
101                if (isNotBlank(theRequest.getResourceName())) {
102                        return false;
103                }
104                return true;
105        }
106
107        @Override
108        public BaseHttpClientInvocation invokeClient(Object[] theArgs) throws InternalErrorException {
109                FhirContext context = getContext();
110                if (theArgs[myTransactionParamIndex] instanceof Bundle) {
111                        Bundle bundle = (Bundle) theArgs[myTransactionParamIndex];
112                        return createTransactionInvocation(bundle, context);
113                } else {
114                        @SuppressWarnings("unchecked")
115                        List<IBaseResource> resources = (List<IBaseResource>) theArgs[myTransactionParamIndex];
116                        return createTransactionInvocation(resources, context);
117                }
118        }
119
120        @SuppressWarnings("unchecked")
121        @Override
122        public Object invokeServer(IRestfulServer theServer, RequestDetails theRequest, Object[] theMethodParams) throws InvalidRequestException, InternalErrorException {
123
124                /*
125                 * The design of HAPI's transaction method for DSTU1 support assumed that a transaction was just an update on a
126                 * bunch of resources (because that's what it was), but in DSTU2 transaction has become much more broad, so we
127                 * no longer hold the user's hand much here.
128                 */
129                if (myTransactionParamStyle == ParamStyle.RESOURCE_BUNDLE) {
130                        // This is the DSTU2 style
131                        Object response = invokeServerMethod(theServer, theRequest, theMethodParams);
132                        return response;
133                }
134
135                // Grab the IDs of all of the resources in the transaction
136                List<IResource> resources;
137                if (theMethodParams[myTransactionParamIndex] instanceof Bundle) {
138                        resources = ((Bundle) theMethodParams[myTransactionParamIndex]).toListOfResources();
139                } else {
140                        resources = (List<IResource>) theMethodParams[myTransactionParamIndex];
141                }
142
143                IdentityHashMap<IResource, IdDt> oldIds = new IdentityHashMap<IResource, IdDt>();
144                for (IResource next : resources) {
145                        oldIds.put(next, next.getId());
146                }
147
148                // Call the server implementation method
149                Object response = invokeServerMethod(theServer, theRequest, theMethodParams);
150                IBundleProvider retVal = toResourceList(response);
151
152                /*
153                 * int offset = 0; if (retVal.size() != resources.size()) { if (retVal.size() > 0 && retVal.getResources(0,
154                 * 1).get(0) instanceof OperationOutcome) { offset = 1; } else { throw new
155                 * InternalErrorException("Transaction bundle contained " + resources.size() +
156                 * " entries, but server method response contained " + retVal.size() + " entries (must be the same)"); } }
157                 */
158
159                List<IBaseResource> retResources = retVal.getResources(0, retVal.size());
160                for (int i = 0; i < retResources.size(); i++) {
161                        IdDt oldId = oldIds.get(retResources.get(i));
162                        IBaseResource newRes = retResources.get(i);
163                        if (newRes.getIdElement() == null || newRes.getIdElement().isEmpty()) {
164                                if (!(newRes instanceof BaseOperationOutcome)) {
165                                        throw new InternalErrorException("Transaction method returned resource at index " + i + " with no id specified - IResource#setId(IdDt)");
166                                }
167                        }
168
169                        if (oldId != null && !oldId.isEmpty()) {
170                                if (!oldId.equals(newRes.getIdElement()) && newRes instanceof IResource) {
171                                        ((IResource)newRes).getResourceMetadata().put(ResourceMetadataKeyEnum.PREVIOUS_ID, oldId);
172                                }
173                        }
174                }
175
176                return retVal;
177        }
178
179        public static BaseHttpClientInvocation createTransactionInvocation(Bundle theBundle, FhirContext theContext) {
180                return new HttpPostClientInvocation(theContext, theBundle);
181        }
182
183        public static BaseHttpClientInvocation createTransactionInvocation(IBaseBundle theBundle, FhirContext theContext) {
184                return new HttpPostClientInvocation(theContext, theBundle);
185        }
186
187        public static BaseHttpClientInvocation createTransactionInvocation(List<? extends IBaseResource> theResources, FhirContext theContext) {
188                return new HttpPostClientInvocation(theContext, theResources, BundleTypeEnum.TRANSACTION);
189        }
190
191        public static BaseHttpClientInvocation createTransactionInvocation(String theRawBundle, FhirContext theContext) {
192                return new HttpPostClientInvocation(theContext, theRawBundle, true, "");
193        }
194
195}