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