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