001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.servicemix.bean.support;
018
019 import java.util.concurrent.ExecutionException;
020 import java.util.concurrent.Future;
021 import java.util.concurrent.TimeUnit;
022
023 import javax.jbi.messaging.ExchangeStatus;
024 import javax.jbi.messaging.MessageExchange;
025 import javax.jbi.messaging.NormalizedMessage;
026
027 import org.apache.servicemix.jbi.exception.FaultException;
028
029 public class Holder implements Future<NormalizedMessage> {
030
031 private MessageExchange object;
032 private boolean cancel;
033
034 public synchronized NormalizedMessage get() throws InterruptedException, ExecutionException {
035 if (object == null) {
036 wait();
037 }
038 return extract(object);
039 }
040 public synchronized NormalizedMessage get(long timeout, TimeUnit unit)
041 throws InterruptedException, ExecutionException {
042 if (object == null) {
043 wait(unit.toMillis(timeout));
044 }
045 return extract(object);
046 }
047 public synchronized void set(MessageExchange t) {
048 object = t;
049 notifyAll();
050 }
051 public boolean cancel(boolean mayInterruptIfRunning) {
052 cancel = true;
053 return false;
054 }
055 public boolean isCancelled() {
056 return cancel;
057 }
058 public boolean isDone() {
059 return object != null;
060 }
061 protected NormalizedMessage extract(MessageExchange me) throws ExecutionException {
062 if (me.getStatus() == ExchangeStatus.ERROR) {
063 throw new ExecutionException(me.getError());
064 } else if (me.getFault() != null) {
065 throw new ExecutionException(new FaultException("Fault occured", me, me.getFault()));
066 } else {
067 return me.getMessage("out");
068 }
069 }
070 }