4 / 4 / 1
Регистрация: 10.09.2010
Сообщений: 53
|
|
|
|
Не обновляется мапа
26.12.2010, 00:32. Показов 1104. Ответов 2
[quote="D.o.c.t.o.r"]Когда ищу через метод findItemGroupByDesccription в моём FileDAO ArrayList, который идет возвращаемым параметром, содержит всего один элемент - последний добавленный, тобишь не добавляет в себя новых элементов, а замещает старый.Никак не пойму почему. Не обновляется Map'а в 75й строчке второго блока кода.
| Java | 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
| public class CMain
{
public static void main(String[] args)
{
Category category = new Category("Books");
ItemGroup ig1 = new ItemGroup("Garry Potter","Book of Garry Potter", BigDecimal.valueOf(100),category,true);
ItemGroup ig2 = new ItemGroup("Garry Potter 2","Book of Garry Potter",BigDecimal.valueOf(100),category,true);
ItemGroup ig3 = new ItemGroup("Garry Potter 3","Book of Garry Potter",BigDecimal.valueOf(100),category,true);
DAO dao = DAOFactory.getDAO();
try
{
dao.save(category);
dao.save(ig1);
dao.save(ig2);
dao.save(ig3);
}
catch(Exception e)
{
e.printStackTrace();
}
ArrayList al;
al = dao.findItemGroupByDescription("Book");
System.out.println(al);
}
} |
|
| Java | 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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
| package core.dao;
import core.entity.*;
import core.session.SessionManager;
import util.FileUtils;
import util.SerializationUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class FileDAO extends MemoryDAO
{
private static final String baseDir = "./files/";
private static final String userLiteral = "users/";
private static final String categoryLiteral = "categories/";
private static final String itemLiteral = "items/";
private static final String itemGroupLiteral = "itemGroups/";
private static final String orderLiteral = "orders/";
private static Map map;
private static final FileDAO INSTANCE = new FileDAO();
private FileDAO() {}
@Override
public void save(AbstractEntity entity) throws Exception
{
byte[] bytes;
SerializationUtil su = new SerializationUtil();
FileOutputStream fos = null;
String path;
// super.save(entity);
// Проверка для пользователя на уникальность login'а
if (entity instanceof User)
{
User user = findUserByLogin(((User) entity).getLogin());
if (user == null)
user = new User("temp@temp.temp","temp","temp");
if (SessionManager.getInstance().getCurrentUser() == null)
{
if (user.getLogin().equals(((User) entity).getLogin()))
throw new RuntimeException("User whith the same login already exist");
}
// Сохраняем в базу данных
map = getDatabaseMap(0);
if (map == null)
map = new HashMap();
map.put(((User) entity).getLogin(),entity.getId());
saveDatabaseMap(map,0);
}
if (entity instanceof Category)
{
map = getDatabaseMap(1);
if (map == null)
map = new HashMap();
map.put(((Category) entity).getName(),entity.getId());
saveDatabaseMap(map,1);
}
if (entity instanceof ItemGroup)
{
map = getDatabaseMap(2);
if (map == null)
map = new HashMap();
map.put(((ItemGroup) entity).getName(),entity.getId());
saveDatabaseMap(map,2);
// Почему-то мапа здесь не обновляется
map = getDatabaseMap(3);
if (map == null)
map = new HashMap();
map.put(((ItemGroup) entity).getDescription(),entity.getId());
saveDatabaseMap(map,3);
}
// Сохраняем сущность в файл
String literal = getEntityLiteral(entity.getClass());
path = baseDir + literal + entity.getId() + ".txt";
File file = new File(path);
file.createNewFile();
bytes = su.serialize(entity);
fos = new FileOutputStream(path);
fos.write(bytes);
fos.close();
}
@Override
public void remove(AbstractEntity entity)
{
super.remove(entity);
String literal = getEntityLiteral(entity.getClass());
String path = baseDir + literal + entity.getId() + ".txt";
File file = new File(path);
if (file.exists())
{
file.delete();
}
if (entity instanceof User)
{
map = getDatabaseMap(0);
map.remove(((User) entity).getLogin());
saveDatabaseMap(map,0);
}
if (entity instanceof Category)
{
map = getDatabaseMap(1);
map.remove(((Category) entity).getName());
saveDatabaseMap(map,1);
}
if (entity instanceof Item)
{
map = getDatabaseMap(2);
map.remove(((Item) entity).getItemGroup().getName());
saveDatabaseMap(map,2);
map = getDatabaseMap(3);
map.remove(((Item) entity).getItemGroup().getDescription());
saveDatabaseMap(map,3);
}
}
@Override
public AbstractEntity findById(long id, Class objectClass)
{
return loadAbstarctEntity(objectClass,id);
}
@Override
public User findUserByLogin(String login)
{
map = getDatabaseMap(0);
if (map != null)
{
Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry)it.next();
if (pairs.getKey().equals(login))
{
User user = (User) findById((Long) pairs.getValue(),User.class);
return user;
}
}
}
return null;
}
@Override
public ArrayList findItemGroupByName(String name)
{
ArrayList al = new ArrayList();
map = getDatabaseMap(2);
Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry)it.next();
String currentName = (String) pairs.getKey();
if (currentName.contains(name))
{
ItemGroup currentItemGroup = (ItemGroup) findById((Long)pairs.getValue(),ItemGroup.class);
al.add(currentItemGroup);
}
}
return al;
}
@Override
public ArrayList findItemGroupByDescription(String description)
{
ArrayList al = new ArrayList();
map = getDatabaseMap(3);
Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry)it.next();
String currentDescription = (String) pairs.getKey();
if (currentDescription.contains(description))
{
ItemGroup currentItemGroup = (ItemGroup) findById((Long)pairs.getValue(),ItemGroup.class);
al.add(currentItemGroup);
}
}
return al;
// map = getDatabaseMap(3);
// ArrayList al = new ArrayList();
// Iterator it = map.values().iterator();
// while (it.hasNext())
// {
// Item item = (Item) it.next();
// if (item.getItemGroup().getDescription().contains(description))
// {
// al.add(item);
// }
// }
// return al;
}
@Override
public Category findCategoryByName(String name)
{
map = getDatabaseMap(1);
Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry)it.next();
String currentName = (String) pairs.getKey();
if (currentName.equals(name))
{
Category category = (Category) pairs.getValue();
return category;
}
}
return null;
}
private <T extends AbstractEntity> T loadAbstarctEntity(Class<T> entityClass, long id)
{
SerializationUtil su = new SerializationUtil();
String literal = getEntityLiteral(entityClass);
File file = new File(baseDir + literal + id + ".txt");
byte[] bytes;
if (file.exists())
{
try
{
bytes = FileUtils.getBytesFromFile(file);
return (T) su.deserialize(bytes);
}
catch (Exception e)
{
e.printStackTrace();
}
}
return null;
}
private String getEntityLiteral(Class entityClass)
{
if (User.class.equals(entityClass))
{
return userLiteral;
}
if (Category.class.equals(entityClass))
{
return categoryLiteral;
}
if (Item.class.equals(entityClass))
{
return itemLiteral;
}
if (ItemGroup.class.equals(entityClass))
{
return itemGroupLiteral;
}
if (Order.class.equals(entityClass))
{
return orderLiteral;
}
return null;
}
private String getLiteralOfDatabase(int numberOfDatabase)
{
if (numberOfDatabase == 0)
{
return baseDir + "/database/" + "userLogin.txt";
}
if (numberOfDatabase == 1)
{
return baseDir + "/database/" + "categoryName.txt";
}
if (numberOfDatabase == 2)
{
return baseDir + "/database/" + "itemGroupName.txt";
}
if (numberOfDatabase == 3)
{
return baseDir + "/database/" + "itemGroupDescription.txt";
}
return null;
}
private Map getDatabaseMap(int numberOfDatabase)
{
String path = "";
File file;
byte[] bytes;
SerializationUtil su = new SerializationUtil();
path = getLiteralOfDatabase(numberOfDatabase);
file = new File(path);
if (file.exists())
{
try
{
bytes = FileUtils.getBytesFromFile(file);
map = (Map) su.deserialize(bytes);
return map;
}
catch (Exception e)
{
e.printStackTrace();
}
}
return null;
}
private void saveDatabaseMap(Map map, int numberOfDatabase)
{
String path;
SerializationUtil su = new SerializationUtil();
File file;
FileOutputStream fos = null;
ObjectOutputStream oos = null;
byte[] bytes;
path = getLiteralOfDatabase(numberOfDatabase);
file = new File(path);
if (!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
try
{
fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
oos.writeObject(map);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
fos.close();
oos.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
public static FileDAO getInstance()
{
return INSTANCE;
}
} |
|
0
|