1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.openehealth.ipf.platform.camel.core.util;
17
18 import org.apache.camel.Exchange;
19 import org.apache.camel.Expression;
20 import org.openehealth.ipf.commons.core.modules.api.ValidationException;
21 import org.openehealth.ipf.commons.core.modules.api.Validator;
22 import org.openehealth.ipf.platform.camel.core.xml.MarkupBuilder;
23
24
25
26
27
28
29 public class Expressions {
30
31
32
33
34
35
36
37 public static Expression headersExpression() {
38 return new Expression() {
39 @Override
40 public <T> T evaluate(Exchange exchange, Class<T> type) {
41 return type.cast(exchange.getIn().getHeaders());
42 }
43
44 @Override
45 public String toString() {
46 return "headers()";
47 }
48 };
49 }
50
51 public static Expression builderExpression() {
52 return new Expression() {
53 @Override
54 public <T> T evaluate(Exchange exchange, Class<T> type) {
55 return type.cast(MarkupBuilder.newInstance());
56 }
57
58 @Override
59 public String toString() {
60 return "headersAndBuilder()";
61 }
62 };
63 }
64
65 public static Expression headersAndBuilderExpression() {
66 return new Expression() {
67 @Override
68 public <T> T evaluate(Exchange exchange, Class<T> type) {
69 Object[] result = new Object[2];
70 result [0] = exchange.getIn().getHeaders();
71 result [1] = MarkupBuilder.newInstance();
72 return type.cast(result);
73 }
74
75 @Override
76 public String toString() {
77 return "headersAndBuilder()";
78 }
79 };
80 }
81
82 public static Expression exceptionObjectExpression() {
83 return new Expression() {
84 @Override
85 public <T> T evaluate(Exchange exchange, Class<T> type) {
86 return type.cast(exception(exchange));
87 }
88 };
89 }
90
91 public static Expression exceptionMessageExpression() {
92 return new Expression() {
93 @Override
94 public <T> T evaluate(Exchange exchange, Class<T> type) {
95 Throwable throwable = exception(exchange);
96 return type.cast(throwable == null ? null : throwable.getMessage());
97 }
98 };
99 }
100
101 public static <S, P> Expression validatorExpression(final Validator<S, P> validator, final P profile, final Class<? extends S> clazz) {
102 return new Expression() {
103 @Override
104 public <T> T evaluate(Exchange exchange, Class<T> type) {
105 try {
106 S body = exchange.getIn().getBody(clazz);
107 validator.validate(body, profile);
108 return type.cast(true);
109 } catch (ValidationException e) {
110 return type.cast(false);
111 }
112 }
113 };
114
115 }
116
117 private static Throwable exception(Exchange exchange) {
118 Throwable throwable = exchange.getException();
119 if (throwable != null) {
120 return throwable;
121 }
122 return (Throwable)exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
123 }
124
125 }