001/* 002 * Copyright 2015-2024 the original author or authors 003 * 004 * This software is licensed under the Apache License, Version 2.0, 005 * the GNU Lesser General Public License version 2 or later ("LGPL") 006 * and the WTFPL. 007 * You may choose either license to govern your use of this software only 008 * upon the condition that you accept all of the terms of either 009 * the Apache License 2.0, the LGPL 2.1+ or the WTFPL. 010 */ 011package org.minidns.util; 012 013import java.io.IOException; 014import java.util.Collection; 015import java.util.Collections; 016import java.util.Iterator; 017import java.util.List; 018 019public final class MultipleIoException extends IOException { 020 021 /** 022 * 023 */ 024 private static final long serialVersionUID = -5932211337552319515L; 025 026 private final List<IOException> ioExceptions; 027 028 private MultipleIoException(List<? extends IOException> ioExceptions) { 029 super(getMessage(ioExceptions)); 030 assert !ioExceptions.isEmpty(); 031 this.ioExceptions = Collections.unmodifiableList(ioExceptions); 032 } 033 034 public List<IOException> getExceptions() { 035 return ioExceptions; 036 } 037 038 private static String getMessage(Collection<? extends Exception> exceptions) { 039 StringBuilder sb = new StringBuilder(); 040 Iterator<? extends Exception> it = exceptions.iterator(); 041 while (it.hasNext()) { 042 sb.append(it.next().getMessage()); 043 if (it.hasNext()) { 044 sb.append(", "); 045 } 046 } 047 return sb.toString(); 048 } 049 050 public static void throwIfRequired(List<? extends IOException> ioExceptions) throws IOException { 051 if (ioExceptions == null || ioExceptions.isEmpty()) { 052 return; 053 } 054 if (ioExceptions.size() == 1) { 055 throw ioExceptions.get(0); 056 } 057 throw new MultipleIoException(ioExceptions); 058 } 059 060 public static IOException toIOException(List<? extends IOException> ioExceptions) { 061 int size = ioExceptions.size(); 062 if (size == 1) { 063 return ioExceptions.get(0); 064 } else if (size > 1) { 065 return new MultipleIoException(ioExceptions); 066 } 067 return null; 068 } 069}