001package ca.uhn.fhir.rest.method;
002
003/*
004 * #%L
005 * HAPI FHIR - Core Library
006 * %%
007 * Copyright (C) 2014 - 2017 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.ResourceParameter;
045import ca.uhn.fhir.rest.param.TransactionParameter;
046import ca.uhn.fhir.rest.param.TransactionParameter.ParamStyle;
047import ca.uhn.fhir.rest.server.IBundleProvider;
048import ca.uhn.fhir.rest.server.IRestfulServer;
049import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
050import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
051import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor.ActionRequestDetails;
052
053public class TransactionMethodBinding extends BaseResourceReturningMethodBinding {
054
055        private int myTransactionParamIndex;
056        private ParamStyle myTransactionParamStyle;
057
058        public TransactionMethodBinding(Method theMethod, FhirContext theContext, Object theProvider) {
059                super(null, theMethod, theContext, theProvider);
060
061                myTransactionParamIndex = -1;
062                int index = 0;
063                for (IParameter next : getParameters()) {
064                        if (next instanceof TransactionParameter) {
065                                if (myTransactionParamIndex != -1) {
066                                        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
067                                                        + " methods");
068                                }
069                                myTransactionParamIndex = index;
070                                myTransactionParamStyle = ((TransactionParameter) next).getParamStyle();
071                        }
072                        index++;
073                }
074
075                if (myTransactionParamIndex == -1) {
076                        throw new ConfigurationException("Method '" + theMethod.getName() + "' in type " + theMethod.getDeclaringClass().getCanonicalName() + " does not have a parameter annotated with the @" + TransactionParam.class + " annotation");
077                }
078        }
079
080        @Override
081        public RestOperationTypeEnum getRestOperationType() {
082                return RestOperationTypeEnum.TRANSACTION;
083        }
084
085        @Override
086        protected BundleTypeEnum getResponseBundleType() {
087                return BundleTypeEnum.TRANSACTION_RESPONSE;
088        }
089
090        @Override
091        public ReturnTypeEnum getReturnType() {
092                return ReturnTypeEnum.BUNDLE;
093        }
094
095        @Override
096        public boolean incomingServerRequestMatchesMethod(RequestDetails theRequest) {
097                if (theRequest.getRequestType() != RequestTypeEnum.POST) {
098                        return false;
099                }
100                if (isNotBlank(theRequest.getOperation())) {
101                        return false;
102                }
103                if (isNotBlank(theRequest.getResourceName())) {
104                        return false;
105                }
106                return true;
107        }
108
109        @Override
110        public BaseHttpClientInvocation invokeClient(Object[] theArgs) throws InternalErrorException {
111                FhirContext context = getContext();
112                if (theArgs[myTransactionParamIndex] instanceof Bundle) {
113                        Bundle bundle = (Bundle) theArgs[myTransactionParamIndex];
114                        return createTransactionInvocation(bundle, context);
115                }
116                @SuppressWarnings("unchecked")
117                List<IBaseResource> resources = (List<IBaseResource>) theArgs[myTransactionParamIndex];
118                return createTransactionInvocation(resources, context);
119        }
120
121        @SuppressWarnings("unchecked")
122        @Override
123        public Object invokeServer(IRestfulServer<?> theServer, RequestDetails theRequest, Object[] theMethodParams) throws InvalidRequestException, InternalErrorException {
124
125                /*
126                 * The design of HAPI's transaction method for DSTU1 support assumed that a transaction was just an update on a
127                 * bunch of resources (because that's what it was), but in DSTU2 transaction has become much more broad, so we
128                 * no longer hold the user's hand much here.
129                 */
130                if (myTransactionParamStyle == ParamStyle.RESOURCE_BUNDLE) {
131                        // This is the DSTU2 style
132                        Object response = invokeServerMethod(theServer, theRequest, theMethodParams);
133                        return response;
134                }
135
136                // Grab the IDs of all of the resources in the transaction
137                List<IResource> resources;
138                if (theMethodParams[myTransactionParamIndex] instanceof Bundle) {
139                        resources = ((Bundle) theMethodParams[myTransactionParamIndex]).toListOfResources();
140                } else {
141                        resources = (List<IResource>) theMethodParams[myTransactionParamIndex];
142                }
143
144                IdentityHashMap<IResource, IdDt> oldIds = new IdentityHashMap<IResource, IdDt>();
145                for (IResource next : resources) {
146                        oldIds.put(next, next.getId());
147                }
148
149                // Call the server implementation method
150                Object response = invokeServerMethod(theServer, theRequest, theMethodParams);
151                IBundleProvider retVal = toResourceList(response);
152
153                /*
154                 * int offset = 0; if (retVal.size() != resources.size()) { if (retVal.size() > 0 && retVal.getResources(0,
155                 * 1).get(0) instanceof OperationOutcome) { offset = 1; } else { throw new
156                 * InternalErrorException("Transaction bundle contained " + resources.size() +
157                 * " entries, but server method response contained " + retVal.size() + " entries (must be the same)"); } }
158                 */
159
160                List<IBaseResource> retResources = retVal.getResources(0, retVal.size());
161                for (int i = 0; i < retResources.size(); i++) {
162                        IdDt oldId = oldIds.get(retResources.get(i));
163                        IBaseResource newRes = retResources.get(i);
164                        if (newRes.getIdElement() == null || newRes.getIdElement().isEmpty()) {
165                                if (!(newRes instanceof BaseOperationOutcome)) {
166                                        throw new InternalErrorException("Transaction method returned resource at index " + i + " with no id specified - IResource#setId(IdDt)");
167                                }
168                        }
169
170                        if (oldId != null && !oldId.isEmpty()) {
171                                if (!oldId.equals(newRes.getIdElement()) && newRes instanceof IResource) {
172                                        ((IResource)newRes).getResourceMetadata().put(ResourceMetadataKeyEnum.PREVIOUS_ID, oldId);
173                                }
174                        }
175                }
176
177                return retVal;
178        }
179
180        
181        @Override
182        protected void populateActionRequestDetailsForInterceptor(RequestDetails theRequestDetails, ActionRequestDetails theDetails, Object[] theMethodParams) {
183                super.populateActionRequestDetailsForInterceptor(theRequestDetails, theDetails, theMethodParams);
184                
185                /*
186                 * If the method has no parsed resource parameter, we parse here in order to have something for the interceptor.
187                 */
188                if (myTransactionParamIndex != -1) {
189                        theDetails.setResource((IBaseResource) theMethodParams[myTransactionParamIndex]);
190                } else {
191                        Class<? extends IBaseResource> resourceType = getContext().getResourceDefinition("Bundle").getImplementingClass();
192                        theDetails.setResource(ResourceParameter.parseResourceFromRequest(theRequestDetails, this, resourceType));
193                }
194
195        }
196
197        public static BaseHttpClientInvocation createTransactionInvocation(Bundle theBundle, FhirContext theContext) {
198                return new HttpPostClientInvocation(theContext, theBundle);
199        }
200
201        public static BaseHttpClientInvocation createTransactionInvocation(IBaseBundle theBundle, FhirContext theContext) {
202                return new HttpPostClientInvocation(theContext, theBundle);
203        }
204
205        public static BaseHttpClientInvocation createTransactionInvocation(List<? extends IBaseResource> theResources, FhirContext theContext) {
206                return new HttpPostClientInvocation(theContext, theResources, BundleTypeEnum.TRANSACTION);
207        }
208
209        public static BaseHttpClientInvocation createTransactionInvocation(String theRawBundle, FhirContext theContext) {
210                return new HttpPostClientInvocation(theContext, theRawBundle, true, "");
211        }
212
213}