001    /*
002     * Copyright (c) 2011, Cloudera, Inc. All Rights Reserved.
003     *
004     * Cloudera, Inc. licenses this file to you under the Apache License,
005     * Version 2.0 (the "License"). You may not use this file except in
006     * compliance with the License. You may obtain a copy of the License at
007     *
008     *     http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
011     * CONDITIONS OF ANY KIND, either express or implied. See the License for
012     * the specific language governing permissions and limitations under the
013     * License.
014     */
015    package com.cloudera.lib.lang;
016    
017    import com.cloudera.lib.util.Check;
018    
019    import java.util.concurrent.Callable;
020    
021    /**
022     * Adapter class that allows <code>Runnable</code>s and <code>Callable</code>s to
023     * be treated as the other.
024     */
025    public class RunnableCallable implements Callable<Void>, Runnable {
026      private Runnable runnable;
027      private Callable<?> callable;
028    
029      /**
030       * Constructor that takes a runnable.
031       *
032       * @param runnable runnable.
033       */
034      public RunnableCallable(Runnable runnable) {
035        this.runnable = Check.notNull(runnable, "runnable");
036      }
037    
038      /**
039       * Constructor that takes a callable.
040       * @param callable callable.
041       */
042      public RunnableCallable(Callable<?> callable) {
043        this.callable = Check.notNull(callable, "callable");
044      }
045    
046      /**
047       * Invokes the wrapped callable/runnable as a callable.
048       * @return void
049       * @throws Exception thrown by the wrapped callable/runnable invocation.
050       */
051      @Override
052      public Void call() throws Exception {
053        if (runnable != null) {
054          runnable.run();
055        }
056        else {
057          callable.call();
058        }
059        return null;
060      }
061    
062      /**
063       * Invokes the wrapped callable/runnable as a runnable.
064       * @return void
065       * @throws Exception thrown by the wrapped callable/runnable invocation.
066       */
067      @Override
068      public void run() {
069        if (runnable != null) {
070          runnable.run();
071        }
072        else {
073          try {
074            callable.call();
075          }
076          catch (Exception ex) {
077            throw new RuntimeException(ex);
078          }
079        }
080      }
081    
082      /**
083       * Returns the class name of the wrapper callable/runnable.
084       *
085       * @return  the class name of the wrapper callable/runnable.
086       */
087      public String toString() {
088        return (runnable != null) ? runnable.getClass().getSimpleName() : callable.getClass().getSimpleName();
089      }
090    }