1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package pl.edu.agh.cast.backward.resources;
19
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.TreeMap;
24 import java.util.Map.Entry;
25
26 import org.apache.log4j.Logger;
27 import org.eclipse.core.resources.IProject;
28
29 import pl.edu.agh.cast.Activator;
30 import pl.edu.agh.cast.model.base.IModel;
31 import pl.edu.agh.cast.model.base.Model;
32 import pl.edu.agh.cast.model.mapper.Mapper;
33 import pl.edu.agh.cast.project.ProjectUtil;
34
35
36
37
38
39
40 public final class ProjectStore {
41
42 private static ProjectStore instance = new ProjectStore();
43
44 private static Logger log = Activator.getLogger();
45
46
47
48
49 private Map<IProject, IModel> projectToModel = new HashMap<IProject, IModel>();
50
51 private ProjectStore() {
52 }
53
54
55
56
57
58
59 public static ProjectStore getInstance() {
60 return instance;
61 }
62
63
64
65
66
67
68
69
70 public boolean isInitialized(IProject project) {
71 return projectToModel.containsKey(project);
72 }
73
74
75
76
77
78
79
80
81
82
83
84
85
86 @SuppressWarnings("unchecked")
87 public void init(IProject project) {
88 IModel model = null;
89 String newId = null;
90 TreeMap<String, Object> conditions = new TreeMap<String, Object>();
91 try {
92 String id = ProjectUtil.getProperty(project, ProjectUtil.PROJECT_ID_PROPERTY);
93 if (id == null) {
94 newId = ProjectUtil.getInstance().generateProjectId();
95 id = newId;
96 }
97
98 conditions.put("getName", id);
99 List<Model> models = Mapper.getInstance().find(Model.class, null, conditions, project);
100
101 if (models.isEmpty()) {
102 model = createNewModel(id, project);
103 } else {
104 if (models.size() == 1) {
105 model = models.get(0);
106 } else {
107 throw new RuntimeException("Too many models with id " + id);
108 }
109 }
110 } catch (Exception ex) {
111 log.error("Failed to load/save project model. Using default.", ex);
112 model = new Model(ProjectUtil.getInstance().generateProjectId());
113 } finally {
114 projectToModel.put(project, model);
115
116 if (newId != null) {
117 ProjectUtil.setProperty(project, ProjectUtil.PROJECT_ID_PROPERTY, newId);
118 }
119 }
120 }
121
122
123
124
125
126
127
128
129 private IModel createNewModel(String id, IProject project) {
130 IModel model = new Model(id);
131 Mapper.getInstance().save(model, project);
132 return model;
133 }
134
135
136
137
138
139
140
141
142 public IModel getModel(IProject project) {
143 if (!isInitialized(project)) {
144 init(project);
145 }
146 return projectToModel.get(project);
147 }
148
149
150
151
152
153
154
155
156 public IProject getProject(IModel model) {
157 for (Entry<IProject, IModel> entry : projectToModel.entrySet()) {
158 if (entry.getValue().equals(model)) {
159 return entry.getKey();
160 }
161 }
162 return null;
163 }
164
165
166
167
168
169
170
171 public void remove(IProject project) {
172 if (isInitialized(project)) {
173 projectToModel.remove(project);
174 }
175 }
176 }