View Javadoc
1   /*
2    * Copyright 2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.openehealth.ipf.platform.camel.hl7.adapter;
18  
19  import ca.uhn.hl7v2.HL7Exception;
20  import ca.uhn.hl7v2.HapiContext;
21  import ca.uhn.hl7v2.model.Message;
22  import ca.uhn.hl7v2.parser.GenericParser;
23  import ca.uhn.hl7v2.parser.Parser;
24  import org.apache.camel.Exchange;
25  import org.openehealth.ipf.platform.camel.core.adapter.ProcessorAdapter;
26  import org.openehealth.ipf.platform.camel.core.util.Exchanges;
27  
28  import static java.util.Objects.requireNonNull;
29  
30  /**
31   *
32   */
33  public abstract class HapiAdapter extends ProcessorAdapter {
34  
35      private static final Parser FALLBACK = new GenericParser();
36  
37      @Override
38      protected void doProcess(Exchange exchange, Object inputData, Object... inputParams) throws Exception {
39          Message message = toMessage(inputData, exchange);
40          Message result = doProcessMessage(
41                  message,
42                  exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class),
43                  inputParams);
44          Exchanges.prepareResult(exchange).setBody(result);
45      }
46  
47      protected abstract Message doProcessMessage(Message message, Throwable t, Object... inputParams);
48  
49      private static Message toMessage(Object inputData, Exchange exchange) throws HL7Exception {
50          Message message;
51          if (inputData instanceof Message) {
52              message = (Message)inputData;
53          } else if (inputData instanceof String) {
54              HapiContext context = exchange.getIn().getHeader("CamelHL7Context", HapiContext.class);
55              Parser parser = context != null ? context.getGenericParser() : FALLBACK;
56              message = parser.parse((String)inputData);
57          } else {
58              // try type conversion
59              message = exchange.getIn().getBody(Message.class);
60          }
61          requireNonNull(message, "Exchange does not contain or can be converted to the required 'ca.uhn.hl7v2.model.Message' type");
62          return message;
63      }
64  }