1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.platform.helpers.exceptions;
18 
19 import java.io.PrintWriter;
20 import java.io.StringWriter;
21 import java.util.HashMap;
22 import java.util.Map;
23 import java.util.stream.Collectors;
24 
25 /**
26  * Custom exception that holds exceptions from multiple classes and print them all out upon
27  * throwing.
28  */
29 public class MappedMultiException extends TestHelperException {
30     private final Map<Object, Throwable> mThrowables = new HashMap<>();
31     private final String mMessage;
32 
MappedMultiException(String message, Map<Object, Throwable> throwables)33     public MappedMultiException(String message, Map<Object, Throwable> throwables) {
34         super(message);
35         mThrowables.putAll(throwables);
36         mMessage = message;
37     }
38 
39     /** Print a stack trace from a Throwable to a string. */
stackTraceToString(Throwable t)40     private String stackTraceToString(Throwable t) {
41         StringWriter stringWriter = new StringWriter();
42         t.printStackTrace(new PrintWriter(stringWriter));
43         // Indent the output by one level.
44         return stringWriter.toString().replaceAll("(?m)^", "\t");
45     }
46 
47     /** Print an entry in the exception map to a string. */
entryToString(Map.Entry<Object, Throwable> entry)48     private String entryToString(Map.Entry<Object, Throwable> entry) {
49         return String.format("%s:\n%s", entry.getKey(), stackTraceToString(entry.getValue()));
50     }
51 
52     /** Print out all the exceptions in this exception in its message, if any. */
53     @Override
getMessage()54     public String getMessage() {
55         if (mThrowables.isEmpty()) {
56             return mMessage;
57         }
58         return String.format(
59                 "%s\nExceptions and their sources: \n%s",
60                 mMessage,
61                 String.join(
62                         "\n,",
63                         mThrowables
64                                 .entrySet()
65                                 .stream()
66                                 .map(entry -> entryToString(entry))
67                                 .collect(Collectors.toList())
68                                 .toArray(new String[mThrowables.size()])));
69     }
70 }
71