summaryrefslogtreecommitdiff
path: root/src/plugins/certmanager/src/com/motorolamobility/studio/android/certmanager/core/SaveStateManager.java
blob: f482d4c501b80c82021591ff0972d4a1c983aa6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.motorolamobility.studio.android.certmanager.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;

import com.motorola.studio.android.common.log.StudioLogger;
import com.motorolamobility.studio.android.certmanager.CertificateManagerActivator;
import com.motorolamobility.studio.android.certmanager.views.KeystoreManagerView;

/**
 * Saves the state of the {@link KeystoreManagerView} with:
 * - the keystores mapped
 * - the last backup date from a keystore
 */
class SaveStateManager
{
    private static final String FILE_COMMENT = "-- Signing and keys view persistence --";

    private static final String STATE_FILENAME = "state.properties";

    private final File persistenceFile = new File(System.getProperty("user.home") + File.separator
            + "." + CertificateManagerActivator.PLUGIN_ID, STATE_FILENAME);

    private static final String KEYSTORE_TYPE = "keystore_type=";

    private static final String BACKUP_DATE = "backup_date=";

    protected class ViewStateEntry
    {
        private final File keystoreFile;

        private String keystoreType;

        private Date backupDate;

        public ViewStateEntry(File keystoreFile)
        {

            this.keystoreFile = keystoreFile;
        }

        public ViewStateEntry(File keystoreFile, String keystoreType)
        {

            this.keystoreFile = keystoreFile;
            this.keystoreType = keystoreType;
        }

        /**
         * @return the backupDate
         */
        public Date getBackupDate()
        {
            return backupDate;
        }

        /**
         * @param backupDate the backupDate to set
         */
        public void setBackupDate(Date backupDate)
        {
            this.backupDate = backupDate;
        }

        /**
         * @return the keystoreType
         */
        public String getKeystoreType()
        {
            return keystoreType;
        }

        /**
         * @param keystoreType the keystoreType to set
         */
        public void setKeystoreType(String keystoreType)
        {
            this.keystoreType = keystoreType;
        }

        /* (non-Javadoc)
         * @see java.lang.Object#toString()
         */
        @Override
        public String toString()
        {
            return "ViewStateEntry [keystoreFile=" + keystoreFile + ", keystoreType="
                    + keystoreType + ", backupDate=" + backupDate + "]";
        }

        /**
         * @return the keystoreFile
         */
        protected File getKeystoreFile()
        {
            return keystoreFile;
        }
    }

    private static SaveStateManager _instance;

    /**
     * This class is a singleton.
     * @return The unique instance of this class.
     * */
    public synchronized static SaveStateManager getInstance() throws IOException
    {
        if (_instance == null)
        {
            _instance = new SaveStateManager();
        }
        return _instance;
    }

    private SaveStateManager() throws IOException
    {
        //create folder if it does not exist
        if (!persistenceFile.getParentFile().exists())
        {
            persistenceFile.getParentFile().mkdirs();
        }
        if (!persistenceFile.exists())
        {
            //init file
            persistenceFile.createNewFile();
            store(new Properties());
        }
    }

    private String write(ViewStateEntry entry)
    {
        StringBuffer buffer = new StringBuffer();
        if (entry.getKeystoreType() != null)
        {
            buffer.append(KEYSTORE_TYPE + entry.getKeystoreType() + File.pathSeparator);
        }
        if (entry.getBackupDate() != null)
        {
            buffer.append(BACKUP_DATE + entry.getBackupDate().getTime());
        }
        return buffer.toString();
    }

    /**
     * List all mapped keystores.
     * @throws IOException If there are problems loading the persistence file.
     */
    public Set<File> getMappedKeystores() throws IOException
    {
        Set<File> mappedKeystores = new HashSet<File>();
        Properties properties = load();
        Enumeration<Object> enumeration = properties.keys();
        while (enumeration.hasMoreElements())
        {
            Object k = enumeration.nextElement();
            if (k instanceof String)
            {
                String key = (String) k;
                File keystoreFile = new File(key);
                mappedKeystores.add(keystoreFile);
            }
        }
        return mappedKeystores;
    }

    /**
     * Get a representation of the entry saved in the persistence.
     * @param keystoreFile The file that will have its state retrieved.     
     * @return 
     * @throws IOException If there are problems loading the persistence file.
     */
    public ViewStateEntry getEntry(File keystoreFile) throws IOException
    {
        Properties properties = load();
        Object v = properties.get(keystoreFile.getAbsolutePath());
        ViewStateEntry entry = null;
        if (v instanceof String)
        {
            String value = (String) v;
            StringTokenizer stringTokenizer = new StringTokenizer(value, File.pathSeparator);
            entry = new ViewStateEntry(keystoreFile);
            while (stringTokenizer.hasMoreTokens())
            {
                String token = stringTokenizer.nextToken();
                if (token.contains(KEYSTORE_TYPE))
                {
                    token = token.substring(KEYSTORE_TYPE.length());
                    entry.setKeystoreType(token);
                }
                else if (token.contains(BACKUP_DATE))
                {
                    token = token.substring(BACKUP_DATE.length());
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(Long.parseLong(token));
                    Date date = calendar.getTime();
                    entry.setBackupDate(date);
                }
            }
        }
        return entry;
    }

    /**
     * Check if a keystore is mapped on the persistence mechanism.
     * @param keystoreFile The keystore to be checked.
     * @return true if keystore mapped, false otherwise
     * @throws IOException If there are problems loading the persistence file.
     */
    public boolean isKeystoreMapped(File keystoreFile) throws IOException
    {
        Properties properties = load();
        return properties.containsKey(keystoreFile.getAbsolutePath());
    }

    /**
     * Adds (maps) a keystore.
     * @param keystoreFile The keystore to be added to the persistence mechanism.
     * @param keystoreType The type of the keystore.
     * @throws IOException If there are problems loading the persistence file.
     */
    public void addEntry(File keystoreFile, String keystoreType) throws IOException
    {
        ViewStateEntry stateEntry = new ViewStateEntry(keystoreFile, keystoreType);
        addEntry(keystoreFile, stateEntry);
    }

    private void addEntry(File keystoreFile, ViewStateEntry stateEntry) throws IOException
    {
        Properties prop = load();
        prop.setProperty(keystoreFile.getAbsolutePath(), write(stateEntry));
        store(prop);
    }

    /**
     * Removes a keystore from the persistence mechanism.
     * @param keystoreFile
     * @throws IOException
     */
    public void removeEntry(File keystoreFile) throws IOException
    {
        Properties properties = load();
        properties.remove(keystoreFile.getAbsolutePath());
        store(properties);
    }

    /**
     * Sets backup date from a keystore 
     * @param keystoreFile The keystore file.
     * @param backupDate The date of the backup.
     * @throws IOException If there are problems loading the persistence file.
     */
    public void setBackupDate(File keystoreFile, Date backupDate) throws IOException
    {
        ViewStateEntry entry = getEntry(keystoreFile);
        entry.setBackupDate(backupDate);
        addEntry(keystoreFile, entry);
    }

    private Properties load() throws IOException
    {
        FileInputStream in = null;
        Properties props = new Properties();

        try
        {
            in = new FileInputStream(persistenceFile);
            props.loadFromXML(in);
        }
        finally
        {
            if (in != null)
            {
                in.close();
            }
        }
        return props;
    }

    private void store(Properties prop) throws IOException
    {
        FileOutputStream out = null;

        try
        {
            out = new FileOutputStream(persistenceFile);
            prop.storeToXML(out, FILE_COMMENT);
        }
        finally
        {
            if (out != null)
            {
                try
                {
                    out.close();
                }
                catch (IOException e)
                {
                    StudioLogger.error("Could not close stream while saving properties. "
                            + e.getMessage());
                }
            }
        }
    }
}