View Javadoc
1   package com.atlassian.plugin.refimpl;
2   
3   import com.atlassian.plugin.manager.DefaultPluginPersistentState;
4   import com.atlassian.plugin.manager.PluginPersistentState;
5   import com.atlassian.plugin.manager.PluginPersistentStateStore;
6   import org.apache.commons.io.IOUtils;
7   import org.slf4j.Logger;
8   import org.slf4j.LoggerFactory;
9   
10  import java.io.File;
11  import java.io.FileInputStream;
12  import java.io.FileOutputStream;
13  import java.io.IOException;
14  import java.util.HashMap;
15  import java.util.Map;
16  import java.util.Map.Entry;
17  import java.util.Properties;
18  import java.util.Set;
19  
20  public class DefaultPluginPersistentStateStore implements PluginPersistentStateStore {
21      private static final Logger log = LoggerFactory.getLogger(DefaultPluginPersistentStateStore.class);
22  
23      private File file;
24  
25      public DefaultPluginPersistentStateStore(final File directory) {
26          try {
27              file = new File(directory.getParentFile(), "plugins.state");
28              if (!file.exists()) {
29                  file.createNewFile();
30              }
31          } catch (final IOException e) {
32              log.error("Error creating plugins.state file. " + e, e);
33          }
34      }
35  
36      public PluginPersistentState load() {
37          final Map<String, Boolean> state = new HashMap<String, Boolean>();
38          FileInputStream inputStream = null;
39          try {
40              final Properties properties = new Properties();
41              inputStream = new FileInputStream(file);
42              properties.load(inputStream);
43              final Set<Object> keys = properties.keySet();
44              for (final Object key : keys) {
45                  state.put(String.valueOf(key), Boolean.valueOf(String.valueOf(properties.get(key))));
46              }
47          } catch (final IOException e) {
48              log.error("Error creating/reading plugins.state file. " + e, e);
49          } finally {
50              IOUtils.closeQuietly(inputStream);
51          }
52          return new DefaultPluginPersistentState(state);
53      }
54  
55      public void save(final PluginPersistentState state) {
56          final Properties properties = new Properties();
57          final Set<Entry<String, Boolean>> entrySet = state.getMap().entrySet();
58          for (final Entry<String, Boolean> entry : entrySet) {
59              properties.put(entry.getKey(), String.valueOf(entry.getValue()));
60          }
61          FileOutputStream outputStream = null;
62          try {
63              outputStream = new FileOutputStream(file);
64              properties.store(outputStream, "Saving plugins state");
65          } catch (final IOException e) {
66              log.error("Error saving to plugins.state file. " + e, e);
67          } finally {
68              IOUtils.closeQuietly(outputStream);
69          }
70      }
71  }