aac34eb34d40347dd199b02479a582d166631d23
[pub/Android/ownCloud.git] / src / com / owncloud / android / utils / RecursiveFileObserver.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.utils;
20
21 import java.io.File;
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.Stack;
25
26 import android.os.FileObserver;
27
28 public class RecursiveFileObserver extends FileObserver {
29
30 public static int CHANGES_ONLY = CLOSE_WRITE | MOVE_SELF | MOVED_FROM;
31
32 List<SingleFileObserver> mObservers;
33 String mPath;
34 int mMask;
35
36 public RecursiveFileObserver(String path) {
37 this(path, ALL_EVENTS);
38 }
39
40 public RecursiveFileObserver(String path, int mask) {
41 super(path, mask);
42 mPath = path;
43 mMask = mask;
44 }
45
46 @Override
47 public void startWatching() {
48 if (mObservers != null) return;
49 mObservers = new ArrayList<SingleFileObserver>();
50 Stack<String> stack = new Stack<String>();
51 stack.push(mPath);
52
53 while (!stack.empty()) {
54 String parent = stack.pop();
55 mObservers.add(new SingleFileObserver(parent, mMask));
56 File path = new File(parent);
57 File[] files = path.listFiles();
58 if (files == null) continue;
59 for (int i = 0; i < files.length; ++i) {
60 if (files[i].isDirectory() && !files[i].getName().equals(".")
61 && !files[i].getName().equals("..")) {
62 stack.push(files[i].getPath());
63 }
64 }
65 }
66 for (int i = 0; i < mObservers.size(); i++)
67 mObservers.get(i).startWatching();
68 }
69
70 @Override
71 public void stopWatching() {
72 if (mObservers == null) return;
73
74 for (int i = 0; i < mObservers.size(); ++i)
75 mObservers.get(i).stopWatching();
76
77 mObservers.clear();
78 mObservers = null;
79 }
80
81 @Override
82 public void onEvent(int event, String path) {
83
84 }
85
86 private class SingleFileObserver extends FileObserver {
87 private String mPath;
88
89 public SingleFileObserver(String path, int mask) {
90 super(path, mask);
91 mPath = path;
92 }
93
94 @Override
95 public void onEvent(int event, String path) {
96 String newPath = mPath + "/" + path;
97 RecursiveFileObserver.this.onEvent(event, newPath);
98 }
99
100 }
101 }