| 1 | |
package org.webslinger.modules; |
| 2 | |
|
| 3 | |
import java.io.IOException; |
| 4 | |
import java.util.ArrayList; |
| 5 | |
import java.util.Collection; |
| 6 | |
import java.util.HashMap; |
| 7 | |
import java.util.concurrent.atomic.AtomicInteger; |
| 8 | |
import java.lang.ref.SoftReference; |
| 9 | |
|
| 10 | |
import org.apache.commons.vfs.FileObject; |
| 11 | |
|
| 12 | |
public abstract class AbstractWorkAreaFactory<T extends WorkArea> implements WorkAreaFactory<T> { |
| 13 | 22 | protected final HashMap<String, SoftReference<T>> workAreas = new HashMap<String, SoftReference<T>>(); |
| 14 | 22 | protected AtomicInteger tempCount = new AtomicInteger(); |
| 15 | |
protected final FileObject work; |
| 16 | |
|
| 17 | 22 | protected AbstractWorkAreaFactory(FileObject work) throws IOException { |
| 18 | 22 | this.work = work; |
| 19 | 22 | work.resolveFile("named").createFolder(); |
| 20 | 22 | work.resolveFile("temp").createFolder(); |
| 21 | 22 | } |
| 22 | |
|
| 23 | |
public T create() throws IOException { |
| 24 | 0 | return createWorkArea(null, "temp/" + tempCount.incrementAndGet()); |
| 25 | |
} |
| 26 | |
|
| 27 | |
protected abstract T createWorkArea(String name, String location) throws IOException; |
| 28 | |
|
| 29 | |
public T join(String name) throws IOException { |
| 30 | 0 | SoftReference<T> ref = workAreas.get(name); |
| 31 | 0 | if (ref != null) { |
| 32 | 0 | T workArea = ref.get(); |
| 33 | 0 | if (workArea != null) return workArea; |
| 34 | |
} |
| 35 | 0 | T workArea = createWorkArea(name, "named/" + name); |
| 36 | 0 | workAreas.put(name, new SoftReference<T>(workArea)); |
| 37 | 0 | return workArea; |
| 38 | |
} |
| 39 | |
|
| 40 | |
public Collection<? extends T> getWorkAreas() throws IOException { |
| 41 | 0 | ArrayList<T> workAreas = new ArrayList<T>(); |
| 42 | 0 | FileObject[] children = work.resolveFile("named").getChildren(); |
| 43 | 0 | if (children == null) return workAreas; |
| 44 | 0 | for (FileObject child: children) { |
| 45 | 0 | workAreas.add(join(child.getName().getBaseName())); |
| 46 | |
} |
| 47 | 0 | return workAreas; |
| 48 | |
} |
| 49 | |
} |