0
|
1 package nabble.model;
|
|
2
|
|
3 import fschmidt.db.DbDatabase;
|
|
4 import fschmidt.db.DbNull;
|
|
5 import fschmidt.db.DbObjectFactory;
|
|
6 import fschmidt.db.DbRecord;
|
|
7 import fschmidt.db.DbTable;
|
|
8 import fschmidt.db.DbUtils;
|
|
9 import fschmidt.db.Listener;
|
|
10 import fschmidt.db.ListenerList;
|
|
11 import fschmidt.db.LongKey;
|
|
12 import fschmidt.html.Html;
|
|
13 import fschmidt.util.java.Computable;
|
|
14 import fschmidt.util.java.Filter;
|
|
15 import fschmidt.util.java.HtmlUtils;
|
|
16 import fschmidt.util.java.Memoizer;
|
|
17 import fschmidt.util.java.ObjectUtils;
|
|
18 import fschmidt.util.java.SimpleCache;
|
|
19 import nabble.model.export.Export;
|
|
20 import nabble.model.export.NodeData;
|
|
21 import org.slf4j.Logger;
|
|
22 import org.slf4j.LoggerFactory;
|
|
23
|
|
24 import java.io.IOException;
|
|
25 import java.io.Serializable;
|
|
26 import java.net.InetAddress;
|
|
27 import java.net.MalformedURLException;
|
|
28 import java.net.URL;
|
|
29 import java.net.UnknownHostException;
|
|
30 import java.sql.Connection;
|
|
31 import java.sql.PreparedStatement;
|
|
32 import java.sql.ResultSet;
|
|
33 import java.sql.SQLException;
|
|
34 import java.sql.Statement;
|
|
35 import java.text.CollationKey;
|
|
36 import java.text.Collator;
|
|
37 import java.util.ArrayList;
|
|
38 import java.util.Collection;
|
|
39 import java.util.Collections;
|
|
40 import java.util.Date;
|
|
41 import java.util.HashMap;
|
|
42 import java.util.Iterator;
|
|
43 import java.util.List;
|
|
44 import java.util.Map;
|
|
45 import java.util.NoSuchElementException;
|
|
46 import java.util.Set;
|
|
47 import java.util.WeakHashMap;
|
|
48 import java.util.concurrent.CopyOnWriteArrayList;
|
|
49 import java.util.concurrent.TimeUnit;
|
|
50
|
|
51
|
|
52 final class NodeImpl implements Node, Node.MailFromList {
|
|
53 private static final Logger logger = LoggerFactory.getLogger(NodeImpl.class);
|
|
54
|
|
55 private static final Message DELETED_MESSAGE = new Message("- deleted -", Message.Format.TEXT) {
|
|
56 public boolean isDeleted() { return true; }
|
|
57 public boolean isDeactivated() { return true; }
|
|
58 };
|
|
59
|
|
60 final SiteKey siteKey;
|
|
61 private final DbRecord<LongKey,NodeImpl> record;
|
|
62 private String subject;
|
|
63 private MyMessage message;
|
|
64 private Date whenCreated;
|
|
65 private long ownerId;
|
|
66 private UserImpl owner;
|
|
67 private long parentId = 0L;
|
|
68 private NodeImpl parent;
|
|
69 private String messageID;
|
|
70 private Date whenUpdated;
|
|
71 private Boolean isGuessedParent = false;
|
|
72 private Date whenSent;
|
|
73 private long lastNodeId;
|
|
74 private Date lastNodeDate;
|
|
75 private int nodeCount;
|
|
76 private Kind kind;
|
|
77 private String type;
|
|
78 private boolean isPinned;
|
|
79 private int childCount;
|
|
80 private String cookie;
|
|
81 private String anonymousName;
|
|
82 private long exportedNodeId;
|
|
83 private String exportPermalink = null;
|
|
84 private String exportEmail = null;
|
|
85 private String embeddingUrl;
|
|
86
|
|
87 private NodeImpl(SiteKey siteKey,LongKey key,ResultSet rs)
|
|
88 throws SQLException
|
|
89 {
|
|
90 this.siteKey = siteKey;
|
|
91 record = table(siteKey).newRecord(this,key);
|
|
92 subject = rs.getString("subject");
|
|
93 Message.Format msgFmt = Message.Format.getMessageFormat( rs.getString("msg_fmt").charAt(0) );
|
|
94 message = new MyMessage(msgFmt);
|
|
95 whenCreated = rs.getTimestamp("when_created");
|
|
96 ownerId = rs.getLong("owner_id");
|
|
97 parentId = rs.getLong("parent_id");
|
|
98 messageID = rs.getString("message_id");
|
|
99 whenUpdated = rs.getTimestamp("when_updated");
|
|
100 isGuessedParent = rs.getBoolean("guessed_parent");
|
|
101 if (rs.wasNull()) isGuessedParent = null;
|
|
102 whenSent = rs.getTimestamp("when_sent");
|
|
103 lastNodeId = rs.getLong("last_node_id");
|
|
104 lastNodeDate = rs.getTimestamp("last_node_date");
|
|
105 nodeCount = rs.getInt("node_count");
|
|
106 kind = rs.getBoolean("is_app") ? Kind.APP : Kind.POST;
|
|
107 type = rs.getString("type");
|
|
108 if( type==null )
|
|
109 type = Type.COMMENT;
|
|
110 rs.getInt("pin");
|
|
111 isPinned = !rs.wasNull();
|
|
112 childCount = rs.getInt("child_count");
|
|
113 cookie = rs.getString("cookie");
|
|
114 anonymousName = rs.getString("anonymous_name");
|
|
115 embeddingUrl = rs.getString("embedding_url");
|
|
116 exportedNodeId = rs.getLong("exported_node_id");
|
|
117 exportPermalink = rs.getString("export_permalink");
|
|
118 exportEmail = rs.getString("export_email");
|
|
119 for( ExtensionFactory<Node,?> factory : extensionFactories ) {
|
|
120 Object obj = factory.construct(this,rs);
|
|
121 if( obj != null )
|
|
122 getExtensionMap().put(factory,obj);
|
|
123 }
|
|
124 }
|
|
125
|
|
126 static NodeImpl newRootNode(Kind kind,UserImpl owner,String subject,String messageRaw,Message.Format msgFmt)
|
|
127 throws ModelException
|
|
128 {
|
|
129 SiteImpl site = owner.getSiteImpl();
|
|
130 return new NodeImpl(site.siteKey,kind,owner,subject,messageRaw,msgFmt);
|
|
131 }
|
|
132
|
|
133 static NodeImpl newRootNode(Kind kind,Person owner,String subject,String messageRaw,Message.Format msgFmt,SiteImpl site,String type)
|
|
134 throws ModelException
|
|
135 {
|
|
136 NodeImpl newRoot = new NodeImpl(site.siteKey,kind,owner,subject,messageRaw,msgFmt);
|
|
137 if( type != null )
|
|
138 newRoot.setType(type);
|
|
139 newRoot.insert(true);
|
|
140 NodeImpl oldRoot = site.getRootNodeImpl();
|
|
141 oldRoot.parentId = newRoot.getId();
|
|
142 oldRoot.record.fields().put("parent_id", oldRoot.parentId);
|
|
143 oldRoot.update();
|
|
144 site.setRoot(newRoot);
|
|
145 site.getDbRecord().update();
|
|
146 oldRoot.addNode();
|
|
147 return newRoot;
|
|
148 }
|
|
149
|
|
150 static NodeImpl newChildNode(Kind kind,Person owner,String subject,String messageRaw,Message.Format msgFmt,NodeImpl parent)
|
|
151 throws ModelException
|
|
152 {
|
|
153 SiteImpl site = parent.getSiteImpl();
|
|
154 if( !site.equals(owner.getSite()) )
|
|
155 throw new RuntimeException();
|
|
156 NodeImpl node = new NodeImpl(site.siteKey,kind,owner,subject,messageRaw,msgFmt);
|
|
157 node.setParent(parent);
|
|
158 return node;
|
|
159 }
|
|
160
|
|
161 private NodeImpl(SiteKey siteKey,Kind kind,Person owner,String subject,String messageRaw,Message.Format msgFmt)
|
|
162 throws ModelException
|
|
163 {
|
|
164 this.siteKey = siteKey;
|
|
165 record = table(siteKey).newRecord(this);
|
|
166 if( owner instanceof UserImpl ) {
|
|
167 this.owner = (UserImpl)owner;
|
|
168 ownerId = this.owner.getId();
|
|
169 record.fields().put("owner_id", ownerId);
|
|
170 } else {
|
|
171 Anonymous anon = (Anonymous)owner;
|
|
172 this.cookie = anon.getCookie();
|
|
173 this.anonymousName = anon.getName();
|
|
174 record.fields().put("cookie",cookie);
|
|
175 record.fields().put("anonymous_name", anonymousName);
|
|
176 }
|
|
177 setKind(kind);
|
|
178 setSubject0(subject);
|
|
179 message = new MyMessage(msgFmt);
|
|
180 setMessage0(messageRaw,msgFmt);
|
|
181 setWhenCreated(new Date());
|
|
182 nodeCount = 1;
|
|
183 childCount = 0;
|
|
184 }
|
|
185
|
|
186 private void setParent(NodeImpl parent)
|
|
187 throws ModelException
|
|
188 {
|
|
189 if( isInDb() )
|
|
190 throw new RuntimeException();
|
|
191 this.parentId = parent.getId();
|
|
192 record.fields().put("parent_id", parentId);
|
|
193 if( siteKey != parent.siteKey )
|
|
194 throw new RuntimeException();
|
|
195 if( !parent.isInDb() ) {
|
|
196 // hack for dummy nodes
|
|
197 this.parent = parent;
|
|
198 List<NodeImpl> children = dummyChildMap.get(parent);
|
|
199 if( children == null ) {
|
|
200 children = new ArrayList<NodeImpl>();
|
|
201 dummyChildMap.put(parent,children);
|
|
202 }
|
|
203 children.add(this);
|
|
204 return;
|
|
205 }
|
|
206 if( db().isInTransaction() )
|
|
207 uncacheAncestors();
|
|
208 }
|
|
209
|
|
210 public DbRecord<LongKey,NodeImpl> getDbRecord() {
|
|
211 return record;
|
|
212 }
|
|
213
|
|
214 private DbTable<LongKey,NodeImpl> table() {
|
|
215 return record.getDbTable();
|
|
216 }
|
|
217
|
|
218 private DbDatabase db() {
|
|
219 return table().getDbDatabase();
|
|
220 }
|
|
221
|
|
222 public long getId() {
|
|
223 LongKey key = record.getPrimaryKey();
|
|
224 if( key==null )
|
|
225 return 0L;
|
|
226 return key.value();
|
|
227 }
|
|
228
|
|
229 public Kind getKind() {
|
|
230 return kind;
|
|
231 }
|
|
232
|
|
233 public void setKind(Kind kind) {
|
|
234 this.kind = kind;
|
|
235 record.fields().put( "is_app", DbNull.fix(kind==Kind.APP) );
|
|
236 }
|
|
237
|
|
238 long getParentId() {
|
|
239 return parentId;
|
|
240 }
|
|
241
|
|
242 long getOwnerId() {
|
|
243 return ownerId;
|
|
244 }
|
|
245
|
|
246 public String getSubject() {
|
|
247 return subject;
|
|
248 }
|
|
249
|
|
250 public String getSubjectHtml() {
|
|
251 return HtmlUtils.htmlEncode(subject);
|
|
252 }
|
|
253
|
|
254 private synchronized boolean setSubject0(String subject) throws ModelException.RequiredSubject {
|
|
255 subject = subject.trim();
|
|
256 if( subject.equals("") )
|
|
257 throw new ModelException.RequiredSubject();
|
|
258 if( subject.equals(this.subject) )
|
|
259 return false;
|
|
260 this.subject = subject;
|
|
261 record.fields().put("subject",subject);
|
|
262 return true;
|
|
263 }
|
|
264
|
|
265 public void setSubject(String subject) throws ModelException.RequiredSubject {
|
|
266 boolean changed = setSubject0(subject);
|
|
267 if (changed)
|
|
268 setWhenUpdated();
|
|
269 }
|
|
270
|
|
271 private static final long TEN_MINUTES = 10 * 60 * 1000;
|
|
272
|
|
273 private void setWhenUpdated() {
|
|
274 long timeDiff = new Date().getTime() - getWhenCreated().getTime();
|
|
275 boolean acceptChanges = timeDiff > TEN_MINUTES || !getChildren().isEmpty() || isMailToList();
|
|
276 if (acceptChanges) {
|
|
277 setWhenUpdated( new Date() );
|
|
278 }
|
|
279 }
|
|
280
|
|
281
|
|
282 private final class MyMessage extends Message {
|
|
283
|
|
284 MyMessage(Message.Format format) {
|
|
285 super(null,format);
|
|
286 }
|
|
287
|
|
288 MyMessage(String raw,Message.Format format) {
|
|
289 super(raw,format);
|
|
290 }
|
|
291
|
|
292 private synchronized boolean hasLoaded() {
|
|
293 return raw!=null;
|
|
294 }
|
|
295
|
|
296 public synchronized String getRaw() {
|
|
297 if( raw==null && record.isInDb() ) {
|
|
298 try {
|
|
299 Connection con = db().getConnection();
|
|
300 PreparedStatement stmt = con.prepareStatement(
|
|
301 "select message from node_msg where node_id=?"
|
|
302 );
|
|
303 stmt.setLong(1,getId());
|
|
304 ResultSet rs = stmt.executeQuery();
|
|
305 if( rs.next() ) {
|
|
306 raw = rs.getString("message");
|
|
307 } else {
|
|
308 logger.error("no message for "+NodeImpl.this+" - inserting empty message");
|
|
309 raw = "";
|
|
310 insertMessage(raw);
|
|
311 }
|
|
312 rs.close();
|
|
313 stmt.close();
|
|
314 con.close();
|
|
315 } catch(SQLException e) {
|
|
316 throw new RuntimeException(e);
|
|
317 }
|
|
318 if( raw==null )
|
|
319 throw new NullPointerException(toString());
|
|
320 }
|
|
321 return raw;
|
|
322 }
|
|
323
|
|
324 public Source getSource() {
|
|
325 if( record.isInDb() )
|
|
326 return NodeImpl.this;
|
|
327 Person owner = getOwner();
|
|
328 return owner instanceof User ? new Message.TempSource((User)owner) : null;
|
|
329 }
|
|
330
|
|
331 public boolean isDeleted() {
|
|
332 return isDeletedMessage();
|
|
333 }
|
|
334
|
|
335 public boolean isDeactivated() {
|
|
336 UserImpl user = getOwnerImpl();
|
|
337 return user != null && user.isDeactivated();
|
|
338 }
|
|
339 }
|
|
340
|
|
341 public Message getMessage() {
|
|
342 return message;
|
|
343 }
|
|
344
|
|
345 private boolean setMessage0(String messageRaw,Message.Format msgFmt) {
|
|
346 MyMessage newMessage = new MyMessage(messageRaw,msgFmt);
|
|
347 if( message.equals(newMessage) )
|
|
348 return false;
|
|
349 message = newMessage;
|
|
350 record.fields().put("msg_fmt",Character.toString(msgFmt.getCode()));
|
|
351 record.fields().put("message",messageRaw);
|
|
352 return true;
|
|
353 }
|
|
354
|
|
355 public void setMessage(String message,Message.Format msgFmt) {
|
|
356 boolean changed = setMessage0(message,msgFmt);
|
|
357 if (changed)
|
|
358 setWhenUpdated();
|
|
359 }
|
|
360
|
|
361 public void deleteMessageOrNode() {
|
|
362 if( !db().isInTransaction() ) {
|
|
363 db().beginTransaction();
|
|
364 try {
|
|
365 NodeImpl node = DbUtils.getGoodCopy(NodeImpl.this);
|
|
366 node.deleteMessageOrNode();
|
|
367 db().commitTransaction();
|
|
368 } finally {
|
|
369 db().endTransaction();
|
|
370 }
|
|
371 return;
|
|
372 }
|
|
373 MailingListImpl mailingList = getMailingListImpl();
|
|
374 if (mailingList != null) {
|
|
375 mailingList.unsubscribe();
|
|
376 }
|
|
377 if( getChildCount() == 0 ) {
|
|
378 deleteRecursively();
|
|
379 } else {
|
|
380 setMessage(DELETED_MESSAGE.getRaw(),DELETED_MESSAGE.getFormat());
|
|
381 clearPending();
|
|
382 update();
|
|
383 }
|
|
384 }
|
|
385
|
|
386 private boolean isDeletedMessage() {
|
|
387 return getMessage().getRaw().equals(DELETED_MESSAGE.getRaw());
|
|
388 }
|
|
389
|
|
390 public void deleteRecursively() {
|
|
391 if( isRoot() ) {
|
|
392 getSiteImpl().delete();
|
|
393 return;
|
|
394 }
|
|
395 if( !db().isInTransaction() ) {
|
|
396 db().beginTransaction();
|
|
397 try {
|
|
398 NodeImpl node = DbUtils.getGoodCopy(NodeImpl.this);
|
|
399 node.deleteRecursively();
|
|
400 db().commitTransaction();
|
|
401 } finally {
|
|
402 db().endTransaction();
|
|
403 }
|
|
404 return;
|
|
405 }
|
|
406 NodeImpl parent = getParentImpl();
|
|
407 record.delete();
|
|
408 removedNodeFrom(parent);
|
|
409 fireChangeListeners();
|
|
410 }
|
|
411
|
|
412 private synchronized void cacheMessage(String message) {
|
|
413 this.message.raw = message;
|
|
414 }
|
|
415
|
|
416 public Date getWhenCreated() {
|
|
417 return whenCreated;
|
|
418 }
|
|
419
|
|
420 public void setWhenCreated(Date whenCreated) {
|
|
421 this.whenCreated = whenCreated;
|
|
422 record.fields().put("when_created",whenCreated);
|
|
423 if( record.isInDb() && childCount==0 ) {
|
|
424 setLastNodeDate( whenCreated );
|
|
425 removedNodeFrom( getParentImpl() );
|
|
426 addNode();
|
|
427 }
|
|
428 }
|
|
429
|
|
430 private static final Object lastNodeLock = new Object();
|
|
431
|
|
432 public Node getLastNode() {
|
|
433 Node lastNode = getNode(lastNodeId);
|
|
434 if( lastNode == null ) {
|
|
435 logger.error("lastNode not found for "+this+" with lastNodeId="+lastNodeId,new NullPointerException());
|
|
436 // hack fix -fschmidt
|
|
437 synchronized(lastNodeLock) {
|
|
438 DbUtils.uncache(this);
|
|
439 NodeImpl node = DbUtils.getGoodCopy(this);
|
|
440 if( lastNodeId != node.lastNodeId )
|
|
441 return getNode(node.lastNodeId);
|
|
442 populateLastNodeFields();
|
|
443 }
|
|
444 DbUtils.uncache(this);
|
|
445 NodeImpl node = DbUtils.getGoodCopy(this);
|
|
446 if( lastNodeId != node.lastNodeId )
|
|
447 return getNode(node.lastNodeId);
|
|
448 logger.error("after populateLastNodeFields, lastNode not found for "+node+" with lastNodeId="+node.lastNodeId);
|
|
449 }
|
|
450 return lastNode;
|
|
451 }
|
|
452
|
|
453 long getLastNodeId() {
|
|
454 return lastNodeId;
|
|
455 }
|
|
456
|
|
457 public Date getLastNodeDate() {
|
|
458 return lastNodeDate;
|
|
459 }
|
|
460
|
|
461 public Node getGoodCopy() {
|
|
462 return DbUtils.getGoodCopy(this);
|
|
463 }
|
|
464
|
|
465 public void insert(boolean isDoneByPoster) throws ModelException.TooManyPosts {
|
|
466 if( !db().isInTransaction() )
|
|
467 throw new RuntimeException();
|
|
468 if( kind==Kind.APP && type==null )
|
|
469 throw new RuntimeException("type not set for app");
|
|
470 if( isDoneByPoster ) {
|
|
471 UserImpl owner = getOwnerImpl();
|
|
472 if (owner != null)
|
|
473 owner.updateNewPostLimit();
|
|
474 }
|
|
475 if( isMailToList() && isDoneByPoster )
|
|
476 throw new RuntimeException("no more pending");
|
|
477 String message = (String)record.fields().remove("message");
|
|
478 record.insert();
|
|
479 insertMessage(message);
|
|
480 setLastNodeId( getId() );
|
|
481 setLastNodeDate( whenCreated );
|
|
482 record.update();
|
|
483 addNode();
|
|
484 }
|
|
485
|
|
486 private void insertMessage(String message) {
|
|
487 try {
|
|
488 Connection con = db().getConnection();
|
|
489 try {
|
|
490 PreparedStatement pstmt = con.prepareStatement(
|
|
491 "insert into node_msg (node_id,message) values (?,?)"
|
|
492 );
|
|
493 pstmt.setLong(1,getId());
|
|
494 pstmt.setString(2,message);
|
|
495 pstmt.executeUpdate();
|
|
496 pstmt.close();
|
|
497 } finally {
|
|
498 con.close();
|
|
499 }
|
|
500 } catch(SQLException e) {
|
|
501 throw new RuntimeException(e);
|
|
502 }
|
|
503 }
|
|
504
|
|
505 public void update() {
|
|
506 String message = (String)record.fields().remove("message");
|
|
507 if( message!=null && !db().isInTransaction() )
|
|
508 throw new RuntimeException();
|
|
509 record.update();
|
|
510 if( message != null ) {
|
|
511 try {
|
|
512 Connection con = db().getConnection();
|
|
513 PreparedStatement stmt = con.prepareStatement(
|
|
514 "update node_msg set message=? where node_id=?"
|
|
515 );
|
|
516 stmt.setLong(2,getId());
|
|
517 stmt.setString(1,message);
|
|
518 stmt.executeUpdate();
|
|
519 stmt.close();
|
|
520 con.close();
|
|
521 } catch(SQLException e) {
|
|
522 throw new RuntimeException(e);
|
|
523 }
|
|
524 }
|
|
525 }
|
|
526
|
|
527 void checkNewPostLimit() throws ModelException.TooManyPosts {
|
|
528 UserImpl owner = getOwnerImpl();
|
|
529 if (owner!=null && owner.hasTooManyPosts()) {
|
|
530 logger.warn( "Too many posts by "+owner );
|
|
531 throw new ModelException.TooManyPosts();
|
|
532 }
|
|
533 }
|
|
534
|
|
535 private void uncacheAncestors() {
|
|
536 for( NodeImpl node=this; node!=null; node=node.getParentImpl() ) {
|
|
537 DbUtils.uncache(node);
|
|
538 }
|
|
539 }
|
|
540
|
|
541 public void changeParent(Node n) throws ModelException {
|
|
542 NodeImpl node = (NodeImpl)n;
|
|
543 if( !db().isInTransaction() ) {
|
|
544 db().beginTransaction();
|
|
545 try {
|
|
546 DbUtils.getGoodCopy(this).changeParent( node.getGoodCopy() );
|
|
547 db().commitTransaction();
|
|
548 return;
|
|
549 } finally {
|
|
550 db().endTransaction();
|
|
551 }
|
|
552 }
|
|
553 changeParentImpl(node);
|
|
554 }
|
|
555
|
|
556 void changeParentImpl(NodeImpl newParent) throws ModelException {
|
|
557 if( !isInDb() )
|
|
558 throw new RuntimeException();
|
|
559 if( !db().isInTransaction() )
|
|
560 throw new RuntimeException();
|
|
561
|
|
562 final NodeImpl oldParent = getParentImpl();
|
|
563 if( oldParent.siteKey != newParent.siteKey )
|
|
564 throw new RuntimeException("can't change site");
|
|
565 db().runAfterCommit(new Runnable(){public void run(){
|
|
566 oldParent.fireChildChangeListeners();
|
|
567 }});
|
|
568 record.fields().put("pin", DbNull.INTEGER);
|
|
569
|
|
570 if (newParent.getAncestors().contains(this))
|
|
571 throw new ModelException.NodeLoop(this);
|
|
572 parentId = newParent.getId();
|
|
573 record.fields().put("parent_id", parentId);
|
|
574 parent = null;
|
|
575
|
|
576 getDbRecord().update();
|
|
577 removedNodeFrom(oldParent);
|
|
578 addNode();
|
|
579 stale();
|
|
580
|
|
581 uncacheAncestors();
|
|
582 }
|
|
583
|
|
584 void makeRoot() {
|
|
585 record.fields().put("pin", DbNull.INTEGER);
|
|
586 parentId = 0L;
|
|
587 record.fields().put("parent_id", DbNull.INTEGER);
|
|
588 parent = null;
|
|
589 getDbRecord().update();
|
|
590 stale();
|
|
591 }
|
|
592
|
|
593 private void stale() {
|
|
594 Executors.executeAfterCommit(db(),new Runnable(){public void run(){
|
|
595 try {
|
|
596 Lucene.staleNode(DbUtils.getGoodCopy(NodeImpl.this));
|
|
597 } catch(IOException e) {
|
|
598 logger.error("StaleNode failed",e);
|
|
599 }
|
|
600 }});
|
|
601 }
|
|
602
|
|
603
|
|
604 private void addNode() {
|
|
605 NodeImpl parent = getParentImpl();
|
|
606 if( parent == null )
|
|
607 return;
|
|
608 // synchronized(siteKey.lastNodeLock) {
|
|
609 parent.setChildCount();
|
|
610 for( NodeImpl node = parent; node != null; node = node.getParentImpl() ) {
|
|
611 if( node.nodeCount==1 || node.lastNodeDate.before(lastNodeDate) ) {
|
|
612 node.setLastNodeId( lastNodeId );
|
|
613 node.setLastNodeDate( lastNodeDate );
|
|
614 }
|
|
615 node.setNodeCount();
|
|
616 node.record.update();
|
|
617 }
|
|
618 // }
|
|
619 }
|
|
620
|
|
621
|
|
622 private void removedNodeFrom(NodeImpl parent) {
|
|
623 if( parent == null )
|
|
624 return;
|
|
625 // synchronized(siteKey.lastNodeLock) {
|
|
626 parent.setChildCount();
|
|
627 try {
|
|
628 Connection con = db().getConnection();
|
|
629 try {
|
|
630 PreparedStatement pstmtGetLastNode = con.prepareStatement(
|
|
631 "select * from node"
|
|
632 +" where parent_id = ?"
|
|
633 +" order by last_node_date desc, node_id desc"
|
|
634 +" limit 1"
|
|
635 );
|
|
636 for( NodeImpl node = parent; node != null; node = node.getParentImpl() ) {
|
|
637 if( node.lastNodeId == lastNodeId ) {
|
|
638 pstmtGetLastNode.setLong(1,node.getId());
|
|
639 ResultSet rs = pstmtGetLastNode.executeQuery();
|
|
640 if( rs.next() ) {
|
|
641 NodeImpl lastNode = getNode(rs);
|
|
642 node.setLastNodeId( lastNode.lastNodeId );
|
|
643 node.setLastNodeDate( lastNode.lastNodeDate );
|
|
644 } else {
|
|
645 node.setLastNodeId( node.getId() );
|
|
646 node.setLastNodeDate( node.whenCreated );
|
|
647 }
|
|
648 rs.close();
|
|
649 }
|
|
650 node.setNodeCount();
|
|
651 node.record.update();
|
|
652 }
|
|
653 pstmtGetLastNode.close();
|
|
654 } finally {
|
|
655 con.close();
|
|
656 }
|
|
657 } catch(SQLException e) {
|
|
658 throw new RuntimeException(e);
|
|
659 }
|
|
660 // }
|
|
661 parent.uncacheAncestors();
|
|
662 }
|
|
663
|
|
664 private void setLastNodeId(long lastNodeId) {
|
|
665 if( this.lastNodeId == lastNodeId )
|
|
666 return;
|
|
667 this.lastNodeId = lastNodeId;
|
|
668 record.fields().put("last_node_id", lastNodeId);
|
|
669 }
|
|
670
|
|
671 private void setLastNodeDate(Date lastNodeDate) {
|
|
672 if( ObjectUtils.equals(this.lastNodeDate,lastNodeDate) )
|
|
673 return;
|
|
674 this.lastNodeDate = lastNodeDate;
|
|
675 record.fields().put("last_node_date", lastNodeDate);
|
|
676 }
|
|
677
|
|
678 private void setNodeCount() {
|
|
679 int nodeCount = getCount( "select 1 + coalesce(sum(node_count),0) as n from node where parent_id = ?" );
|
|
680 if( this.nodeCount == nodeCount )
|
|
681 return;
|
|
682 this.nodeCount = nodeCount;
|
|
683 record.fields().put("node_count", nodeCount);
|
|
684 }
|
|
685
|
|
686 private void setChildCount() {
|
|
687 int childCount = getCount( "select count(*) as n from node where parent_id = ?" );
|
|
688 if( this.childCount == childCount )
|
|
689 return;
|
|
690 this.childCount = childCount;
|
|
691 record.fields().put("child_count", childCount);
|
|
692 }
|
|
693
|
|
694
|
|
695 public NodeIterator<? extends Node> getChildren() {
|
|
696 return getChildrenImpl(null);
|
|
697 }
|
|
698
|
|
699 public NodeIterator<? extends Node> getChildren(String cnd) {
|
|
700 return getChildrenImpl(cnd);
|
|
701 }
|
|
702
|
|
703 private static final Map<NodeImpl,List<NodeImpl>> dummyChildMap = Collections.synchronizedMap(new WeakHashMap<NodeImpl,List<NodeImpl>>());
|
|
704
|
|
705 NodeIterator<NodeImpl> getChildrenImpl(String cnd) {
|
|
706 if( !isInDb() ) {
|
|
707 List<NodeImpl> children = dummyChildMap.get(this);
|
|
708 if( children == null )
|
|
709 return NodeIterator.empty();
|
|
710 return NodeIterator.nodeIterator( children.iterator() );
|
|
711 }
|
|
712 return new CursorNodeIterator( siteKey,
|
|
713 "(select *"
|
|
714 +" from node"
|
|
715 +" where parent_id = ?"
|
|
716 +" and pin is not null "
|
|
717 +(cnd==null?"":"and " + cnd)
|
|
718 +" order by pin)"
|
|
719 +" union all"
|
|
720 +" (select *"
|
|
721 +" from node"
|
|
722 +" where parent_id = ?"
|
|
723 +" and pin is null "
|
|
724 +(cnd==null?"":"and " + cnd)
|
|
725 +" order by last_node_date desc, node_id desc)"
|
|
726 ,
|
|
727 new DbParamSetter() {
|
|
728 public void setParams(PreparedStatement stmt) throws SQLException {
|
|
729 stmt.setLong( 1, getId() );
|
|
730 stmt.setLong( 2, getId() );
|
|
731 }
|
|
732 }
|
|
733 );
|
|
734 }
|
|
735
|
|
736 private int getCount(String sql) {
|
|
737 try {
|
|
738 Connection con = db().getConnection();
|
|
739 PreparedStatement stmt = con.prepareStatement(sql);
|
|
740 stmt.setLong(1,getId());
|
|
741 ResultSet rs = stmt.executeQuery();
|
|
742 rs.next();
|
|
743 int n = rs.getInt("n");
|
|
744 rs.close();
|
|
745 stmt.close();
|
|
746 con.close();
|
|
747 return n;
|
|
748 } catch(SQLException e) {
|
|
749 logger.error("sql = " + sql);
|
|
750 throw new RuntimeException(e);
|
|
751 }
|
|
752 }
|
|
753
|
|
754 public int getChildCount() {
|
|
755 return childCount;
|
|
756 }
|
|
757
|
|
758
|
|
759
|
|
760 public boolean isPinned() {
|
|
761 return isPinned;
|
|
762 }
|
|
763
|
|
764 public void pin(Node[] children) {
|
|
765 if( !db().isInTransaction() ) {
|
|
766 db().beginTransaction();
|
|
767 try {
|
|
768 pin(children);
|
|
769 db().commitTransaction();
|
|
770 } finally {
|
|
771 db().endTransaction();
|
|
772 }
|
|
773 return;
|
|
774 }
|
|
775 try {
|
|
776 Connection con = db().getConnection();
|
|
777 try {
|
|
778 {
|
|
779 PreparedStatement stmt = con.prepareStatement(
|
|
780 "select node_id"
|
|
781 +" from node"
|
|
782 +" where parent_id = ?"
|
|
783 +" and pin is not null"
|
|
784 );
|
|
785 stmt.setLong(1,getId());
|
|
786 ResultSet rs = stmt.executeQuery();
|
|
787 while( rs.next() ) {
|
|
788 table().uncache( new LongKey(rs.getLong("node_id")) );
|
|
789 }
|
|
790 rs.close();
|
|
791 stmt.close();
|
|
792 }
|
|
793 PreparedStatement stmt = con.prepareStatement(
|
|
794 "update node set pin=null where parent_id=? and pin is not null"
|
|
795 );
|
|
796 stmt.setLong(1,getId());
|
|
797 stmt.executeUpdate();
|
|
798 stmt.close();
|
|
799 stmt = con.prepareStatement(
|
|
800 "update node set pin=? where node_id=?"
|
|
801 );
|
|
802 for( int i=0; i<children.length; i++ ) {
|
|
803 Node child = children[i];
|
|
804 if( !this.equals(child.getParent()) )
|
|
805 throw new RuntimeException(""+child+" not a child of "+this);
|
|
806 stmt.setInt(1,i+1);
|
|
807 stmt.setLong(2,child.getId());
|
|
808 stmt.executeUpdate();
|
|
809 DbUtils.uncache((NodeImpl)child);
|
|
810 }
|
|
811 stmt.close();
|
|
812 } finally {
|
|
813 con.close();
|
|
814 }
|
|
815 } catch(SQLException e) {
|
|
816 throw new RuntimeException(e);
|
|
817 }
|
|
818 fireChildChangeListeners();
|
|
819 }
|
|
820
|
|
821
|
|
822 public long getExportedNodeId() {
|
|
823 return exportedNodeId;
|
|
824 }
|
|
825
|
|
826 public void setExportedNodeId(long id) {
|
|
827 if( id==0L )
|
|
828 throw new RuntimeException();
|
|
829 this.exportedNodeId = id;
|
|
830 record.fields().put( "exported_node_id", Long.valueOf(id) );
|
|
831 record.update();
|
|
832 }
|
|
833
|
|
834 public String getEmbeddingUrl() {
|
|
835 return embeddingUrl;
|
|
836 }
|
|
837
|
|
838 public void setEmbeddingUrl(String url) {
|
|
839 this.embeddingUrl = url;
|
|
840 record.fields().put( "embedding_url", DbNull.fix(embeddingUrl));
|
|
841 record.update();
|
|
842 }
|
|
843
|
|
844
|
|
845 @Override public boolean equals(Object obj) {
|
|
846 return this==obj || obj instanceof NodeImpl && record.isInDb() && ((NodeImpl)obj).getId()==getId();
|
|
847 }
|
|
848
|
|
849 @Override public int hashCode() {
|
|
850 return (int)getId();
|
|
851 }
|
|
852
|
|
853 @Override public String toString() {
|
|
854 return "node-"+getId();
|
|
855 }
|
|
856
|
|
857 // private final ListenerList<V> preInsertListeners = new ListenerList<V>();
|
|
858 static final ListenerList<NodeImpl> preUpdateListeners = new ListenerList<NodeImpl>();
|
|
859 // private final ListenerList<V> preDeleteListeners = new ListenerList<V>();
|
|
860 static final ListenerList<NodeImpl> postInsertListeners = new ListenerList<NodeImpl>();
|
|
861 static final ListenerList<NodeImpl> postUpdateListeners = new ListenerList<NodeImpl>();
|
|
862 static final ListenerList<NodeImpl> postDeleteListeners = new ListenerList<NodeImpl>();
|
|
863
|
|
864 private static Computable<SiteKey,DbTable<LongKey,NodeImpl>> tables = new SimpleCache<SiteKey,DbTable<LongKey,NodeImpl>>(new WeakHashMap<SiteKey,DbTable<LongKey,NodeImpl>>(), new Computable<SiteKey,DbTable<LongKey,NodeImpl>>() {
|
|
865 public DbTable<LongKey,NodeImpl> get(SiteKey siteKey) {
|
|
866 DbDatabase db = siteKey.getDb();
|
|
867 final long siteId = siteKey.getId();
|
|
868 DbTable<LongKey,NodeImpl> table = db.newTable("node",db.newIdentityLongKeySetter("node_id")
|
|
869 , new DbObjectFactory<LongKey,NodeImpl>() {
|
|
870 public NodeImpl makeDbObject(LongKey key,ResultSet rs,String tableName)
|
|
871 throws SQLException
|
|
872 {
|
|
873 SiteKey siteKey = SiteKey.getInstance(siteId);
|
|
874 return new NodeImpl(siteKey,key,rs);
|
|
875 }
|
|
876 }
|
|
877 );
|
|
878 table.getPreUpdateListeners().add(preUpdateListeners);
|
|
879 table.getPostInsertListeners().add(postInsertListeners);
|
|
880 table.getPostUpdateListeners().add(postUpdateListeners);
|
|
881 table.getPostDeleteListeners().add(postDeleteListeners);
|
|
882 return table;
|
|
883 }
|
|
884 });
|
|
885
|
|
886 static DbTable<LongKey,NodeImpl> table(SiteKey siteKey) {
|
|
887 return tables.get(siteKey);
|
|
888 }
|
|
889
|
|
890 static NodeImpl getNode(SiteKey siteKey,long id) {
|
|
891 return table(siteKey).findByPrimaryKey(new LongKey(id));
|
|
892 }
|
|
893
|
|
894 private NodeImpl getNode(long id) {
|
|
895 return getNode(siteKey,id);
|
|
896 }
|
|
897
|
|
898 static Collection<NodeImpl> getNodes(SiteKey siteKey,Collection<Long> ids) {
|
|
899 List<LongKey> list = new ArrayList<LongKey>();
|
|
900 for( long id : ids ) {
|
|
901 list.add( new LongKey(id) );
|
|
902 }
|
|
903 return table(siteKey).findByPrimaryKey(list).values();
|
|
904 }
|
|
905
|
|
906 static NodeImpl getNode(SiteKey siteKey,ResultSet rs)
|
|
907 throws SQLException
|
|
908 {
|
|
909 return table(siteKey).getDbObject(rs);
|
|
910 }
|
|
911
|
|
912 private NodeImpl getNode(ResultSet rs)
|
|
913 throws SQLException
|
|
914 {
|
|
915 return getNode(siteKey,rs);
|
|
916 }
|
|
917
|
|
918
|
|
919
|
|
920
|
|
921
|
|
922 private static final Collator collator = Collator.getInstance();
|
|
923 private CollationKey collationKey = null;
|
|
924
|
|
925 CollationKey getCollationKey() {
|
|
926 if( collationKey==null )
|
|
927 collationKey = collator.getCollationKey(getSubject());
|
|
928 return collationKey;
|
|
929 }
|
|
930
|
|
931
|
|
932
|
|
933 public Collection<Subscription> getSubscriptions(int i, int n) {
|
|
934 return getSubscriptions(
|
|
935 "select * from subscription where node_id = ? limit " + n + " offset " + i
|
|
936 );
|
|
937 }
|
|
938
|
|
939 Collection<Subscription> getSubscriptions(String sql) {
|
|
940 List<Subscription> list = new ArrayList<Subscription>();
|
|
941 try {
|
|
942 Connection con = db().getConnection();
|
|
943 try {
|
|
944 PreparedStatement stmt = con.prepareStatement(sql);
|
|
945 stmt.setLong( 1, getId() );
|
|
946 ResultSet rs = stmt.executeQuery();
|
|
947 while( rs.next() ) {
|
|
948 SubscriptionImpl subscription = SubscriptionImpl.getSubscription(siteKey,rs);
|
|
949 if( subscription != null )
|
|
950 list.add( subscription );
|
|
951 }
|
|
952 rs.close();
|
|
953 stmt.close();
|
|
954 } finally {
|
|
955 con.close();
|
|
956 }
|
|
957 } catch(SQLException e) {
|
|
958 throw new RuntimeException(e);
|
|
959 }
|
|
960 return list;
|
|
961 }
|
|
962
|
|
963 public int getSubscriptionCount() {
|
|
964 db().beginTransaction();
|
|
965 try {
|
|
966 return getCount(
|
|
967 "select count(*) as n from subscription where node_id=?"
|
|
968 );
|
|
969 } finally {
|
|
970 db().endTransaction();
|
|
971 }
|
|
972 }
|
|
973
|
|
974 public Map<User,Subscription> getSubscribersToNotify() {
|
|
975 return SubscriptionImpl.getSubscribersToNotify(this);
|
|
976 }
|
|
977
|
|
978 public NodeIterator<? extends Node> getAncestors() {
|
|
979 return getAncestorImpls();
|
|
980 }
|
|
981
|
|
982 NodeIterator<NodeImpl> getAncestorImpls() {
|
|
983 return new NodeIterator<NodeImpl>() {
|
|
984 private NodeImpl next = NodeImpl.this;
|
|
985
|
|
986 public boolean hasNext() {
|
|
987 return next != null;
|
|
988 }
|
|
989
|
|
990 public NodeImpl next() {
|
|
991 if( !hasNext() )
|
|
992 throw new NoSuchElementException();
|
|
993 try {
|
|
994 return next;
|
|
995 } finally {
|
|
996 next = next.getParentImpl();
|
|
997 }
|
|
998 }
|
|
999
|
|
1000 public void close() {
|
|
1001 next = null;
|
|
1002 }
|
|
1003 };
|
|
1004 }
|
|
1005
|
|
1006
|
|
1007 synchronized UserImpl getOwnerImpl() {
|
|
1008 if( ownerId!=0L && DbUtils.isStale(owner) ) {
|
|
1009 owner = UserImpl.getUser(siteKey,ownerId);
|
|
1010 }
|
|
1011 return owner;
|
|
1012 }
|
|
1013
|
|
1014 public final Person getOwner() {
|
|
1015 UserImpl user = getOwnerImpl();
|
|
1016 if( user != null )
|
|
1017 return user;
|
|
1018 if( cookie != null )
|
|
1019 return new Anonymous(getSiteImpl(), cookie, anonymousName);
|
|
1020 throw new RuntimeException();
|
|
1021 }
|
|
1022
|
|
1023 public void setOwner(User owner) {
|
|
1024 this.owner = null;
|
|
1025 this.ownerId = owner.getId();
|
|
1026 record.fields().put("owner_id", ownerId);
|
|
1027 // Remove any anonymous information
|
|
1028 record.fields().put("cookie", DbNull.STRING);
|
|
1029 record.fields().put("anonymous_name", DbNull.STRING);
|
|
1030 }
|
|
1031
|
|
1032
|
|
1033 NodeImpl getAppImpl() {
|
|
1034 for( NodeImpl node=this; node!=null; node=node.getParentImpl() ) {
|
|
1035 if( node.getKind() == Kind.APP )
|
|
1036 return node;
|
|
1037 }
|
|
1038 return null;
|
|
1039 }
|
|
1040
|
|
1041 public final Node getApp() {
|
|
1042 return getAppImpl();
|
|
1043 }
|
|
1044
|
|
1045
|
|
1046 static ListenerList<NodeImpl> gotParentListeners = new ListenerList<NodeImpl>();
|
|
1047
|
|
1048 synchronized NodeImpl getParentImpl() {
|
|
1049 if( parentId == 0L && parent==null )
|
|
1050 return null;
|
|
1051 if( DbUtils.isStale(parent) ) {
|
|
1052 parent = getNode(parentId);
|
|
1053 if( parent == null )
|
|
1054 logger.error(""+this+" parent="+parentId+" doesn't exist");
|
|
1055 else if( parent.siteKey != siteKey )
|
|
1056 logger.error(""+this+" parent="+parentId+" siteId="+siteKey+" parent.siteId="+parent.siteKey);
|
|
1057 gotParentListeners.event(this);
|
|
1058 }
|
|
1059 return parent;
|
|
1060 }
|
|
1061
|
|
1062 public final Node getParent(){
|
|
1063 return getParentImpl();
|
|
1064 }
|
|
1065
|
|
1066 SiteImpl getSiteImpl() {
|
|
1067 return siteKey.site();
|
|
1068 }
|
|
1069
|
|
1070 public Site getSite() {
|
|
1071 return getSiteImpl();
|
|
1072 }
|
|
1073
|
|
1074 public boolean isRoot() {
|
|
1075 return parentId == 0L;
|
|
1076 }
|
|
1077
|
|
1078
|
|
1079 NodeImpl getTopicImpl() {
|
|
1080 if( getKind() != Kind.POST )
|
|
1081 return null;
|
|
1082 NodeImpl node = this;
|
|
1083 while(true) {
|
|
1084 NodeImpl parent = node.getParentImpl();
|
|
1085 if( parent==null || parent.getKind() != Kind.POST )
|
|
1086 break;
|
|
1087 node = parent;
|
|
1088 }
|
|
1089 return node;
|
|
1090 }
|
|
1091
|
|
1092 public final Node getTopic() {
|
|
1093 return getTopicImpl();
|
|
1094 }
|
|
1095
|
|
1096 static void preloadMessages(List<Node> nodes) {
|
|
1097 if( nodes.size()==0 )
|
|
1098 return;
|
|
1099 try {
|
|
1100 Map<Long,NodeImpl> map = new HashMap<Long,NodeImpl>();
|
|
1101 StringBuilder query = new StringBuilder();
|
|
1102 query.append( "select node_id, message from node_msg where node_id in (" );
|
|
1103 for (Node n : nodes) {
|
|
1104 NodeImpl node = (NodeImpl) n;
|
|
1105 if (node.message.hasLoaded())
|
|
1106 continue;
|
|
1107 if (!map.isEmpty())
|
|
1108 query.append(',');
|
|
1109 query.append(node.getId());
|
|
1110 map.put(node.getId(), node);
|
|
1111 }
|
|
1112 if( map.isEmpty() )
|
|
1113 return;
|
|
1114 query.append( ')' );
|
|
1115 Connection con = nodes.get(0).getSite().getDb().getConnection();
|
|
1116 Statement stmt = con.createStatement();
|
|
1117 ResultSet rs = stmt.executeQuery(query.toString());
|
|
1118 while( rs.next() ) {
|
|
1119 long nodeId = rs.getLong("node_id");
|
|
1120 String message = rs.getString("message");
|
|
1121 map.get(nodeId).cacheMessage(message);
|
|
1122 }
|
|
1123 rs.close();
|
|
1124 stmt.close();
|
|
1125 con.close();
|
|
1126 } catch(SQLException e) {
|
|
1127 throw new RuntimeException(e);
|
|
1128 }
|
|
1129 }
|
|
1130
|
|
1131
|
|
1132 int getIntId() {
|
|
1133 return getIntId(getId());
|
|
1134 }
|
|
1135
|
|
1136 static int getIntId(long id) {
|
|
1137 if( id > Integer.MAX_VALUE )
|
|
1138 throw new RuntimeException();
|
|
1139 return (int)id;
|
|
1140 }
|
|
1141
|
|
1142 public Date getWhenUpdated() {
|
|
1143 return whenUpdated;
|
|
1144 }
|
|
1145
|
|
1146 void setWhenUpdated(Date whenUpdated) {
|
|
1147 this.whenUpdated = whenUpdated;
|
|
1148 record.fields().put("when_updated", whenUpdated);
|
|
1149 }
|
|
1150
|
|
1151
|
|
1152
|
|
1153
|
|
1154 static ListenerList<NodeImpl> childChangeListeners = new ListenerList<NodeImpl>();
|
|
1155
|
|
1156 private void fireChildChangeListeners() {
|
|
1157 childChangeListeners.event(this);
|
|
1158 }
|
|
1159
|
|
1160 static void addPostInsertListener(final Listener<? super NodeImpl> listener) {
|
|
1161 postInsertListeners.add(listener);
|
|
1162 }
|
|
1163
|
|
1164 static void addPostUpdateListener(final Listener<? super NodeImpl> listener) {
|
|
1165 postUpdateListeners.add(listener);
|
|
1166 Listener<MailingListImpl> mlListener = new Listener<MailingListImpl>() {
|
|
1167 public void event(MailingListImpl ml) {
|
|
1168 listener.event(ml.getForumImpl());
|
|
1169 }
|
|
1170 };
|
|
1171 MailingListImpl.postInsertListeners.add(mlListener);
|
|
1172 MailingListImpl.postUpdateListeners.add(mlListener);
|
|
1173 MailingListImpl.postDeleteListeners.add(mlListener);
|
|
1174 }
|
|
1175
|
|
1176 static void addPostDeleteListener(final Listener<? super NodeImpl> listener) {
|
|
1177 postDeleteListeners.add(listener);
|
|
1178 }
|
|
1179
|
|
1180
|
|
1181 private static ListenerList<NodeImpl> changeListeners = new ListenerList<NodeImpl>();
|
|
1182
|
|
1183 private void fireChangeListeners() {
|
|
1184 changeListeners.event(this);
|
|
1185 }
|
|
1186
|
|
1187 static void addChangeListener(final Listener<? super NodeImpl> listener) {
|
|
1188 addPostUpdateListener(listener);
|
|
1189 addPostDeleteListener(listener);
|
|
1190 changeListeners.add(listener);
|
|
1191 }
|
|
1192
|
|
1193 private boolean hasNeighborTopic(boolean next) {
|
|
1194 try {
|
|
1195 Connection con = db().getConnection();
|
|
1196 PreparedStatement stmt = con.prepareStatement(
|
|
1197 "SELECT 1 " +
|
|
1198 "FROM node " +
|
|
1199 "WHERE parent_id = ? " +
|
|
1200 "AND (is_app = 'f' or is_app is null) " +
|
|
1201 "AND last_node_date " + (next?'<':'>') + " ? " +
|
|
1202 "LIMIT 1"
|
|
1203 );
|
|
1204 stmt.setLong( 1, getParentId() );
|
|
1205 stmt.setTimestamp( 2, new java.sql.Timestamp(getLastNodeDate().getTime()));
|
|
1206 ResultSet rs = stmt.executeQuery();
|
|
1207 try {
|
|
1208 return rs.next();
|
|
1209 } finally {
|
|
1210 rs.close();
|
|
1211 stmt.close();
|
|
1212 con.close();
|
|
1213 }
|
|
1214 } catch(SQLException e) {
|
|
1215 throw new RuntimeException(e);
|
|
1216 }
|
|
1217 }
|
|
1218
|
|
1219 private Node getNeighborTopic(boolean next) {
|
|
1220 try {
|
|
1221 Connection con = db().getConnection();
|
|
1222 PreparedStatement stmt = con.prepareStatement(
|
|
1223 "SELECT * "+
|
|
1224 "FROM node "+
|
|
1225 "WHERE parent_id = ? "+
|
|
1226 "AND (is_app = 'f' or is_app is null) " +
|
|
1227 "AND last_node_date " + (next?'<':'>') + " ? " +
|
|
1228 "ORDER BY last_node_date " + (next?"DESC ":"ASC ") +
|
|
1229 "LIMIT 1"
|
|
1230 );
|
|
1231
|
|
1232 stmt.setLong( 1, getParentId() );
|
|
1233 stmt.setTimestamp( 2, new java.sql.Timestamp(getLastNodeDate().getTime()));
|
|
1234 ResultSet rs = stmt.executeQuery();
|
|
1235 try {
|
|
1236 return rs.next()? getNode(rs) : null;
|
|
1237 } finally {
|
|
1238 rs.close();
|
|
1239 stmt.close();
|
|
1240 con.close();
|
|
1241 }
|
|
1242 } catch(SQLException e) {
|
|
1243 throw new RuntimeException(e);
|
|
1244 }
|
|
1245 }
|
|
1246
|
|
1247 public boolean hasPreviousTopic() {
|
|
1248 return hasNeighborTopic(false);
|
|
1249 }
|
|
1250
|
|
1251 public Node getPreviousTopic() {
|
|
1252 return getNeighborTopic(false);
|
|
1253 }
|
|
1254
|
|
1255 public boolean hasNextTopic() {
|
|
1256 return hasNeighborTopic(true);
|
|
1257 }
|
|
1258
|
|
1259 public Node getNextTopic() {
|
|
1260 return getNeighborTopic(true);
|
|
1261 }
|
|
1262
|
|
1263
|
|
1264 public int getDescendantPostCount() {
|
|
1265 return getDescendantCount() - getDescendantAppCount();
|
|
1266 }
|
|
1267
|
|
1268 public int getDescendantAppCount() {
|
|
1269 int count = 1;
|
|
1270 for( Node f : getChildApps() ) {
|
|
1271 count += f.getDescendantAppCount();
|
|
1272 }
|
|
1273 return count;
|
|
1274 }
|
|
1275
|
|
1276
|
|
1277 private Collection<NodeImpl> getDescendantApps(Filter<Node> filter) {
|
|
1278 List<NodeImpl> list = new ArrayList<NodeImpl>();
|
|
1279 getDescendantApps(filter,list);
|
|
1280 return list;
|
|
1281 }
|
|
1282
|
|
1283 private void getDescendantApps(Filter<Node> filter,Collection<NodeImpl> list) {
|
|
1284 list.add(this);
|
|
1285 for( Node f : getChildApps() ) {
|
|
1286 NodeImpl node = (NodeImpl)f;
|
|
1287 if( filter.ok(node) )
|
|
1288 node.getDescendantApps(filter,list);
|
|
1289 }
|
|
1290 }
|
|
1291
|
|
1292 private boolean hasChildKind(Node.Kind kind) {
|
|
1293 String cnd = kind == Node.Kind.APP? "is_app" : "(is_app = 'f' or is_app is null)";
|
|
1294 try {
|
|
1295 Connection con = db().getConnection();
|
|
1296 PreparedStatement stmt = con.prepareStatement(
|
|
1297 "select exists"
|
|
1298 +" (select * from node"
|
|
1299 +" where parent_id = ?"
|
|
1300 +" and "
|
|
1301 + cnd
|
|
1302 +") as b"
|
|
1303 );
|
|
1304 stmt.setLong( 1, getId() );
|
|
1305 ResultSet rs = stmt.executeQuery();
|
|
1306 rs.next();
|
|
1307 try {
|
|
1308 return rs.getBoolean("b");
|
|
1309 } finally {
|
|
1310 rs.close();
|
|
1311 stmt.close();
|
|
1312 con.close();
|
|
1313 }
|
|
1314 } catch(SQLException e) {
|
|
1315 throw new RuntimeException(e);
|
|
1316 }
|
|
1317 }
|
|
1318
|
|
1319 private boolean hasPinnedKind(Node.Kind kind) {
|
|
1320 String cnd = kind == Node.Kind.APP? "is_app" : "(is_app = 'f' or is_app is null)";
|
|
1321 try {
|
|
1322 Connection con = db().getConnection();
|
|
1323 PreparedStatement stmt = con.prepareStatement(
|
|
1324 "select exists"
|
|
1325 +" (select 1 from node"
|
|
1326 +" where parent_id = ?"
|
|
1327 +" and pin is not null"
|
|
1328 +" and "
|
|
1329 + cnd
|
|
1330 +") as b"
|
|
1331 );
|
|
1332 stmt.setLong( 1, getId() );
|
|
1333 ResultSet rs = stmt.executeQuery();
|
|
1334 rs.next();
|
|
1335 try {
|
|
1336 return rs.getBoolean("b");
|
|
1337 } finally {
|
|
1338 rs.close();
|
|
1339 stmt.close();
|
|
1340 con.close();
|
|
1341 }
|
|
1342 } catch(SQLException e) {
|
|
1343 throw new RuntimeException(e);
|
|
1344 }
|
|
1345 }
|
|
1346
|
|
1347 public boolean hasChildApps() {
|
|
1348 return hasChildKind(Node.Kind.APP);
|
|
1349 }
|
|
1350
|
|
1351 public boolean hasChildTopics() {
|
|
1352 return hasChildKind(Node.Kind.POST);
|
|
1353 }
|
|
1354
|
|
1355 public boolean hasPinnedApps() {
|
|
1356 return hasPinnedKind(Node.Kind.APP);
|
|
1357 }
|
|
1358
|
|
1359 public boolean hasPinnedTopics() {
|
|
1360 return hasPinnedKind(Node.Kind.POST);
|
|
1361 }
|
|
1362
|
|
1363 public NodeIterator<? extends Node> getChildApps() {
|
|
1364 return getChildApps(null);
|
|
1365 }
|
|
1366
|
|
1367 public NodeIterator<? extends Node> getChildApps(String cnd) {
|
|
1368 cnd = cnd==null ? "is_app" : "is_app and (" + cnd + ")";
|
|
1369 return getChildrenImpl(cnd);
|
|
1370 }
|
|
1371
|
|
1372 public String getType() {
|
|
1373 return type;
|
|
1374 }
|
|
1375
|
|
1376 public void setType(String type) {
|
|
1377 this.type = type;
|
|
1378 record.fields().put( "type",
|
|
1379 Type.COMMENT.equals(type) ? DbNull.STRING : type
|
|
1380 );
|
|
1381 }
|
|
1382
|
|
1383
|
|
1384 public boolean isInDb() {
|
|
1385 return record.isInDb();
|
|
1386 }
|
|
1387
|
|
1388
|
|
1389 public int getDescendantCount() {
|
|
1390 return nodeCount;
|
|
1391 }
|
|
1392
|
|
1393 public Message.SourceType getMessageSourceType() {
|
|
1394 return Message.SourceType.NODE;
|
|
1395 }
|
|
1396
|
|
1397
|
|
1398 static void nop() {}
|
|
1399
|
|
1400
|
|
1401 private DbParamSetter simpleParamSetter() {
|
|
1402 return new DbParamSetter() {
|
|
1403 public void setParams(PreparedStatement stmt) throws SQLException {
|
|
1404 stmt.setLong( 1, getId() );
|
|
1405 }
|
|
1406 };
|
|
1407 }
|
|
1408
|
|
1409 private List<NodeImpl> childAppList() {
|
|
1410 return new CursorNodeIterator( siteKey,
|
|
1411 "select * from node where parent_id = ? and is_app"
|
|
1412 , simpleParamSetter()
|
|
1413 ).asList();
|
|
1414 }
|
|
1415
|
|
1416 private int getTopicCount(Filter<Node> filter) {
|
|
1417 int n = childCount;
|
|
1418 for( NodeImpl childApp : childAppList() ) {
|
|
1419 n--;
|
|
1420 if( filter.ok(childApp) )
|
|
1421 n += childApp.getTopicCount(filter);
|
|
1422 }
|
|
1423 return n;
|
|
1424 }
|
|
1425
|
|
1426 private int getTopicCount2(String cnd,Filter<Node> filter) {
|
|
1427 int n = getCount(
|
|
1428 "select count(*) as n from node where parent_id=? and is_app is null and (" + cnd + ")"
|
|
1429 );
|
|
1430 for( NodeImpl childApp : childAppList() ) {
|
|
1431 if( filter.ok(childApp) )
|
|
1432 n += childApp.getTopicCount2(cnd,filter);
|
|
1433 }
|
|
1434 return n;
|
|
1435 }
|
|
1436
|
|
1437 public int getTopicCount(String cnd,Filter<Node> filter) {
|
|
1438 if( !db().isInTransaction() ) {
|
|
1439 db().beginTransaction();
|
|
1440 try {
|
|
1441 return getTopicCount(cnd,filter);
|
|
1442 } finally {
|
|
1443 db().endTransaction();
|
|
1444 }
|
|
1445 }
|
|
1446 return getTopicCount0(cnd, filter);
|
|
1447 }
|
|
1448
|
|
1449 private Map<String, Integer> topicCountCache;
|
|
1450
|
|
1451 private synchronized int getTopicCount0(String cnd, Filter<Node> filter) {
|
|
1452 if (topicCountCache == null)
|
|
1453 topicCountCache = new HashMap<String, Integer>();
|
|
1454 String cacheKey = (cnd == null? "" : cnd + '|') + filter.getClass().getName();
|
|
1455 Integer countValue = topicCountCache.get(cacheKey);
|
|
1456 if (countValue == null) {
|
|
1457 countValue = cnd==null ? getTopicCount(filter) : getTopicCount2(cnd,filter);
|
|
1458 topicCountCache.put(cacheKey, countValue);
|
|
1459 }
|
|
1460 return countValue;
|
|
1461 }
|
|
1462
|
|
1463
|
|
1464 private static class MyIter {
|
|
1465 NodeImpl node;
|
|
1466 Comparable cmp;
|
|
1467 final NodeIterator<NodeImpl> iter;
|
|
1468
|
|
1469 MyIter(NodeImpl node,Comparable cmp,NodeIterator<NodeImpl> iter) {
|
|
1470 this.node = node;
|
|
1471 this.cmp = cmp;
|
|
1472 this.iter = iter;
|
|
1473 }
|
|
1474 }
|
|
1475
|
|
1476 private class OrderedNodeIterator extends NodeIterator<NodeImpl> {
|
|
1477 private final List<MyIter> mis = new ArrayList<MyIter>();
|
|
1478 NodeImpl next = null;
|
|
1479 private final boolean isTopics;
|
|
1480 private final boolean skipPinned;
|
|
1481 private final Order order;
|
|
1482 private final String sql;
|
|
1483 private final Filter<Node> filter;
|
|
1484
|
|
1485 OrderedNodeIterator(boolean isTopics,boolean skipPinned,String cnd,Filter<Node> filter,Order order) {
|
|
1486 if( !isTopics && skipPinned )
|
|
1487 throw new UnsupportedOperationException();
|
|
1488 this.isTopics = isTopics;
|
|
1489 this.skipPinned = skipPinned;
|
|
1490 this.order = order;
|
|
1491 this.filter = filter;
|
|
1492 StringBuilder buf = new StringBuilder();
|
|
1493 buf.append( "select * from node where parent_id = ?" );
|
|
1494 if( cnd != null )
|
|
1495 buf.append( " and (is_app or (" + cnd + ")) " );
|
|
1496 buf.append( " order by " ).append( order.sqlOrder() );
|
|
1497 this.sql = buf.toString();
|
|
1498 NodeIterator<NodeImpl> empty = NodeIterator.empty();
|
|
1499 mis.add( new MyIter(NodeImpl.this,order.getComparable(NodeImpl.this),empty) );
|
|
1500 }
|
|
1501
|
|
1502 void add(MyIter mi) {
|
|
1503 int len = mis.size();
|
|
1504 for( int i=0; i<len; i++ ) {
|
|
1505 @SuppressWarnings("unchecked")
|
|
1506 boolean precedes = mi.cmp.compareTo(mis.get(i).cmp) < 0;
|
|
1507 if( precedes ) {
|
|
1508 mis.add(i,mi);
|
|
1509 return;
|
|
1510 }
|
|
1511 }
|
|
1512 mis.add(mi);
|
|
1513 }
|
|
1514
|
|
1515 public boolean hasNext() {
|
|
1516 if( next != null )
|
|
1517 return true;
|
|
1518 while( !mis.isEmpty() ) {
|
|
1519 MyIter mi = mis.remove(0);
|
|
1520 if( mi.iter == null ) {
|
|
1521 next = mi.node;
|
|
1522 return true;
|
|
1523 }
|
|
1524 final NodeImpl node = mi.node;
|
|
1525 if( mi.iter.hasNext() ) {
|
|
1526 mi.node = mi.iter.next();
|
|
1527 mi.cmp = order.getComparable(mi.node);
|
|
1528 add(mi);
|
|
1529 }
|
|
1530 if( node != NodeImpl.this && filter != null && !filter.ok(node) )
|
|
1531 continue;
|
|
1532 boolean isPost = node.getKind() == Kind.POST;
|
|
1533 if( isPost && isTopics ) {
|
|
1534 if( skipPinned && node.isPinned() && node.parentId==getId() )
|
|
1535 continue;
|
|
1536 next = node;
|
|
1537 return true;
|
|
1538 }
|
|
1539 NodeIterator<NodeImpl> children = new CursorNodeIterator( siteKey, sql,
|
|
1540 new DbParamSetter() {
|
|
1541 public void setParams(PreparedStatement stmt) throws SQLException {
|
|
1542 stmt.setLong( 1, node.getId() );
|
|
1543 }
|
|
1544 }
|
|
1545 );
|
|
1546 if( children.hasNext() ) {
|
|
1547 NodeImpl firstChild = children.next();
|
|
1548 add( new MyIter(firstChild,order.getComparable(firstChild),children) );
|
|
1549 }
|
|
1550 if( isPost ) {
|
|
1551 Comparable postCmp = order.getPostComparable(node);
|
|
1552 if( postCmp != order.getComparable(node) ) {
|
|
1553 add( new MyIter(node,postCmp,null) );
|
|
1554 } else {
|
|
1555 next = node;
|
|
1556 return true;
|
|
1557 }
|
|
1558 }
|
|
1559 }
|
|
1560 return false;
|
|
1561 }
|
|
1562
|
|
1563 public NodeImpl next() throws NoSuchElementException {
|
|
1564 if( !hasNext() )
|
|
1565 throw new NoSuchElementException();
|
|
1566 try {
|
|
1567 return next;
|
|
1568 } finally {
|
|
1569 next = null;
|
|
1570 }
|
|
1571 }
|
|
1572
|
|
1573 public void close() {
|
|
1574 while( !mis.isEmpty() ) {
|
|
1575 NodeIterator<NodeImpl> iter = mis.remove(0).iter;
|
|
1576 if( iter != null )
|
|
1577 iter.close();
|
|
1578 }
|
|
1579 }
|
|
1580 }
|
|
1581
|
|
1582 private static class ConcatNodeIterator extends NodeIterator<NodeImpl> {
|
|
1583 private final NodeIterator<NodeImpl>[] a;
|
|
1584 private int i = 0;
|
|
1585
|
|
1586 ConcatNodeIterator(NodeIterator<NodeImpl>... a) {
|
|
1587 this.a = a;
|
|
1588 }
|
|
1589
|
|
1590 public boolean hasNext() {
|
|
1591 while(true) {
|
|
1592 if( i==a.length )
|
|
1593 return false;
|
|
1594 if( a[i].hasNext() )
|
|
1595 return true;
|
|
1596 a[i++].close();
|
|
1597 }
|
|
1598 }
|
|
1599
|
|
1600 public NodeImpl next() throws NoSuchElementException {
|
|
1601 return a[i].next();
|
|
1602 }
|
|
1603
|
|
1604 public void close() {
|
|
1605 while( i < a.length ) {
|
|
1606 a[i++].close();
|
|
1607 }
|
|
1608 }
|
|
1609 }
|
|
1610
|
|
1611 private String fixCnd(String cnd) {
|
|
1612 if( cnd==null )
|
|
1613 return "";
|
|
1614 cnd = cnd.trim();
|
|
1615 return cnd.length()==0 ? "" : " and (" + cnd + ") ";
|
|
1616 }
|
|
1617
|
|
1618 private NodeIterator<NodeImpl> getPinned(String cnd) {
|
|
1619 cnd = fixCnd(cnd);
|
|
1620 return new CursorNodeIterator( siteKey,
|
|
1621 "select * from node where pin is not null and parent_id = ? and is_app is null"
|
|
1622 + cnd
|
|
1623 +" order by pin"
|
|
1624 , simpleParamSetter()
|
|
1625 );
|
|
1626 }
|
|
1627
|
|
1628
|
|
1629 public NodeIterator<? extends Node> getTopicsByPinnedAndLastNodeDate(String cnd,Filter<Node> filter) {
|
|
1630 @SuppressWarnings("unchecked")
|
|
1631 NodeIterator<NodeImpl> i = new ConcatNodeIterator(
|
|
1632 getPinned(cnd),
|
|
1633 new OrderedNodeIterator(true,true,cnd,filter,Order.BY_LAST_NODE_DATE_DESC)
|
|
1634 );
|
|
1635 return i;
|
|
1636 }
|
|
1637
|
|
1638 public NodeIterator<? extends Node> getPostsByDate(Filter<Node> filter) {
|
|
1639 return new OrderedNodeIterator(false,false,null,filter,Order.BY_DATE_DESC);
|
|
1640 }
|
|
1641
|
|
1642 public NodeIterator<? extends Node> getPostsByDateAscending(Filter<Node> filter) {
|
|
1643 return new OrderedNodeIterator(false,false,null,filter,Order.BY_WHEN_CREATED);
|
|
1644 }
|
|
1645
|
|
1646 public NodeIterator<? extends Node> getTopicsByLastNodeDate(String cnd,Filter<Node> filter) {
|
|
1647 return new OrderedNodeIterator(true,false,cnd,filter,Order.BY_LAST_NODE_DATE_DESC);
|
|
1648 }
|
|
1649
|
|
1650 public NodeIterator<? extends Node> getTopicsBySubject(String cnd,Filter<Node> filter) {
|
|
1651 return new OrderedNodeIterator(true,false,cnd,filter,Order.BY_SUBJECT);
|
|
1652 }
|
|
1653
|
|
1654 public NodeIterator<? extends Node> getTopicsByPinnedAndRootNodeDate(String cnd,Filter<Node> filter) {
|
|
1655 String fixedCnd = fixCnd(cnd);
|
|
1656 StringBuilder sql = new StringBuilder();
|
|
1657 Collection<NodeImpl> apps = getDescendantApps(filter);
|
|
1658 apps.remove(this);
|
|
1659 sql.append( "select * from node where parent_id=" ).append( getId() )
|
|
1660 .append( " and is_app is null and pin is null" ).append( fixedCnd );
|
|
1661 if( !apps.isEmpty() ) {
|
|
1662 sql.append( " or parent_id in (" );
|
|
1663 Iterator<NodeImpl> iter = apps.iterator();
|
|
1664 sql.append( iter.next().getId() );
|
|
1665 while( iter.hasNext() ) {
|
|
1666 sql.append( "," ).append( iter.next().getId() );
|
|
1667 }
|
|
1668 sql.append( ") and is_app is null" ).append( fixedCnd );
|
|
1669 }
|
|
1670 sql.append(" order by when_created desc");
|
|
1671
|
|
1672 @SuppressWarnings("unchecked")
|
|
1673 NodeIterator<NodeImpl> i = new ConcatNodeIterator(
|
|
1674 getPinned(cnd),
|
|
1675 new CursorNodeIterator( siteKey, sql.toString(), DbParamSetter.NONE )
|
|
1676 );
|
|
1677 return i;
|
|
1678 }
|
|
1679
|
|
1680 public NodeIterator<? extends Node> getTopicsByPopularity(String cnd,Filter<Node> filter) {
|
|
1681 String fixedCnd = fixCnd(cnd);
|
|
1682 StringBuilder sql = new StringBuilder();
|
|
1683 Collection<NodeImpl> apps = getDescendantApps(filter);
|
|
1684 sql.append( "SELECT n.* FROM node n, view_count vc ")
|
|
1685 .append("WHERE n.node_id = vc.node_id ")
|
|
1686 .append("AND is_app is null ")
|
|
1687 .append("AND pin is null " )
|
|
1688 .append(fixedCnd)
|
|
1689 .append("AND parent_id in (");
|
|
1690 Iterator<NodeImpl> iter = apps.iterator();
|
|
1691 sql.append( iter.next().getId() );
|
|
1692 while( iter.hasNext() ) {
|
|
1693 sql.append( "," ).append( iter.next().getId() );
|
|
1694 }
|
|
1695 sql.append(") ")
|
|
1696 .append("ORDER BY views desc");
|
|
1697
|
|
1698 @SuppressWarnings("unchecked")
|
|
1699 NodeIterator<NodeImpl> i = new ConcatNodeIterator(
|
|
1700 getPinned(cnd),
|
|
1701 new CursorNodeIterator( siteKey, sql.toString(), DbParamSetter.NONE )
|
|
1702 );
|
|
1703 return i;
|
|
1704 }
|
|
1705
|
|
1706 public NodeIterator<? extends Node> getDescendants() {
|
|
1707 return getDescendantImpls();
|
|
1708 }
|
|
1709
|
|
1710 NodeIterator<NodeImpl> getDescendantImpls() {
|
|
1711 return getDescendantImpls(null);
|
|
1712 }
|
|
1713
|
|
1714 public NodeIterator<? extends Node> getDescendantApps() {
|
|
1715 return getDescendantImpls("is_app");
|
|
1716 }
|
|
1717
|
|
1718 private NodeIterator<NodeImpl> getDescendantImpls(String cnd) {
|
|
1719 List<NodeImpl> list = new ArrayList<NodeImpl>();
|
|
1720 list.add(this);
|
|
1721 int i = 0;
|
|
1722 while( i < list.size() ) {
|
|
1723 NodeImpl node = list.get(i++);
|
|
1724 for( NodeImpl child : node.getChildrenImpl(cnd) ) {
|
|
1725 list.add(child);
|
|
1726 }
|
|
1727 }
|
|
1728 return NodeIterator.nodeIterator(list);
|
|
1729 }
|
|
1730
|
|
1731 public long getSourceId() {
|
|
1732 return getId();
|
|
1733 }
|
|
1734
|
|
1735
|
|
1736
|
|
1737 public void populateLastNodeFields() {
|
|
1738 if( !db().isInTransaction() ) {
|
|
1739 db().beginTransaction();
|
|
1740 try {
|
|
1741 DbUtils.getGoodCopy(this).populateLastNodeFields();
|
|
1742 db().commitTransaction();
|
|
1743 } finally {
|
|
1744 db().endTransaction();
|
|
1745 }
|
|
1746 return;
|
|
1747 }
|
|
1748 // synchronized(siteKey.lastNodeLock) {
|
|
1749 populateLastNodeFields2();
|
|
1750 // }
|
|
1751 }
|
|
1752
|
|
1753 private void populateLastNodeFields2() {
|
|
1754 NodeImpl lastChild = null;
|
|
1755 NodeIterator<NodeImpl> nodes = new CursorNodeIterator( siteKey,
|
|
1756 "select * from node where parent_id = ?"
|
|
1757 , simpleParamSetter()
|
|
1758 );
|
|
1759 for( NodeImpl child : nodes ) {
|
|
1760 child.populateLastNodeFields2();
|
|
1761 if( lastChild==null || lastChild.lastNodeDate.before(child.lastNodeDate) )
|
|
1762 lastChild = child;
|
|
1763 }
|
|
1764 if( lastChild==null ) {
|
|
1765 setLastNodeId( getId() );
|
|
1766 setLastNodeDate( whenCreated );
|
|
1767 } else {
|
|
1768 setLastNodeId( lastChild.lastNodeId );
|
|
1769 setLastNodeDate( lastChild.lastNodeDate );
|
|
1770 }
|
|
1771 setNodeCount();
|
|
1772 setChildCount();
|
|
1773 if( !record.fields().isEmpty() )
|
|
1774 record.update();
|
|
1775 }
|
|
1776
|
|
1777
|
|
1778
|
|
1779 // mailing list related
|
|
1780
|
|
1781 static final String messageIDEnding;
|
|
1782 static {
|
|
1783 try {
|
|
1784 messageIDEnding = ".post@" + Init.get("mailDomain",InetAddress.getLocalHost().getHostName());
|
|
1785 } catch(UnknownHostException e) {
|
|
1786 logger.error("",e);
|
|
1787 System.exit(-1);
|
|
1788 throw new RuntimeException(); // for compiler
|
|
1789 }
|
|
1790 }
|
|
1791
|
|
1792 public String getMessageID() {
|
|
1793 return messageID;
|
|
1794 }
|
|
1795
|
|
1796 public MailFromList getParentMailFromList() {
|
|
1797 Node node = getParent();
|
|
1798 return (node == null) ? null : node.getMailFromList();
|
|
1799 }
|
|
1800
|
|
1801 public String getOrGenerateMessageID() {
|
|
1802 if (messageID == null) {
|
|
1803 String id = "" + System.currentTimeMillis() + "-" + getId() + messageIDEnding;
|
|
1804 setMessageID(id);
|
|
1805 if( isInDb() )
|
|
1806 this.record.update();
|
|
1807 }
|
|
1808 return messageID;
|
|
1809 }
|
|
1810
|
|
1811 void setMessageID(String messageID) {
|
|
1812 this.messageID = messageID;
|
|
1813 record.fields().put("message_id",messageID);
|
|
1814 }
|
|
1815
|
|
1816 void setGuessedParent(NodeImpl newParent)
|
|
1817 throws ModelException
|
|
1818 {
|
|
1819 setGuessedParent(true);
|
|
1820 changeParentImpl(newParent);
|
|
1821 }
|
|
1822
|
|
1823 boolean isGuessedParent() {
|
|
1824 return (isGuessedParent != null) && isGuessedParent;
|
|
1825 }
|
|
1826
|
|
1827 boolean isNotGuessedParent() {
|
|
1828 return (isGuessedParent != null) && !isGuessedParent;
|
|
1829 }
|
|
1830
|
|
1831 public boolean hasGuessedParent() {
|
|
1832 return isGuessedParent();
|
|
1833 }
|
|
1834
|
|
1835 Boolean rawGuessedParent() {
|
|
1836 return isGuessedParent;
|
|
1837 }
|
|
1838
|
|
1839 /**
|
|
1840 * Set 'guessed_parent' flag of the post.
|
|
1841 *
|
|
1842 * @param guessed flag value
|
|
1843 */
|
|
1844 void setGuessedParent(Boolean guessed) {
|
|
1845 this.isGuessedParent = guessed;
|
|
1846 record.fields().put("guessed_parent", DbNull.fix(this.isGuessedParent) );
|
|
1847 }
|
|
1848
|
|
1849 void setGuessedParent(String parentID) {
|
|
1850 setGuessedParent(Boolean.TRUE);
|
|
1851 setRawParentMessageId(parentID);
|
|
1852 }
|
|
1853
|
|
1854 // only returns MailingList if not isUIHidden
|
|
1855 public MailingList getAssociatedMailingList() {
|
|
1856 return getAssociatedMailingListImpl();
|
|
1857 }
|
|
1858
|
|
1859 MailingListImpl getAssociatedMailingListImpl() {
|
|
1860 for( NodeImpl node=this; node!=null; node=node.getParentImpl() ) {
|
|
1861 if( node.getKind()==Kind.APP ) {
|
|
1862 MailingListImpl ml = node.getMailingListImpl();
|
|
1863 if( ml != null )
|
|
1864 return ml;
|
|
1865 }
|
|
1866 }
|
|
1867 return null;
|
|
1868 }
|
|
1869
|
|
1870 boolean isFromMailingList() {
|
|
1871 return message.getFormat() == Message.Format.MAILING_LIST;
|
|
1872 }
|
|
1873
|
|
1874 void clearPending() {
|
|
1875 whenSent = null;
|
|
1876 record.fields().put("when_sent", DbNull.TIMESTAMP);
|
|
1877 if( !db().isInTransaction() ) {
|
|
1878 record.update();
|
|
1879 DbUtils.uncache(getOwnerImpl());
|
|
1880 }
|
|
1881 }
|
|
1882
|
|
1883 private boolean isMailToList() {
|
|
1884 return getKind() == Kind.POST && getAssociatedMailingListImpl() != null && !isFromMailingList();
|
|
1885 }
|
|
1886
|
|
1887 public MailToList getMailToList() {
|
|
1888 if( !isMailToList() )
|
|
1889 return null;
|
|
1890 return new MailToList() {
|
|
1891
|
|
1892 public Node getNode() {
|
|
1893 return NodeImpl.this;
|
|
1894 }
|
|
1895
|
|
1896 public boolean isPending() {
|
|
1897 return whenSent != null;
|
|
1898 }
|
|
1899
|
|
1900 public void clearPending() {
|
|
1901 NodeImpl.this.clearPending();
|
|
1902 }
|
|
1903
|
|
1904 public Date getWhenSent() {
|
|
1905 return whenSent;
|
|
1906 }
|
|
1907
|
|
1908 public String getOrGenerateMessageID() {
|
|
1909 return NodeImpl.this.getOrGenerateMessageID();
|
|
1910 }
|
|
1911
|
|
1912 };
|
|
1913 }
|
|
1914
|
|
1915
|
|
1916 public MailFromList getMailFromList() {
|
|
1917 // MailFromList is used to work with all messages from mailing lists, both local and external
|
|
1918 return (getKind() == Kind.POST && getAssociatedMailingListImpl() != null) ? this : null;
|
|
1919 }
|
|
1920
|
|
1921 public MailingList newMailingList(ListServer listServer,String listAddress,String url) throws ModelException {
|
|
1922 if( getKind() != Kind.APP )
|
|
1923 throw new UnsupportedOperationException();
|
|
1924 if( !ModelHome.insideImportProcedure.get() )
|
|
1925 DailyNumber.forumsStarted.dec();
|
|
1926 setMailingList(new MailingListImpl(this, listServer, listAddress, url));
|
|
1927 DbUtils.uncache(this);
|
|
1928 return mailingList;
|
|
1929 }
|
|
1930
|
|
1931 private void setRawParentMessageId(String parentMessageId) {
|
|
1932 record.fields().put("parent_message_id", DbNull.fix(parentMessageId));
|
|
1933 }
|
|
1934
|
|
1935 static NodeImpl[] getFromParentID(String parentID, MailingListImpl mailingList) {
|
|
1936 try {
|
|
1937 SiteKey siteKey = mailingList.siteKey;
|
|
1938 Connection con = siteKey.getDb().getConnection();
|
|
1939 PreparedStatement stmt = con.prepareStatement(
|
|
1940 "select *"
|
|
1941 +" from node"
|
|
1942 +" where lower(parent_message_id)=?"
|
|
1943 );
|
|
1944 stmt.setString(1,parentID.toLowerCase());
|
|
1945 ResultSet rs = stmt.executeQuery();
|
|
1946 try {
|
|
1947 List<NodeImpl> list = new ArrayList<NodeImpl>();
|
|
1948 while( rs.next() ) {
|
|
1949 NodeImpl post = getNode(siteKey,rs);
|
|
1950 if (mailingList.equals(post.getAssociatedMailingListImpl()))
|
|
1951 list.add( post );
|
|
1952 }
|
|
1953 return list.toArray(new NodeImpl[0]);
|
|
1954 } finally {
|
|
1955 rs.close();
|
|
1956 stmt.close();
|
|
1957 con.close();
|
|
1958 }
|
|
1959 } catch(SQLException e) {
|
|
1960 throw new RuntimeException(e);
|
|
1961 }
|
|
1962 }
|
|
1963
|
|
1964 NodeImpl getNodeImplFromMessageID(String messageID) {
|
|
1965 if( messageID == null )
|
|
1966 return null;
|
|
1967 try {
|
|
1968 Connection con = db().getConnection();
|
|
1969 PreparedStatement stmt = con.prepareStatement(
|
|
1970 "select * from node"
|
|
1971 +" where lower(message_id)=? and message_id is not null"
|
|
1972 );
|
|
1973 stmt.setString(1,messageID.toLowerCase());
|
|
1974 ResultSet rs = stmt.executeQuery();
|
|
1975 try {
|
|
1976 while (rs.next()) {
|
|
1977 NodeImpl post = getNode(rs);
|
|
1978 if( post.getAncestors().contains(this) )
|
|
1979 return post;
|
|
1980 }
|
|
1981 return null;
|
|
1982 } finally {
|
|
1983 rs.close();
|
|
1984 stmt.close();
|
|
1985 con.close();
|
|
1986 }
|
|
1987 } catch(SQLException e) {
|
|
1988 throw new RuntimeException(e);
|
|
1989 }
|
|
1990 }
|
|
1991
|
|
1992
|
|
1993
|
|
1994
|
|
1995
|
|
1996 private MailingListImpl mailingList;
|
|
1997 private boolean mailingListSet = false;
|
|
1998
|
|
1999 private void setMailingList(MailingListImpl mailingList) {
|
|
2000 this.mailingList = mailingList;
|
|
2001 mailingListSet = true;
|
|
2002 }
|
|
2003
|
|
2004 MailingListImpl getMailingListImpl() {
|
|
2005 if( getKind() != Kind.APP )
|
|
2006 return null;
|
|
2007 if (!mailingListSet || (mailingList != null && DbUtils.isStale(mailingList))) {
|
|
2008 setMailingList(MailingListImpl.getMailingListForForum(this));
|
|
2009 }
|
|
2010 return mailingList;
|
|
2011 }
|
|
2012
|
|
2013 public MailingList getMailingList() {
|
|
2014 return getMailingListImpl();
|
|
2015 }
|
|
2016
|
|
2017 public void deleteMailingList() {
|
|
2018 MailingList mailingList = getMailingList();
|
|
2019 if (mailingList != null) {
|
|
2020 mailingList.delete();
|
|
2021 this.mailingList = null;
|
|
2022 this.mailingListSet = false;
|
|
2023 DbUtils.uncache(this);
|
|
2024 }
|
|
2025 }
|
|
2026
|
|
2027
|
|
2028
|
|
2029
|
|
2030 // export/import
|
|
2031
|
|
2032 NodeImpl(SiteImpl site,NodeData data)
|
|
2033 throws ModelException
|
|
2034 {
|
|
2035 this(
|
|
2036 site.siteKey,
|
|
2037 Kind.valueOf(data.kind),
|
|
2038 data.ownerAnonymousId == null ?
|
|
2039 site.getOrCreateUser(data.ownerEmail,data.ownerName) :
|
|
2040 new Anonymous(site, data.ownerAnonymousId, data.ownerName),
|
|
2041 data.subject,
|
|
2042 data.message,
|
|
2043 Message.Format.getMessageFormat(data.msgFmt)
|
|
2044 );
|
|
2045 if( data.parentId != null ) {
|
|
2046 setParent( getNode(data.parentId) );
|
|
2047 }
|
|
2048 setWhenCreated( data.whenCreated );
|
|
2049 if( data.whenUpdated != null )
|
|
2050 setWhenUpdated( data.whenUpdated );
|
|
2051 setType( data.type );
|
|
2052 if( data.pin != null )
|
|
2053 record.fields().put( "pin", data.pin );
|
|
2054 if( data.messageID != null )
|
|
2055 setMessageID( data.messageID );
|
|
2056 setGuessedParent( data.isGuessedParent );
|
|
2057 insert(false);
|
|
2058
|
|
2059 if( data.mlAddress != null ) {
|
|
2060 ListServer listServer = ListServer.getServer( data.mlServer );
|
|
2061 MailingList mailingList = newMailingList( listServer, data.mlAddress, data.mlUrl );
|
|
2062 mailingList.setPlainTextOnly( data.mlPlainTextOnly );
|
|
2063 mailingList.setIgnoreNoArchive( data.mlIgnoreNoArchive );
|
|
2064 mailingList.setListName( data.mlListName );
|
|
2065 mailingList.update();
|
|
2066 update();
|
|
2067 }
|
|
2068
|
|
2069 for( URL url : data.fileUrls ) {
|
|
2070 try {
|
|
2071 FileUpload.uploadFile( new FileUpload.UrlFileItem(url), this );
|
|
2072 } catch(ModelException e) {}
|
|
2073 }
|
|
2074
|
|
2075 // Only for backup recovery
|
|
2076 if (data.files != null && data.files.size() > 0) {
|
|
2077 Set<Map.Entry<String, byte[]>> entries = data.files.entrySet();
|
|
2078 for (Map.Entry<String, byte[]> entry : entries) {
|
|
2079 FileUpload.saveFile(entry.getValue(), entry.getKey(), this);
|
|
2080 }
|
|
2081 }
|
|
2082
|
|
2083 for( ExtensionFactory<Node,?> factory : extensionFactories ) {
|
|
2084 Serializable obj = data.extensionData.get(factory.getName());
|
|
2085 if( obj != null )
|
|
2086 factory.saveExportData(this,obj);
|
|
2087 }
|
|
2088 }
|
|
2089
|
|
2090 public NodeData getData() {
|
|
2091 NodeData data = new NodeData();
|
|
2092
|
|
2093 data.exportId = getId();
|
|
2094 data.kind = kind.toString();
|
|
2095 Person owner = getOwner();
|
|
2096 if (owner instanceof Anonymous)
|
|
2097 data.ownerAnonymousId = ((Anonymous)owner).getCookie();
|
|
2098 else
|
|
2099 data.ownerEmail = ((User) owner).getEmail();
|
|
2100 data.ownerName = owner.getName();
|
|
2101 data.subject = subject;
|
|
2102 data.message = getMessage().getRaw();
|
|
2103 data.msgFmt = getMessage().getFormat().getCode();
|
|
2104 data.whenCreated = whenCreated;
|
|
2105 data.whenUpdated = whenUpdated;
|
|
2106 data.type = type;
|
|
2107 data.messageID = messageID;
|
|
2108 data.isGuessedParent = isGuessedParent;
|
|
2109
|
|
2110 MailingListImpl mailingList = getMailingListImpl();
|
|
2111 if( mailingList != null ) {
|
|
2112 data.mlAddress = mailingList.getListAddress();
|
|
2113 data.mlUrl = mailingList.getUrl();
|
|
2114 if( data.mlUrl==null )
|
|
2115 data.mlUrl = "http://localhost";
|
|
2116 data.mlPlainTextOnly = mailingList.plainTextOnly();
|
|
2117 data.mlIgnoreNoArchive = mailingList.ignoreNoArchive();
|
|
2118 data.mlServer = mailingList.getListServer().getType();
|
|
2119 data.mlListName = mailingList.getListName();
|
|
2120 }
|
|
2121
|
|
2122 List<URL> urls = new ArrayList<URL>();
|
|
2123 Message.Format fmt = message.getFormat();
|
|
2124 if( !(fmt instanceof MailMessageFormat) ) {
|
|
2125 Html list = message.parse();
|
|
2126 Map<String,String> files = FileUpload.getFileInfo(list,this);
|
|
2127 for( String url : files.values() ) {
|
|
2128 try {
|
|
2129 urls.add( new URL(url) );
|
|
2130 } catch(MalformedURLException e) {
|
|
2131 throw new RuntimeException(e);
|
|
2132 }
|
|
2133 }
|
|
2134 }
|
|
2135 data.fileUrls = urls.toArray(new URL[0]);
|
|
2136
|
|
2137 for( ExtensionFactory<Node,?> factory : extensionFactories ) {
|
|
2138 Serializable obj = factory.getExportData(this);
|
|
2139 if( obj != null )
|
|
2140 data.extensionData.put(factory.getName(),obj);
|
|
2141 }
|
|
2142
|
|
2143 return data;
|
|
2144 }
|
|
2145
|
|
2146
|
|
2147
|
|
2148
|
|
2149
|
|
2150
|
|
2151
|
|
2152
|
|
2153 private static final String EXPORT_TASK = "export";
|
|
2154
|
|
2155 private static class LazyExports {
|
|
2156 static {
|
|
2157 try {
|
|
2158 for( SiteKey siteKey : SiteKey.getSiteKeys(EXPORT_TASK) ) {
|
|
2159 Connection con = siteKey.getDb().getConnection();
|
|
2160 try {
|
|
2161 Statement stmt = con.createStatement();
|
|
2162 ResultSet rs = stmt.executeQuery(
|
|
2163 "select * from node"
|
|
2164 +" where export_permalink is not null"
|
|
2165 );
|
|
2166 while( rs.next() ) {
|
|
2167 // Put the task back because the export hasn't finished yet and
|
|
2168 // it should keep trying until everything has moved. Since the node
|
|
2169 // is deleted at the end of the export, the SQL above will not find any
|
|
2170 // node to be migrated when the export finishes. So this task loop will
|
|
2171 // finally come to an end.
|
|
2172 siteKey.site().addTask(EXPORT_TASK);
|
|
2173
|
|
2174 NodeImpl node = getNode(siteKey,rs);
|
|
2175 // Logs node/site ids because we may need this in the shell.
|
|
2176 logger.error("Export restarted for node=" + node.getId() + " [site=" + node.getSite().getId() + ']');
|
|
2177 // Continue exporting...
|
|
2178 node.doExport();
|
|
2179 }
|
|
2180 rs.close();
|
|
2181 stmt.close();
|
|
2182 } finally {
|
|
2183 con.close();
|
|
2184 }
|
|
2185 }
|
|
2186 } catch(SQLException e) {
|
|
2187 throw new RuntimeException(e);
|
|
2188 }
|
|
2189 }
|
|
2190 static void start() {}
|
|
2191 }
|
|
2192
|
|
2193 static {
|
|
2194 Executors.schedule(
|
|
2195 new Runnable(){public void run(){
|
|
2196 LazyExports.start();
|
|
2197 }}, 200, TimeUnit.SECONDS
|
|
2198 );
|
|
2199 }
|
|
2200
|
|
2201 public void export(String permalink,String email) {
|
|
2202 LazyExports.start();
|
|
2203 setExport(permalink,email);
|
|
2204 doExport();
|
|
2205 }
|
|
2206
|
|
2207 private void setExport(String permalink,String email) {
|
|
2208 if( exportPermalink != null )
|
|
2209 throw new RuntimeException("already set");
|
|
2210 this.exportPermalink = permalink;
|
|
2211 getDbRecord().fields().put("export_permalink",exportPermalink);
|
|
2212 this.exportEmail = email;
|
|
2213 getDbRecord().fields().put("export_email",exportEmail);
|
|
2214 getDbRecord().update();
|
|
2215 getSiteImpl().addTask(EXPORT_TASK);
|
|
2216 }
|
|
2217
|
|
2218 /* to be called from luan shell */
|
|
2219 public void clearExport() {
|
|
2220 if( exportPermalink == null )
|
|
2221 throw new RuntimeException("already cleared");
|
|
2222 this.exportPermalink = null;
|
|
2223 getDbRecord().fields().put("export_permalink",DbNull.STRING);
|
|
2224 this.exportEmail = null;
|
|
2225 getDbRecord().fields().put("export_email",DbNull.STRING);
|
|
2226 getDbRecord().update();
|
|
2227 }
|
|
2228
|
|
2229 /* to be called from luan shell */
|
|
2230 public static void clearExportedNodeIds(Node node) {
|
|
2231 if (node.getExportedNodeId() > 0) {
|
|
2232 node.getDbRecord().fields().put( "exported_node_id", DbNull.INTEGER );
|
|
2233 node.getDbRecord().update();
|
|
2234 for (Node child : node.getChildren()) {
|
|
2235 clearExportedNodeIds(child);
|
|
2236 }
|
|
2237 }
|
|
2238 }
|
|
2239
|
|
2240 private void doExport() {
|
|
2241 final Export export;
|
|
2242 try {
|
|
2243 export = new Export(this, exportPermalink, exportEmail);
|
|
2244 } catch(IOException e) {
|
|
2245 throw new RuntimeException(e);
|
|
2246 }
|
|
2247 Executors.executeNow(new Runnable(){public void run(){
|
|
2248 export.run();
|
|
2249 //clearExport();
|
|
2250 }});
|
|
2251 }
|
|
2252
|
|
2253
|
|
2254
|
|
2255
|
|
2256 private Map<ExtensionFactory<Node,?>,Object> extensionMap;
|
|
2257
|
|
2258 public synchronized Map<ExtensionFactory<Node, ?>, Object> getExtensionMap() {
|
|
2259 if (extensionMap == null)
|
|
2260 extensionMap = new HashMap<ExtensionFactory<Node, ?>, Object>();
|
|
2261 return extensionMap;
|
|
2262 }
|
|
2263
|
|
2264 public <T> T getExtension(ExtensionFactory<Node,T> factory) {
|
|
2265 synchronized(getExtensionMap()) {
|
|
2266 Object obj = extensionMap.get(factory);
|
|
2267 if( obj == null ) {
|
|
2268 obj = factory.construct(this);
|
|
2269 if( obj != null )
|
|
2270 extensionMap.put(factory,obj);
|
|
2271 }
|
|
2272 return factory.extensionClass().cast(obj);
|
|
2273 }
|
|
2274 }
|
|
2275
|
|
2276 private static Collection<ExtensionFactory<Node,?>> extensionFactories = new CopyOnWriteArrayList<ExtensionFactory<Node,?>>();
|
|
2277
|
|
2278 static <T> void addExtensionFactory(ExtensionFactory<Node,T> factory) {
|
|
2279 extensionFactories.add(factory);
|
|
2280 Db.clearCache();
|
|
2281 }
|
|
2282
|
|
2283
|
|
2284
|
|
2285 private final Memoizer<String,String> propertyCache = new Memoizer<String,String>(new Computable<String,String>() {
|
|
2286 public String get(String key) {
|
|
2287 try {
|
|
2288 Connection con = db().getConnection();
|
|
2289 PreparedStatement stmt = con.prepareStatement(
|
|
2290 "select value from node_property where node_id = ? and key = ?"
|
|
2291 );
|
|
2292 stmt.setLong( 1, getId() );
|
|
2293 stmt.setString( 2, key );
|
|
2294 ResultSet rs = stmt.executeQuery();
|
|
2295 try {
|
|
2296 return rs.next() ? rs.getString("value") : null;
|
|
2297 } finally {
|
|
2298 rs.close();
|
|
2299 stmt.close();
|
|
2300 con.close();
|
|
2301 }
|
|
2302 } catch(SQLException e) {
|
|
2303 throw new RuntimeException(e);
|
|
2304 }
|
|
2305 }
|
|
2306 });
|
|
2307
|
|
2308 public String getProperty(String key) {
|
|
2309 return propertyCache.get(key);
|
|
2310 }
|
|
2311
|
|
2312 public void setProperty(String key,String value) {
|
|
2313 try {
|
|
2314 Connection con = db().getConnection();
|
|
2315 PreparedStatement stmt = con.prepareStatement(
|
|
2316 "delete from node_property where node_id = ? and key = ?"
|
|
2317 );
|
|
2318 stmt.setLong( 1, getId() );
|
|
2319 stmt.setString( 2, key );
|
|
2320 stmt.executeUpdate();
|
|
2321 stmt.close();
|
|
2322 if( value != null ) {
|
|
2323 stmt = con.prepareStatement(
|
|
2324 "insert into node_property (node_id,key,value) values (?,?,?)"
|
|
2325 );
|
|
2326 stmt.setLong( 1, getId() );
|
|
2327 stmt.setString( 2, key );
|
|
2328 stmt.setString( 3, value );
|
|
2329 stmt.executeUpdate();
|
|
2330 stmt.close();
|
|
2331 }
|
|
2332 con.close();
|
|
2333 } catch(SQLException e) {
|
|
2334 throw new RuntimeException(e);
|
|
2335 } finally {
|
|
2336 propertyCache.remove(key);
|
|
2337 }
|
|
2338 }
|
|
2339
|
|
2340
|
|
2341 final Memoizer<String,Boolean> tagCache = new Memoizer<String,Boolean>(new Computable<String,Boolean>() {
|
|
2342 public Boolean get(String sqlCondition) {
|
|
2343 return TagImpl.countTags(siteKey,sqlCondition) > 0;
|
|
2344 }
|
|
2345 });
|
|
2346
|
|
2347 }
|