1/*
2 * Copyright (C) 2011 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 */
16package com.squareup.okhttp.internal;
17
18import com.squareup.okhttp.internal.io.FileSystem;
19import java.io.File;
20import java.io.FileNotFoundException;
21import java.io.IOException;
22import java.util.LinkedHashSet;
23import java.util.Set;
24import okio.Buffer;
25import okio.ForwardingSink;
26import okio.Sink;
27import okio.Source;
28
29public final class FaultyFileSystem implements FileSystem {
30  private final FileSystem delegate;
31  private final Set<File> writeFaults = new LinkedHashSet<>();
32
33  public FaultyFileSystem(FileSystem delegate) {
34    this.delegate = delegate;
35  }
36
37  public void setFaulty(File file, boolean faulty) {
38    if (faulty) {
39      writeFaults.add(file);
40    } else {
41      writeFaults.remove(file);
42    }
43  }
44
45  @Override public Source source(File file) throws FileNotFoundException {
46    return delegate.source(file);
47  }
48
49  @Override public Sink sink(File file) throws FileNotFoundException {
50    return new FaultySink(delegate.sink(file), file);
51  }
52
53  @Override public Sink appendingSink(File file) throws FileNotFoundException {
54    return new FaultySink(delegate.appendingSink(file), file);
55  }
56
57  @Override public void delete(File file) throws IOException {
58    delegate.delete(file);
59  }
60
61  @Override public boolean exists(File file) throws IOException {
62    return delegate.exists(file);
63  }
64
65  @Override public long size(File file) {
66    return delegate.size(file);
67  }
68
69  @Override public void rename(File from, File to) throws IOException {
70    delegate.rename(from, to);
71  }
72
73  @Override public void deleteContents(File directory) throws IOException {
74    delegate.deleteContents(directory);
75  }
76
77  private class FaultySink extends ForwardingSink {
78    private final File file;
79
80    public FaultySink(Sink delegate, File file) {
81      super(delegate);
82      this.file = file;
83    }
84
85    @Override public void write(Buffer source, long byteCount) throws IOException {
86      if (writeFaults.contains(file)) throw new IOException("boom!");
87      super.write(source, byteCount);
88    }
89  }
90}
91