1 /*
2  * aTunes
3  * Copyright (C) Alex Aranda, Sylvain Gaudard and contributors
4  *
5  * See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors
6  *
7  * http://www.atunes.org
8  * http://sourceforge.net/projects/atunes
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  */
20 
21 package net.sourceforge.atunes.kernel;
22 
23 import java.util.concurrent.CountDownLatch;
24 
25 import net.sourceforge.atunes.model.IBeanFactory;
26 import net.sourceforge.atunes.model.IStateService;
27 import net.sourceforge.atunes.utils.Logger;
28 
29 /**
30  * Abstract task to retrieve state
31  *
32  * @author alex
33  *
34  */
35 public abstract class AbstractStateRetrieveTask implements Runnable {
36 
37 	private IStateService stateService;
38 
39 	private IBeanFactory beanFactory;
40 
41 	private final CountDownLatch latch = new CountDownLatch(1);
42 
43 	/**
44 	 * @param stateService
45 	 */
setStateService(final IStateService stateService)46 	public final void setStateService(final IStateService stateService) {
47 		this.stateService = stateService;
48 	}
49 
50 	/**
51 	 * @param beanFactory
52 	 */
setBeanFactory(final IBeanFactory beanFactory)53 	public final void setBeanFactory(final IBeanFactory beanFactory) {
54 		this.beanFactory = beanFactory;
55 	}
56 
57 	@Override
run()58 	public final void run() {
59 		retrieveData(this.stateService, this.beanFactory);
60 		this.latch.countDown();
61 	}
62 
63 	/**
64 	 * Runnable called to set data retrieved
65 	 *
66 	 * @return
67 	 */
setData()68 	public final Runnable setData() {
69 		return new Runnable() {
70 			@Override
71 			public void run() {
72 				taskFinished();
73 				setData(AbstractStateRetrieveTask.this.beanFactory);
74 			}
75 		};
76 	}
77 
78 	/**
79 	 * Retrieves data
80 	 *
81 	 * @param stateService
82 	 * @param beanFactory
83 	 */
84 	public abstract void retrieveData(IStateService stateService,
85 			IBeanFactory beanFactory);
86 
87 	/**
88 	 * Loads retrieved data
89 	 *
90 	 * @param beanFactory
91 	 *
92 	 * @return runnable task
93 	 */
94 	public abstract void setData(IBeanFactory beanFactory);
95 
96 	/**
97 	 * Waits until task finishes
98 	 */
99 	private final void taskFinished() {
100 		try {
101 			this.latch.await();
102 		} catch (InterruptedException e) {
103 			Logger.error(e);
104 		}
105 	}
106 }
107