001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.io;
019
020import java.io.IOException;
021import java.util.ArrayList;
022import java.util.List;
023
024import org.apache.hadoop.classification.InterfaceAudience;
025import org.apache.hadoop.classification.InterfaceStability;
026
027/** Encapsulate a list of {@link IOException} into an {@link IOException} */
028@InterfaceAudience.Public
029@InterfaceStability.Stable
030public class MultipleIOException extends IOException {
031  /** Require by {@link java.io.Serializable} */
032  private static final long serialVersionUID = 1L;
033  
034  private final List<IOException> exceptions;
035  
036  /** Constructor is private, use {@link #createIOException(List)}. */
037  private MultipleIOException(List<IOException> exceptions) {
038    super(exceptions.size() + " exceptions " + exceptions);
039    this.exceptions = exceptions;
040  }
041
042  /** @return the underlying exceptions */
043  public List<IOException> getExceptions() {return exceptions;}
044
045  /** A convenient method to create an {@link IOException}. */
046  public static IOException createIOException(List<IOException> exceptions) {
047    if (exceptions == null || exceptions.isEmpty()) {
048      return null;
049    }
050    if (exceptions.size() == 1) {
051      return exceptions.get(0);
052    }
053    return new MultipleIOException(exceptions);
054  }
055
056  /**
057   * Build an {@link IOException} using {@link MultipleIOException}
058   * if there are more than one.
059   */
060  public static class Builder {
061    private List<IOException> exceptions;
062    
063    /** Add the given {@link Throwable} to the exception list. */
064    public void add(Throwable t) {
065      if (exceptions == null) {
066        exceptions = new ArrayList<>();
067      }
068      exceptions.add(t instanceof IOException? (IOException)t
069          : new IOException(t));
070    }
071
072    /**
073     * @return null if nothing is added to this builder;
074     *         otherwise, return an {@link IOException}
075     */
076    public IOException build() {
077      return createIOException(exceptions);
078    }
079  }
080}