01: /*
02: * $Id: MessageAttachmentsExpressionEvaluator.java 11297 2008-03-09 20:11:02Z rossmason $
03: * --------------------------------------------------------------------------------------
04: * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
05: *
06: * The software in this package is published under the terms of the CPAL v1.0
07: * license, a copy of which has been included with this distribution in the
08: * LICENSE.txt file.
09: */
10:
11: package org.mule.util.expression;
12:
13: import org.mule.api.transport.MessageAdapter;
14: import org.mule.config.i18n.CoreMessages;
15:
16: import java.util.HashMap;
17: import java.util.Map;
18: import java.util.StringTokenizer;
19: import java.util.List;
20: import java.util.ArrayList;
21:
22: /**
23: * Looks up the attachment(s) on the message using the expression given. The expression can contain a comma-separated list
24: * of header names to lookup. A {@link java.util.Map} of key value pairs is returned.
25: *
26: * @see MessageAttachmentsListExpressionEvaluator
27: * @see MessageAttachmentExpressionEvaluator
28: * @see ExpressionEvaluator
29: * @see ExpressionEvaluatorManager
30: */
31: public class MessageAttachmentsExpressionEvaluator implements
32: ExpressionEvaluator {
33: public static final String NAME = "attachments";
34: public static final String DELIM = ",";
35:
36: public Object evaluate(String expression, Object message) {
37: boolean required = false;
38:
39: //This is a bit of a hack to manage required headers
40: if (expression.endsWith("required")) {
41: required = true;
42: expression = expression.substring(0,
43: expression.length() - 8);
44: }
45:
46: if (message instanceof MessageAdapter) {
47: StringTokenizer tokenizer = new StringTokenizer(expression,
48: DELIM);
49: Map result = new HashMap(tokenizer.countTokens());
50: while (tokenizer.hasMoreTokens()) {
51: String s = tokenizer.nextToken();
52: s = s.trim();
53: Object val = ((MessageAdapter) message)
54: .getAttachment(s);
55: if (val != null) {
56: result.put(s, val);
57: } else if (required) {
58: throw new ExpressionRuntimeException(CoreMessages
59: .expressionEvaluatorReturnedNull(NAME,
60: expression));
61: }
62: }
63: if (result.size() == 0) {
64: return null;
65: } else {
66: return result;
67: }
68: }
69: return null;
70: }
71:
72: /**
73: * {@inheritDoc}
74: */
75: public String getName() {
76: return NAME;
77: }
78:
79: /**
80: * {@inheritDoc}
81: */
82: public void setName(String name) {
83: throw new UnsupportedOperationException("setName");
84: }
85: }
|