1 /*
2  * Copyright (C) 2016 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 package com.android.compatibility.common.tradefed.result;
17 
18 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
19 import com.android.tradefed.log.LogUtil.CLog;
20 import com.android.tradefed.util.FileUtil;
21 
22 import java.io.File;
23 import java.io.FileNotFoundException;
24 import java.io.IOException;
25 
26 
27 /**
28  * A helper class for setting and checking whether an invocation has failed.
29  */
30 public class InvocationFailureHandler {
31 
32     /**
33      * Determine whether the invocation for this session has previously failed.
34      *
35      * @param buildHelper the {@link CompatibilityBuildHelper} from which to retrieve invocation
36      * failure file
37      * @return if invocation has previously failed
38      */
hasFailed(final CompatibilityBuildHelper buildHelper)39     public static boolean hasFailed(final CompatibilityBuildHelper buildHelper) {
40         try {
41             File f = buildHelper.getInvocationFailureFile();
42             return (f.exists() && f.length() != 0);
43         } catch (FileNotFoundException e) {
44             CLog.e("Could not find invocation failure file for session %s",
45                 CompatibilityBuildHelper.getDirSuffix(buildHelper.getStartTime()));
46             CLog.e(e);
47             return false;
48         }
49     }
50 
51     /**
52      * Write the cause of invocation failure to the result's invocation failure file.
53      *
54      * @param buildHelper the {@link CompatibilityBuildHelper} from which to retrieve the
55      * invocation failure file
56      * @param cause the throwable responsible for invocation failure
57      */
setFailed(final CompatibilityBuildHelper buildHelper, Throwable cause)58     public static void setFailed(final CompatibilityBuildHelper buildHelper, Throwable cause) {
59         try {
60             File f = buildHelper.getInvocationFailureFile();
61             if (!f.exists()) {
62                 f.createNewFile();
63             }
64             // Append to previous failures to get them all.
65             FileUtil.writeToFile(cause.toString(), f, true);
66         } catch (IOException e) {
67             CLog.e("Exception while writing invocation failure file.");
68             CLog.e(e);
69         }
70     }
71 }
72