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