BrightSide Workbench Full Report + Source Code
CookieManager.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2020 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 package org.turro.elephant.cookies;
20 
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.util.Properties;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27 import org.turro.elephant.context.ElephantContext;
28 import org.turro.file.FileWatch;
29 
34 public class CookieManager extends Properties {
35 
36  /* Cookies' context */
37 
38  private static final String cookieFile = "/WEB-INF/elephant/conf/cookie-context.properties";
39 
40  private static CookieManager _cookies;
41  private static long _lastLoad;
42 
43  public static CookieManager load() {
44  boolean exists = FileWatch.exists(ElephantContext.getRealPath(cookieFile));
45  if(_cookies == null || FileWatch.isNewer(ElephantContext.getRealPath(cookieFile), _lastLoad) || !exists) {
46  if(exists) {
47  try(FileInputStream fis = new FileInputStream(ElephantContext.getRealPath(cookieFile))) {
48  _cookies = new CookieManager();
49  _cookies.load(fis);
50  } catch (IOException ex) {
51  Logger.getLogger(CookieManager.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
52  }
53  } else {
54  _cookies = new CookieManager();
55  }
56  _lastLoad = FileWatch.getTime(ElephantContext.getRealPath(cookieFile));
57  }
58  return _cookies;
59  }
60 
61  private static void store() {
62  try(FileOutputStream fos = new FileOutputStream(ElephantContext.getRealPath(cookieFile))) {
63  _cookies.store(fos, null);
64  } catch (IOException ex) {
65  Logger.getLogger(CookieManager.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
66  }
67  }
68 
69 }