Project

General

Profile

1
package eu.dnetlib.openaire.api;
2

    
3
import java.io.StringReader;
4
import java.util.Iterator;
5
import java.util.List;
6

    
7
import com.mongodb.*;
8
import eu.dnetlib.miscutils.datetime.DateUtils;
9
import org.apache.commons.logging.Log;
10
import org.apache.commons.logging.LogFactory;
11
import org.dom4j.io.SAXReader;
12
import org.springframework.beans.factory.annotation.Required;
13

    
14
/**
15
 * Created by michele on 11/11/15.
16
 */
17
public class RecentPublicationsQueue implements Iterable<String> {
18

    
19
	private static final Log log = LogFactory.getLog(RecentPublicationsQueue.class);
20

    
21
	private DB db;
22
	private String collection;
23

    
24
	public void init() {
25
		if (!db.collectionExists(collection)) {
26
			log.info(String.format("creating collection %s", collection));
27
			db.createCollection(collection, new BasicDBObject());
28
		}
29
	}
30

    
31
	@Override
32
	public Iterator<String> iterator() {
33

    
34
		final DBCursor cursor = db.getCollection(collection).find();
35

    
36
		return new Iterator<String>() {
37

    
38
			@Override
39
			public boolean hasNext() {
40
				return cursor.hasNext();
41
			}
42

    
43
			@Override
44
			public String next() {
45
				final DBObject obj = cursor.next();
46
				return ((obj != null) && obj.containsField("record")) ? obj.get("record").toString() : "";
47
			}
48

    
49
			@Override
50
			public void remove() {
51
				throw new RuntimeException("NOT IMPLEMENTED");
52
			}
53
		};
54
	}
55

    
56
	synchronized public void add(final String oaf) throws Exception {
57
		final String id = (new SAXReader()).read(new StringReader(oaf)).valueOf("//*[local-name() = 'objIdentifier']");
58

    
59
		log.info("Saving record " + id + " in db: " + db.getName() + ", coll: " + collection);
60

    
61
		final DBCollection coll = db.getCollection(collection);
62
		final DBObject obj = BasicDBObjectBuilder.start()
63
				.append("id", id)
64
				.append("record", oaf)
65
				.append("date", DateUtils.now())
66
				.get();
67
		coll.update(new BasicDBObject("id", id), obj, true, false);
68
	}
69

    
70
	public void remove(final List<String> list) {
71
		final DBCollection coll = db.getCollection(collection);
72
		for (final String id : list) {
73
			coll.remove(new BasicDBObject("id", id));
74
		}
75
	}
76

    
77
	public DB getDb() {
78
		return db;
79
	}
80

    
81
	@Required
82
	public void setDb(final DB db) {
83
		this.db = db;
84
	}
85

    
86
	public String getCollection() {
87
		return collection;
88
	}
89

    
90
	@Required
91
	public void setCollection(final String collection) {
92
		this.collection = collection;
93
	}
94
}
(1-1/3)