Project

General

Profile

« Previous | Next » 

Revision 34743

[maven-release-plugin] copy for tag cnr-mongo-mdstore-4.1.5

View differences:

modules/cnr-mongo-mdstore/tags/cnr-mongo-mdstore-4.1.5/deploy.info
1
{"type_source": "SVN", "goal": "package -U -T 4C source:jar", "url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet40/modules/cnr-mongo-mdstore/trunk/", "deploy_repository": "dnet4-snapshots", "version": "4", "mail": "sandro.labruzzo@isti.cnr.it,michele.artini@isti.cnr.it, claudio.atzori@isti.cnr.it, alessia.bardi@isti.cnr.it", "deploy_repository_url": "http://maven.research-infrastructures.eu/nexus/content/repositories/dnet4-snapshots", "name": "cnr-mongo-mdstore"}
modules/cnr-mongo-mdstore/tags/cnr-mongo-mdstore-4.1.5/src/test/java/eu/dnetlib/data/mdstore/modular/mongodb/FeedSpeedTest.java
1
package eu.dnetlib.data.mdstore.modular.mongodb;
2

  
3
import java.io.File;
4
import java.io.FileInputStream;
5
import java.io.IOException;
6
import java.util.Iterator;
7
import java.util.UUID;
8

  
9
import org.apache.commons.io.IOUtils;
10
import org.junit.Ignore;
11
import org.junit.Test;
12
import org.junit.runner.RunWith;
13
import org.springframework.beans.factory.annotation.Autowired;
14
import org.springframework.core.io.ClassPathResource;
15
import org.springframework.test.context.ContextConfiguration;
16
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
17

  
18
import com.mongodb.DB;
19

  
20
import eu.dnetlib.data.mdstore.MDStoreServiceException;
21
import eu.dnetlib.data.mdstore.modular.RecordParser;
22
import eu.dnetlib.data.mdstore.modular.connector.MDStoreDao;
23
import eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager;
24

  
25
@Ignore
26
@RunWith(SpringJUnit4ClassRunner.class)
27
@ContextConfiguration(classes = ConfigurationTestConfig.class)
28
public class FeedSpeedTest {
29

  
30
	private static final int N_RECORDS = 68271;
31

  
32
	@Autowired
33
	private DB db;
34

  
35
	@Autowired
36
	private MDStoreTransactionManager manager;
37

  
38
	@Autowired
39
	private MDStoreDao dao;
40

  
41
	@Autowired
42
	private RecordParser recordParser;
43

  
44
	@Ignore
45
	@Test
46
	public void testSpeedFromFolder() throws IOException {
47
		Iterable<String> iterable = new Iterable<String>() {
48

  
49
			private int counter = 0;
50
			private double last = System.currentTimeMillis();
51

  
52
			@Override
53
			public Iterator<String> iterator() {
54
				return new Iterator<String>() {
55

  
56
					@Override
57
					public boolean hasNext() {
58
						return counter < N_RECORDS;
59
					}
60

  
61
					@Override
62
					public String next() {
63
						if (counter % 10000 == 0) {
64
							System.out.println("10K records processed in " + (System.currentTimeMillis() - last) / 1000 + " seconds");
65
							last = System.currentTimeMillis();
66
						}
67

  
68
						File f = new File(String.format("/var/lib/eagle/content/EDH/HD%06d.xml", counter++));
69
						if (f.exists()) {
70
							try {
71
								FileInputStream fileInputStream = new FileInputStream(f);
72
								String s = IOUtils.toString(fileInputStream);
73
								fileInputStream.close();
74
								return s;
75
							} catch (Exception e) {
76
								return null;
77
							}
78
						} else {
79
							try {
80
								FileInputStream fileInputStream = new FileInputStream(new File("/var/lib/eagle/content/EDH/HD000001.xml"));
81
								String s = IOUtils.toString(fileInputStream);
82
								fileInputStream.close();
83
								return s;
84
							} catch (Exception e) {
85
								return null;
86
							}
87
						}
88
					}
89

  
90
					@Override
91
					public void remove() {}
92
				};
93
			}
94
		};
95

  
96
		MongoMDStore mdStore = new MongoMDStore(UUID.randomUUID().toString(), db.getCollection("speed_test"), recordParser, true);
97
		mdStore.feed(iterable, false);
98
	}
99

  
100
	@Ignore
101
	@Test
102
	public void testFeedSpeedFromTemplate() throws MDStoreServiceException, IOException {
103
		MongoMDStore mdStore = new MongoMDStore(UUID.randomUUID().toString(), db.getCollection("speed_test"), recordParser, false);
104
		mdStore.feed(new Iterable<String>() {
105

  
106
			private int counter = 0;
107
			private double last = System.currentTimeMillis();
108
			private String templateRecord = IOUtils.toString(new ClassPathResource("/eu/dnetlib/data/mdstore/modular/mongodb/templateRecord.xml")
109
					.getInputStream());
110

  
111
			@Override
112
			public Iterator<String> iterator() {
113
				return new Iterator<String>() {
114

  
115
					@Override
116
					public boolean hasNext() {
117
						return counter < N_RECORDS;
118
					}
119

  
120
					@Override
121
					public String next() {
122
						if (counter % 10000 == 0) {
123
							System.out.println("10K records processed in " + (System.currentTimeMillis() - last) / 1000 + " seconds");
124
							last = System.currentTimeMillis();
125
						}
126

  
127
						File f = new File(String.format("/var/lib/eagle/content/EDH/HD%06d.xml", counter++));
128
						if (f.exists()) {
129
							try {
130
								FileInputStream fileInputStream = new FileInputStream(f);
131
								String s = IOUtils.toString(fileInputStream);
132
								fileInputStream.close();
133
								return s;
134
							} catch (Exception e) {
135
								return null;
136
							}
137
						} else {
138
							counter++;
139
							try {
140
								FileInputStream fileInputStream = new FileInputStream(new File("/var/lib/eagle/content/EDH/HD000009.xml"));
141
								String s = IOUtils.toString(fileInputStream);
142
								fileInputStream.close();
143
								return s;
144
							} catch (Exception e) {
145
								return null;
146
							}
147
						}
148
					}
149

  
150
					@Override
151
					public void remove() {}
152
				};
153
			}
154
		}, false);
155
	}
156
}
modules/cnr-mongo-mdstore/tags/cnr-mongo-mdstore-4.1.5/src/test/java/eu/dnetlib/data/mdstore/modular/mongodb/ConfigurationTestConfig.java
1
package eu.dnetlib.data.mdstore.modular.mongodb;
2

  
3
import java.net.UnknownHostException;
4

  
5
import org.springframework.context.annotation.Bean;
6
import org.springframework.context.annotation.Configuration;
7

  
8
import com.mongodb.DB;
9
import com.mongodb.Mongo;
10
import com.mongodb.MongoClient;
11

  
12
import eu.dnetlib.data.mdstore.modular.RecordParser;
13
import eu.dnetlib.data.mdstore.modular.RecordParserFactory;
14
import eu.dnetlib.data.mdstore.modular.StreamingRecordParser;
15
import eu.dnetlib.data.mdstore.modular.connector.MDStoreDao;
16
import eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager;
17

  
18
@Configuration
19
public class ConfigurationTestConfig {
20

  
21
	@Bean
22
	public DB db() throws UnknownHostException {
23
		final Mongo mongo = new MongoClient("localhost", 27017);
24
		return mongo.getDB("mdstore");
25
	}
26

  
27
	@Bean
28
	public MDStoreTransactionManager manager() throws UnknownHostException {
29
		final MDStoreTransactionManagerImpl manager = new MDStoreTransactionManagerImpl();
30
		manager.setDb(db());
31
		return manager;
32
	}
33

  
34
	@Bean
35
	public RecordParser recordParser() {
36
		final RecordParserFactory rpfactory = new RecordParserFactory();
37
		rpfactory.setParserType(StreamingRecordParser.class);
38
		return rpfactory.newInstance();
39
	}
40

  
41
	@Bean
42
	public MDStoreDao mdstoreDao() throws UnknownHostException {
43
		final MDStoreDaoImpl dao = new MDStoreDaoImpl();
44
		dao.setDb(db());
45
		dao.setRecordParser(recordParser());
46
		return dao;
47
	}
48

  
49
}
modules/cnr-mongo-mdstore/tags/cnr-mongo-mdstore-4.1.5/src/test/java/eu/dnetlib/data/mdstore/modular/mongodb/MDStoreTransactionManagerTest.java
1
package eu.dnetlib.data.mdstore.modular.mongodb;
2

  
3
import java.net.UnknownHostException;
4
import java.util.ArrayList;
5
import java.util.List;
6
import java.util.UUID;
7

  
8
import org.junit.Assert;
9
import org.junit.Ignore;
10
import org.junit.runner.RunWith;
11
import org.springframework.beans.factory.annotation.Autowired;
12
import org.springframework.test.context.ContextConfiguration;
13
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
14

  
15
import com.mongodb.DB;
16
import com.mongodb.DBCollection;
17
import com.mongodb.DBCursor;
18
import com.mongodb.Mongo;
19

  
20
import eu.dnetlib.data.mdstore.MDStoreServiceException;
21
import eu.dnetlib.data.mdstore.modular.connector.MDStore;
22
import eu.dnetlib.data.mdstore.modular.connector.MDStoreDao;
23
import eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager;
24

  
25
// TODO: reimplement tests
26
@Ignore
27
@RunWith(SpringJUnit4ClassRunner.class)
28
@ContextConfiguration(classes = ConfigurationTestConfig.class)
29
public class MDStoreTransactionManagerTest {
30

  
31
	@Autowired
32
	private DB db;
33

  
34
	@Autowired
35
	private MDStoreTransactionManager manager;
36

  
37
	@Autowired
38
	private MDStoreDao dao;
39

  
40
	@Ignore
41
	public void testCreateandRetrieve() throws MDStoreServiceException {
42
		UUID idCreation = UUID.randomUUID();
43
		db.getCollection("metadataManager").drop();
44
		((MDStoreTransactionManagerImpl) manager).setManagerTable(null);
45

  
46
		String mdId = idCreation.toString() + "_TURTdG9yZURTUmVzb3VyY2VzL01EU3RvcmVEU1Jlc291cmNlVHlwZQ==";
47
		manager.createMDStore(mdId);
48

  
49
		Assert.assertNotNull(manager.startTransaction(mdId, true));
50
		Assert.assertNotNull(manager.startTransaction(mdId, true));
51

  
52
		String s = manager.getMDStoreCollection(mdId);
53
		Assert.assertNotNull(s);
54
		this.manager.dropMDStore(mdId);
55
		s = null;
56
		try {
57
			s = manager.getMDStoreCollection(mdId);
58
		} catch (Exception e) {
59

  
60
		}
61
		Assert.assertNull(s);
62
		db.getCollection("metadataManager").drop();
63
		((MDStoreTransactionManagerImpl) manager).setManagerTable(null);
64
	}
65

  
66
	@Ignore
67
	public void testReadMdStore() throws MDStoreServiceException {
68
		UUID idCreation = UUID.randomUUID();
69
		String mdId = idCreation.toString() + "_TURTdG9yZURTUmVzb3VyY2VzL01EU3RvcmVEU1Jlc291cmNlVHlwZQ==";
70
		manager.createMDStore(mdId);
71
		Assert.assertNotNull(manager.readMdStore(mdId));
72
		Assert.assertNotNull(manager.startTransaction(mdId, true));
73
		Assert.assertNotNull(manager.readMdStore(mdId));
74
		db.getCollection("metadataManager").drop();
75
		((MDStoreTransactionManagerImpl) manager).setManagerTable(null);
76
		db.getCollection("metadataManager").drop();
77
		((MDStoreTransactionManagerImpl) manager).setManagerTable(null);
78

  
79
	}
80

  
81
	@Ignore
82
	public void testCommit() throws MDStoreServiceException {
83
		UUID idCreation = UUID.randomUUID();
84
		String mdId = idCreation.toString() + "_TURTdG9yZURTUmVzb3VyY2VzL01EU3RvcmVEU1Jlc291cmNlVHlwZQ==";
85
		manager.createMDStore(mdId);
86
		String idCurrent = manager.readMdStore(mdId);
87
		String transaction = manager.startTransaction(mdId, true);
88
		// Assert.assertTrue(manager.commit(transaction, mdId));
89
		Assert.assertNotSame(idCurrent, manager.readMdStore(mdId));
90

  
91
	}
92

  
93
	@Ignore
94
	public void testDateTime() throws MDStoreServiceException, UnknownHostException {
95
		Mongo mongo = new Mongo("localhost", 27017);
96
		DB dbinput = mongo.getDB("mdstore");
97
		DBCollection inputCollection = dbinput.getCollection("70e07e9f-b3bf-4423-8777-b159819e0c6a");
98

  
99
		Assert.assertNotNull(inputCollection.findOne().get("body"));
100
		UUID idCreation = UUID.randomUUID();
101

  
102
		String mdId = idCreation.toString() + "_TURTdG9yZURTUmVzb3VyY2VzL01EU3RvcmVEU1Jlc291cmNlVHlwZQ==";
103

  
104
		manager.createMDStore(mdId);
105
		dao.createMDStore(mdId, "a", "a", "a");
106

  
107
		String transId = manager.startTransaction(mdId, true);
108

  
109
		ArrayList<String> data = new ArrayList<String>();
110
		DBCursor cursor = inputCollection.find();
111

  
112
		for (int i = 0; i < 1000; i++) {
113
			data.add((String) cursor.next().get("body"));
114
		}
115
		dao.getMDStore(transId).feed(data, true);
116
		// manager.commit(transId, mdId);
117

  
118
		cursor = inputCollection.find();
119
		transId = manager.startTransaction(mdId, false);
120

  
121
		data.clear();
122
		for (int i = 0; i < 10; i++) {
123
			data.add(cursor.next().get("body").toString().replace("oai:pumaoai.isti.cnr.it:", "SUUUCAAA"));
124
		}
125

  
126
		String currentId = manager.readMdStore(mdId);
127

  
128
		final MDStore newMdstore = dao.getMDStore(currentId);
129

  
130
		new Thread(new Runnable() {
131

  
132
			@Override
133
			public void run() {
134
				List<String> dataInput = newMdstore.deliver("", "", null).getResult(0, 10);
135
				for (int i = 0; i < 10; i++) {
136
					try {
137
						Thread.sleep(1000);
138
					} catch (InterruptedException e) {
139
						// TODO Auto-generated catch block
140
						e.printStackTrace();
141
					}
142
					System.out.println(dataInput.get(i));
143
				}
144

  
145
			}
146
		}).start();
147

  
148
		dao.getMDStore(transId).feed(data, true);
149
		// manager.commit(transId, mdId);
150

  
151
	}
152
}
modules/cnr-mongo-mdstore/tags/cnr-mongo-mdstore-4.1.5/src/test/resources/eu/dnetlib/data/mdstore/modular/mongodb/templateRecord.xml
1
<oai:record xmlns="http://namespace.openaire.eu/"
2
  xmlns:dc="http://purl.org/dc/elements/1.1/"
3
  xmlns:dr="http://www.driver-repository.eu/namespace/dr"
4
  xmlns:dri="http://www.driver-repository.eu/namespace/dri"
5
  xmlns:oai="http://www.openarchives.org/OAI/2.0/"
6
  xmlns:prov="http://www.openarchives.org/OAI/2.0/provenance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
7
  <oai:header>
8
    <dri:objIdentifier>{id}</dri:objIdentifier>
9
    <dri:recordIdentifier>entityId:2533216</dri:recordIdentifier>
10
    <dri:dateOfCollection>2015-01-09T12:15:02.177+01:00</dri:dateOfCollection>
11
    <dri:repositoryId>8e17a4fe-b77d-406b-8c75-4cfa233092d2_UmVwb3NpdG9yeVNlcnZpY2VSZXNvdXJjZXMvUmVwb3NpdG9yeVNlcnZpY2VSZXNvdXJjZVR5cGU=</dri:repositoryId>
12
    <dri:datasourceprefix>DAI</dri:datasourceprefix>
13
  </oai:header>
14
  <oai:metadata>
15
    <eagle:eagleObject xmlns:eagle="http://www.eagle-network.eu/eagle">
16
      <eagle:recordSourceInfo
17
        landingPage="http://arachne.uni-koeln.de/entity/2533216" providerName="Arachne">entityId:2533216</eagle:recordSourceInfo>
18
      <eagle:editingInfo>
19
        <eagle:dateEdited>0000-00-00</eagle:dateEdited>
20
        <eagle:metadataEditor>unknown</eagle:metadataEditor>
21
      </eagle:editingInfo>
22
      <eagle:metadataIpr uri="http://creativecommons.org/licenses/by/3.0/">This file is licensed under the Creative Commons Attribution 3.0 Unported license.</eagle:metadataIpr>
23
      <eagle:title lang="de">CMS-XII-d009c-3_168111,02.jpg</eagle:title>
24
      <!-- objekt http://arachne.uni-koeln.de/entity/1160926 -->
25
      <eagle:description lang="de">Foto von: Siegel CMS XII D009c</eagle:description>
26
      <eagle:entityType>visual</eagle:entityType>
27
      <eagle:visualRepresentation>
28
        <eagle:representationType>image</eagle:representationType>
29
        <eagle:url>http://arachne.uni-koeln.de/entity/2533216</eagle:url>
30
        <eagle:thumbnail>http://arachne.dainst.org/data/image/thumbnail/2533216</eagle:thumbnail>
31
        <eagle:visualRepresentationIpr uri="http://creativecommons.org/licenses/by/3.0/">This file is licensed under the Creative Commons Attribution 3.0 Unported license.</eagle:visualRepresentationIpr>
32
        <eagle:format>jpg</eagle:format>
33
        <!-- objekt http://arachne.uni-koeln.de/entity/1160926 -->
34
        <eagle:hasArtifact>
35
          <eagle:artifactTitle>Siegel CMS XII D009c</eagle:artifactTitle>
36
          <eagle:objectType>Dreiseitiges Prisma Mallia Steatitgruppe</eagle:objectType>
37
          <eagle:material>weicher Stein</eagle:material>
38
        </eagle:hasArtifact>
39
      </eagle:visualRepresentation>
40
    </eagle:eagleObject>
41
  </oai:metadata>
42
</oai:record>
modules/cnr-mongo-mdstore/tags/cnr-mongo-mdstore-4.1.5/src/main/java/eu/dnetlib/mongodb/MongoOptionsFactory.java
1
package eu.dnetlib.mongodb;
2

  
3
import org.springframework.beans.BeansException;
4
import org.springframework.beans.factory.FactoryBean;
5

  
6
import com.mongodb.MongoOptions;
7

  
8
public class MongoOptionsFactory implements FactoryBean<MongoOptions> {
9
	private int connectionsPerHost;
10

  
11
	@Override
12
	public MongoOptions getObject() throws BeansException {
13
		MongoOptions opts = new MongoOptions();
14
		opts.connectionsPerHost = connectionsPerHost;
15
		return opts;
16
	}
17

  
18
	@Override
19
	public Class<MongoOptions> getObjectType() {
20
		return MongoOptions.class;
21
	}
22

  
23
	@Override
24
	public boolean isSingleton() {
25
		return false;
26
	}
27

  
28
	public int getConnectionsPerHost() {
29
		return connectionsPerHost;
30
	}
31

  
32
	public void setConnectionsPerHost(int connectionsPerHost) {
33
		this.connectionsPerHost = connectionsPerHost;
34
	}
35

  
36
}
0 37

  
modules/cnr-mongo-mdstore/tags/cnr-mongo-mdstore-4.1.5/src/main/java/eu/dnetlib/data/mdstore/modular/mongodb/MDStoreTransactionManagerImpl.java
1
package eu.dnetlib.data.mdstore.modular.mongodb;
2

  
3
import java.util.Collections;
4
import java.util.Date;
5
import java.util.List;
6
import java.util.Set;
7

  
8
import org.apache.commons.lang.StringUtils;
9
import org.apache.commons.logging.Log;
10
import org.apache.commons.logging.LogFactory;
11
import org.joda.time.DateTime;
12
import org.joda.time.Days;
13
import org.springframework.beans.factory.annotation.Required;
14

  
15
import com.google.common.collect.Lists;
16
import com.mongodb.BasicDBList;
17
import com.mongodb.BasicDBObject;
18
import com.mongodb.DB;
19
import com.mongodb.DBCollection;
20
import com.mongodb.DBCursor;
21
import com.mongodb.DBObject;
22
import com.mongodb.QueryBuilder;
23
import com.mongodb.WriteConcern;
24

  
25
import eu.dnetlib.data.mdstore.MDStoreServiceException;
26
import eu.dnetlib.data.mdstore.modular.connector.MDStore;
27
import eu.dnetlib.data.mdstore.modular.connector.MDStoreExpiredInfo;
28
import eu.dnetlib.data.mdstore.modular.connector.MDStoreManagerInfo;
29
import eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionInfo;
30
import eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager;
31
import eu.dnetlib.data.mdstore.modular.mongodb.utils.MDStoreUtils;
32

  
33
/**
34
 * The Class MDStoreTransactionManager.
35
 */
36
public class MDStoreTransactionManagerImpl implements MDStoreTransactionManager {
37

  
38
	/** The Constant log. */
39
	private static final Log log = LogFactory.getLog(MDStoreTransactionManagerImpl.class);
40

  
41
	/**
42
	 * The table name.
43
	 */
44
	private static String TABLE_NAME = "metadataManager";
45

  
46
	/** The max number of concurrent transactions per mdstore. */
47
	private int maxTransactions = 1;
48

  
49
	/**
50
	 * The db.
51
	 */
52

  
53
	private DB db;
54

  
55
	/**
56
	 * The manager table.
57
	 */
58
	private DBCollection managerTable;
59

  
60
	/** The expired days. */
61
	private int expiredDays;
62

  
63
	/**
64
	 * Bootstrap manager.
65
	 */
66
	private void bootstrapManager() {
67
		log.debug("Bootstrap Manager start");
68
		final DBCollection metadataColl = db.getCollection("metadata");
69
		final DBCursor values = metadataColl.find();
70
		this.setManagerTable(db.getCollection(TABLE_NAME));
71
		while (values.hasNext()) {
72
			final DBObject object = values.next();
73
			final String id = (String) object.get("mdId");
74
			String newId = null;
75
			if (id.contains("_")) {
76

  
77
				newId = StringUtils.substringBefore(id, "_");
78
			}
79

  
80
			final BasicDBObject input = new BasicDBObject();
81
			input.put("mdId", id);
82
			input.put("currentId", newId);
83
			input.put("expiring", new String[] {});
84
			input.put("transactions", new String[] {});
85
			getManagerTable().insert(input);
86
			log.debug(String.format("Added %s to Metadata Manager data structure", id));
87

  
88
		}
89
		final BasicDBObject ensureIndex = new BasicDBObject();
90
		ensureIndex.put("mdId", 1);
91
		log.debug("Create index in MetadaManager ");
92
		this.getManagerTable().createIndex(ensureIndex);
93
	}
94

  
95
	/**
96
	 * Verify consistency.
97
	 * 
98
	 * @throws MDStoreServiceException
99
	 *             the MD store service exception
100
	 */
101
	@Override
102
	public void verifyConsistency() throws MDStoreServiceException {
103
		if (this.getManagerTable() == null) {
104
			if (!db.collectionExists(TABLE_NAME)) {
105
				bootstrapManager();
106
				if (this.getManagerTable() == null) throw new MDStoreServiceException("Something bad happen, unable to create managerTable");
107
			} else {
108
				this.setManagerTable(db.getCollection(TABLE_NAME));
109
			}
110
		}
111
	}
112

  
113
	/**
114
	 * {@inheritDoc}
115
	 * 
116
	 * @see eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager#createMDStore(java.lang.String)
117
	 */
118
	@Override
119
	public void createMDStore(final String mdId) throws MDStoreServiceException {
120
		log.debug("Creating new mdstore");
121
		verifyConsistency();
122
		String newId = mdId;
123
		if (mdId.contains("_")) {
124
			newId = StringUtils.substringBefore(mdId, "_");
125
		}
126
		final BasicDBObject instance = new BasicDBObject();
127
		instance.put("mdId", mdId);
128
		instance.put("currentId", newId);
129
		instance.put("expiring", new String[] {});
130
		getManagerTable().insert(instance);
131
		this.getManagerTable().save(instance);
132
	}
133

  
134
	/**
135
	 * {@inheritDoc}
136
	 * 
137
	 * @see eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager#dropMDStore(java.lang.String)
138
	 */
139
	@Override
140
	public void dropMDStore(final String mdId) throws MDStoreServiceException {
141
		verifyConsistency();
142
		log.debug("Droping MDStore: " + mdId);
143
		final BasicDBObject query = new BasicDBObject();
144
		query.put("mdId", mdId);
145
		final DBCursor cursor = this.getManagerTable().find(query);
146
		if (cursor.hasNext() == false) return;
147
		final DBObject item = cursor.next();
148
		garbage();
149
		final String collectionName = (String) item.get("currentId");
150
		this.db.getCollection(collectionName).drop();
151
		this.db.getCollection("discarded-" + collectionName).drop();
152
		this.getManagerTable().remove(query);
153

  
154
	}
155

  
156
	/**
157
	 * {@inheritDoc}
158
	 * 
159
	 * @see eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager#getMDStoreCollection(java.lang.String)
160
	 */
161
	@Override
162
	public String getMDStoreCollection(final String mdId) throws MDStoreServiceException {
163
		verifyConsistency();
164
		final BasicDBObject query = new BasicDBObject();
165
		query.put("mdId", mdId);
166
		final DBCursor cursor = this.getManagerTable().find(query);
167
		if (cursor.hasNext() == false) {
168
			log.error("Error, unable to find Mdstore with Id " + mdId);
169
			throw new MDStoreServiceException("Error, unable to find Mdstore with Id " + mdId);
170
		}
171
		return (String) cursor.next().get("currentId");
172
	}
173

  
174
	/**
175
	 * {@inheritDoc}
176
	 * 
177
	 * @see eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager#startTransaction(java.lang.String, boolean)
178
	 */
179
	@Override
180
	public String startTransaction(final String mdId, final boolean refresh) throws MDStoreServiceException {
181
		verifyConsistency();
182
		log.info("Start transaction for metadata store " + mdId);
183
		final BasicDBObject query = new BasicDBObject();
184
		query.put("mdId", mdId);
185
		final DBCursor cursor = this.getManagerTable().find(query);
186
		if (cursor.hasNext() == false) throw new MDStoreServiceException("Error, unable to find Mdstore with Id " + mdId);
187

  
188
		String idCreation = StringUtils.substringBefore(mdId, "_");
189

  
190
		idCreation = idCreation + "::" + System.currentTimeMillis();
191
		final DBObject object = cursor.next();
192

  
193
		BasicDBList values;
194
		if (object.containsField("transactions")) {
195
			values = (BasicDBList) object.get("transactions");
196
			if (values.size() > getMaxTransactions())
197
				throw new MDStoreServiceException("Cannot create more than " + getMaxTransactions() + " transactions, found: " + values.size() + ", mdId:"
198
						+ mdId);
199
		} else {
200
			values = new BasicDBList();
201
			object.put("transactions", values);
202
		}
203
		final BasicDBObject transactionMetadata = new BasicDBObject();
204
		transactionMetadata.put("id", idCreation.toString());
205
		transactionMetadata.put("refresh", refresh);
206
		transactionMetadata.put("date", new Date());
207
		values.add(transactionMetadata);
208
		this.getManagerTable().save(object);
209
		return idCreation.toString();
210
	}
211

  
212
	/**
213
	 * {@inheritDoc}
214
	 * 
215
	 * @see eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager#commit(java.lang.String, java.lang.String,
216
	 *      eu.dnetlib.data.mdstore.modular.connector.MDStore)
217
	 */
218
	@Override
219
	public boolean commit(final String transactionId, final String mdstoreId, final MDStore current) throws MDStoreServiceException {
220
		verifyConsistency();
221
		final BasicDBObject query = new BasicDBObject();
222
		query.put("mdId", mdstoreId);
223
		final DBCursor cursor = this.getManagerTable().find(query);
224
		if (cursor.hasNext() == false) throw new MDStoreServiceException("Error, unable to find Mdstore with Id " + mdstoreId);
225
		final DBObject object = cursor.next();
226
		final BasicDBList transactions = (BasicDBList) object.get("transactions");
227
		final DBObject transaction = findTransaction(transactions, transactionId);
228
		if (transaction == null) throw new MDStoreServiceException("Error, unable to find transaction with Id " + transactionId);
229
		final boolean refresh = (Boolean) transaction.get("refresh");
230
		transactions.remove(transaction);
231
		final String oldId = (String) object.get("currentId");
232
		if (refresh) {
233
			object.put("currentId", transactionId);
234
			final BasicDBList stillUsed = (BasicDBList) object.get("expiring");
235
			if (stillUsed.size() == 0) {
236
				db.getCollection(oldId).drop();
237
				db.getCollection("discarded-" + oldId).drop();
238
			}
239
			log.debug("Replaced collection ");
240
		} else {
241
			log.debug("commit incremental ");
242
			updateIncremental(transactionId, oldId);
243
			db.getCollection(transactionId).drop();
244
			db.getCollection("discarded-" + transactionId).drop();
245
		}
246
		this.managerTable.save(object);
247

  
248
		log.info("Committed transaction for metadata store " + mdstoreId);
249
		return true;
250
	}
251

  
252
	/**
253
	 * Find transaction.
254
	 * 
255
	 * @param transactions
256
	 *            the transactions
257
	 * @param transactionId
258
	 *            the transaction id
259
	 * @return the DB object
260
	 */
261
	private DBObject findTransaction(final BasicDBList transactions, final String transactionId) {
262
		if (transactions.size() == 0) return null;
263
		for (int i = 0; i < transactions.size(); i++) {
264
			final BasicDBObject transaction = (BasicDBObject) transactions.get(i);
265
			final String id = (String) transaction.get("id");
266
			if (transactionId.equals(id)) return transaction;
267
		}
268
		return null;
269

  
270
	}
271

  
272
	/**
273
	 * Gets the db.
274
	 * 
275
	 * @return the db
276
	 */
277
	public DB getDb() {
278
		return db;
279
	}
280

  
281
	/**
282
	 * Sets the db.
283
	 * 
284
	 * @param db
285
	 *            the db to set
286
	 */
287
	@Required
288
	public void setDb(final DB db) {
289
		this.db = db;
290
	}
291

  
292
	/**
293
	 * {@inheritDoc}
294
	 * 
295
	 * @see eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager#readMdStore(java.lang.String)
296
	 */
297
	@Override
298
	public String readMdStore(final String mdStoreId) throws MDStoreServiceException {
299
		verifyConsistency();
300
		final BasicDBObject query = new BasicDBObject();
301
		query.put("mdId", mdStoreId);
302
		final DBCursor cursor = this.getManagerTable().find(query);
303
		if (cursor.hasNext() == false) throw new MDStoreServiceException("Error, unable to find Mdstore with Id " + mdStoreId);
304
		final DBObject object = cursor.next();
305
		final String currentId = (String) object.get("currentId");
306
		final BasicDBList values = (BasicDBList) object.get("expiring");
307
		updateMdstoreUsed(values, currentId);
308
		this.getManagerTable().save(object);
309
		return currentId;
310

  
311
	}
312

  
313
	/**
314
	 * Update mdstore used.
315
	 * 
316
	 * @param values
317
	 *            the values
318
	 * @param mdId
319
	 *            the md id
320
	 */
321
	private void updateMdstoreUsed(final BasicDBList values, final String mdId) {
322
		if (values.size() > 0) {
323
			for (int i = 0; i < values.size(); i++) {
324
				final DBObject obj = (DBObject) values.get(i);
325
				final String id = (String) obj.get("id");
326
				if (mdId.equals(id)) {
327
					obj.put("lastRead", new Date());
328
					return;
329
				}
330
			}
331
		}
332
		final BasicDBObject readStore = new BasicDBObject();
333
		readStore.put("id", mdId);
334
		readStore.put("lastRead", new Date());
335
		values.add(readStore);
336
	}
337

  
338
	/**
339
	 * Gets the manager table.
340
	 * 
341
	 * @return the managerTable
342
	 */
343
	public DBCollection getManagerTable() {
344
		return managerTable;
345
	}
346

  
347
	/**
348
	 * Sets the manager table.
349
	 * 
350
	 * @param managerTable
351
	 *            the managerTable to set
352
	 */
353
	public void setManagerTable(final DBCollection managerTable) {
354
		this.managerTable = managerTable;
355
	}
356

  
357
	/*
358
	 * (non-Javadoc)
359
	 * 
360
	 * @see eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager#getInfoForCurrentMdStore(java.lang.String)
361
	 */
362
	@Override
363
	public MDStoreManagerInfo getInfoForCurrentMdStore(final String mdStoreId) throws MDStoreServiceException {
364
		verifyConsistency();
365
		final BasicDBObject query = new BasicDBObject();
366
		query.put("mdId", mdStoreId);
367
		final DBCursor cursor = this.getManagerTable().find(query);
368
		if (cursor.hasNext() == false) throw new MDStoreServiceException("Error, unable to find Mdstore with Id " + mdStoreId);
369
		final DBObject object = cursor.next();
370
		final MDStoreManagerInfo result = new MDStoreManagerInfo();
371
		result.setCurrentId((String) object.get("currentId"));
372
		result.setMdId((String) object.get("mdId"));
373
		final BasicDBList values = (BasicDBList) object.get("expiring");
374
		for (int i = 0; i < values.size(); i++) {
375
			final MDStoreExpiredInfo stillused = new MDStoreExpiredInfo();
376
			final DBObject value = (DBObject) values.get(i);
377
			stillused.setId((String) value.get("id"));
378
			stillused.setLastRead((Date) value.get("lastRead"));
379
			result.addExpiredItem(stillused);
380
		}
381
		final BasicDBList transactions = (BasicDBList) object.get("transactions");
382
		if (transactions != null) {
383
			for (int i = 0; i < transactions.size(); i++) {
384
				final MDStoreTransactionInfo transaction = new MDStoreTransactionInfo();
385
				final DBObject value = (DBObject) transactions.get(i);
386
				final String transactionId = (String) value.get("id");
387
				transaction.setId(transactionId);
388
				transaction.setDate((Date) value.get("date"));
389
				transaction.setRefresh((Boolean) value.get("refresh"));
390
				transaction.setSize(db.getCollection(transactionId).count());
391
				result.addTransactionInfo(transaction);
392
			}
393
		}
394
		return result;
395
	}
396

  
397
	/*
398
	 * (non-Javadoc)
399
	 * 
400
	 * @see eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager#dropUsed(java.lang.String, java.lang.String)
401
	 */
402
	@Override
403
	public Boolean dropUsed(final String mdId, final String idToDrop) throws MDStoreServiceException {
404
		verifyConsistency();
405
		final BasicDBObject query = new BasicDBObject();
406
		query.put("mdId", mdId);
407
		final DBCursor cursor = this.getManagerTable().find(query);
408
		if (cursor.hasNext() == false) throw new MDStoreServiceException("Error, unable to find Mdstore with Id " + mdId);
409
		final DBObject object = cursor.next();
410
		final BasicDBList values = (BasicDBList) object.get("expiring");
411
		for (int i = 0; i < values.size(); i++) {
412
			final DBObject value = (DBObject) values.get(i);
413
			final String currentUsedId = (String) value.get("id");
414
			if (currentUsedId.equals(idToDrop)) {
415
				db.getCollection(idToDrop).drop();
416
				db.getCollection("discarded-" + idToDrop).drop();
417
				values.remove(value);
418
				this.managerTable.save(object);
419
				return true;
420
			}
421
		}
422
		throw new MDStoreServiceException("Error, unable to drop old collection " + idToDrop);
423
	}
424

  
425
	/*
426
	 * (non-Javadoc)
427
	 * 
428
	 * @see eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager#garbage()
429
	 */
430
	@Override
431
	public void garbage() throws MDStoreServiceException {
432
		verifyConsistency();
433
		log.info("Start garbage collection of MdStore");
434
		final DBCursor cursor = this.managerTable.find();
435
		int totalDeleted = 0;
436
		while (cursor.hasNext()) {
437
			final DBObject currentObject = cursor.next();
438
			if (log.isDebugEnabled()) {
439
				log.debug("start to check id: " + (String) currentObject.get("currentId"));
440
			}
441
			garbageExpiring(currentObject, (String) currentObject.get("currentId"));
442
			garbageTransactions(currentObject, (String) currentObject.get("currentId"));
443
			this.managerTable.save(currentObject);
444
		}
445

  
446
		// DELETING Collection that are not in the metadataManager table
447
		Set<String> collections = this.db.getCollectionNames();
448
		for (String collection : collections) {
449
			if ((collection.length() > 30) && (collection.contains("discarded-") == false)) {
450
				final DBObject item = getMetadataObjectForCollections(collection);
451

  
452
				if (shouldDelete(collection, item)) {
453
					if (log.isDebugEnabled()) {
454
						log.debug("delete collection: " + collection + " from mongo");
455
					}
456
					db.getCollection(collection).drop();
457
					db.getCollection("discarded-" + collection).drop();
458
					if (log.isDebugEnabled()) {
459
						log.debug("delete collection: discarded-" + collection + " from mongo");
460
					}
461
				}
462
			}
463
		}
464

  
465
		log.info("Complete garbage collection of MdStore, total store deleted: " + totalDeleted);
466
	}
467

  
468
	private DBObject getMetadataObjectForCollections(final String collectionName) {
469
		if (collectionName == null) return null;
470
		final String postfix = "_TURTdG9yZURTUmVzb3VyY2VzL01EU3RvcmVEU1Jlc291cmNlVHlwZQ==";
471
		final String tmp = collectionName.contains("discarded-") == true ? StringUtils.substringAfter(collectionName, "discarded-") : collectionName;
472
		final String collectionNameCleaned = StringUtils.substringBefore(tmp, "::") + postfix;
473

  
474
		DBObject query = QueryBuilder.start("mdId").is(collectionNameCleaned).get();
475
		return this.managerTable.findOne(query);
476
	}
477

  
478
	private boolean shouldDelete(final String collectionName, final DBObject metadataManagerInstance) {
479
		String currentId = (String) metadataManagerInstance.get("currentId");
480
		if (collectionName.equals(currentId)) return false;
481
		BasicDBList expiringList = (BasicDBList) metadataManagerInstance.get("expiring");
482
		if (findInList(expiringList, collectionName, "id") == true) return false;
483
		BasicDBList transactionsList = (BasicDBList) metadataManagerInstance.get("transactions");
484
		if (findInList(transactionsList, collectionName, "id") == true) return false;
485
		return true;
486
	}
487

  
488
	private boolean findInList(final BasicDBList list, final String object, final String tagname) {
489
		if (list == null) return false;
490
		for (int i = 0; i < list.size(); i++) {
491
			DBObject currentObject = (DBObject) list.get(i);
492
			final String id = (String) currentObject.get(tagname);
493
			if (id.equals(object)) return true;
494
		}
495
		return false;
496
	}
497

  
498
	/**
499
	 * Delete.
500
	 * 
501
	 * @param list
502
	 *            the list
503
	 * @param toRemove
504
	 *            the to remove
505
	 */
506
	private void delete(final BasicDBList list, final List<DBObject> toRemove) {
507

  
508
		for (final DBObject obj : toRemove) {
509
			if (log.isDebugEnabled()) {
510
				log.debug("deleting " + obj);
511
			}
512
			list.remove(obj);
513
		}
514
	}
515

  
516
	/**
517
	 * Garbage transactions.
518
	 * 
519
	 * @param currentObject
520
	 *            the current object
521
	 * @param currentId
522
	 *            the current id
523
	 */
524
	private void garbageTransactions(final DBObject currentObject, final String currentId) {
525
		if (log.isDebugEnabled()) {
526
			log.debug("Start garbage transactions ");
527
		}
528

  
529
		final BasicDBList expiring = (BasicDBList) currentObject.get("transactions");
530
		if ((expiring == null) || (expiring.size() <= getMaxTransactions())) return;
531

  
532
		List<DBObject> expiringList = Lists.newArrayList();
533

  
534
		for (int i = 0; i < expiring.size(); i++) {
535
			final DBObject cobj = (DBObject) expiring.get(i);
536
			if (cobj != null) {
537
				expiringList.add((DBObject) expiring.get(i));
538
			}
539

  
540
		}
541

  
542
		Collections.sort(expiringList, MDStoreUtils.getComparatorOnDate());
543

  
544
		List<DBObject> toRemove = Lists.newArrayList();
545
		int i = 0;
546

  
547
		// We should remove the k item less recent
548
		// where k = numberOftotalTransaction - maxNumberOfTransaction
549
		// k = numberOfItemToRemove
550

  
551
		while (((expiringList.size() - toRemove.size()) > getMaxTransactions()) || (i < expiringList.size())) {
552
			DBObject currentObj = expiringList.get(i++);
553
			String objectId = (String) currentObj.get("id");
554
			if (!objectId.equals(currentId)) {
555
				if (log.isDebugEnabled()) {
556
					log.debug("delete collection: " + objectId + " from mongo");
557
				}
558
				db.getCollection(objectId).drop();
559
				db.getCollection("discarded-" + objectId).drop();
560
				if (log.isDebugEnabled()) {
561
					log.debug("delete collection: discarded-" + objectId + " from mongo");
562
				}
563
				toRemove.add(currentObj);
564
			} else {
565
				if (log.isDebugEnabled()) {
566
					log.debug("Cannot remove transaction " + objectId + " because is the currentId: " + currentId);
567
				}
568
			}
569
		}
570

  
571
		delete(expiring, toRemove);
572
		log.info("Deleted " + toRemove.size() + " transactions, mdStore Id:" + currentObject.get("mdId"));
573
	}
574

  
575
	/**
576
	 * Garbage expiring.
577
	 * 
578
	 * @param currentObject
579
	 *            the current object
580
	 * @param currentId
581
	 *            the current id
582
	 */
583
	private void garbageExpiring(final DBObject currentObject, final String currentId) {
584
		if (log.isDebugEnabled()) {
585
			log.debug("Start to search expiring mdstores for id: " + currentObject.get("mdId"));
586
		}
587
		final BasicDBList expiring = (BasicDBList) currentObject.get("expiring");
588
		final List<DBObject> toRemove = Lists.newArrayList();
589
		if (log.isDebugEnabled()) {
590
			if (expiring == null) {
591
				log.debug("expiring list is null");
592
			} else {
593
				log.debug("expiring list size is :" + expiring.size());
594
			}
595
		}
596
		if ((expiring == null) || (expiring.size() == 0)) {
597
			log.debug("Deleted  0  expired  collections, mdStore Id:" + currentObject.get("mdId"));
598
			return;
599
		}
600
		for (int i = 0; i < expiring.size(); i++) {
601
			final DBObject currentExpiredStore = (DBObject) expiring.get(i);
602
			final String currentUsedId = (String) currentExpiredStore.get("id");
603
			final Days d = getExpiringDays(currentExpiredStore, "lastRead");
604
			if (log.isDebugEnabled()) {
605
				log.debug("the store :" + currentId + " expired since " + d.getDays() + "days ");
606
			}
607
			// DELETE the collection where the last time they was read
608
			// is more than 3 days ago
609
			if (d.getDays() > getExpiredDays()) {
610
				if (currentUsedId.equals(currentId) == false) {
611
					db.getCollection(currentUsedId).drop();
612
					db.getCollection("discarded-" + currentUsedId).drop();
613
					log.debug("deleted collection " + currentUsedId);
614
				}
615
				toRemove.add(currentExpiredStore);
616
			}
617
		}
618
		delete(expiring, toRemove);
619
		log.debug("Deleted expired " + toRemove.size() + "collections, mdStore Id:" + currentObject.get("mdId"));
620
	}
621

  
622
	/**
623
	 * Gets the expiring days.
624
	 * 
625
	 * @param value
626
	 *            the value
627
	 * @param paramName
628
	 *            the param name
629
	 * @return the expiring days
630
	 */
631
	private Days getExpiringDays(final DBObject value, final String paramName) {
632
		final Date lastRead = (Date) value.get(paramName);
633
		final DateTime last = new DateTime(lastRead);
634
		final DateTime today = new DateTime();
635
		final Days d = Days.daysBetween(last, today);
636
		return d;
637
	}
638

  
639
	/**
640
	 * Gets the expired days.
641
	 * 
642
	 * @return the expiredDays
643
	 */
644
	public int getExpiredDays() {
645
		if (this.expiredDays == 0) return 3;
646
		return expiredDays;
647
	}
648

  
649
	/**
650
	 * Sets the expired days.
651
	 * 
652
	 * @param expiredDays
653
	 *            the expiredDays to set
654
	 */
655
	public void setExpiredDays(final int expiredDays) {
656
		this.expiredDays = expiredDays;
657
	}
658

  
659
	/**
660
	 * Update incremental.
661
	 * 
662
	 * @param transactionId
663
	 *            the transaction id
664
	 * @param currentId
665
	 *            the current id
666
	 */
667
	private void updateIncremental(final String transactionId, final String currentId) {
668
		final DBCollection transaction = db.getCollection(transactionId);
669
		final DBCollection mdstore = db.getCollection(currentId);
670
		final DBCursor cursor = transaction.find();
671
		if (!cursor.hasNext()) return;
672
		DBObject currentObj = cursor.next();
673
		while (cursor.hasNext()) {
674

  
675
			BasicDBObject newObj = new BasicDBObject();
676

  
677
			final String id = (String) currentObj.get("id");
678
			final String body = (String) currentObj.get("body");
679
			newObj.put("id", id);
680
			newObj.put("body", body);
681
			if ((id != null) && !id.isEmpty()) {
682
				mdstore.update(new BasicDBObject("id", id), newObj, true, false, WriteConcern.ACKNOWLEDGED);
683
			}
684
			currentObj = cursor.next();
685
		}
686
		mdstore.getDB().command("{fsync:1}");
687
	}
688

  
689
	/*
690
	 * (non-Javadoc)
691
	 * 
692
	 * @see eu.dnetlib.data.mdstore.modular.connector.MDStoreTransactionManager#dropTransaction(java.lang.String, java.lang.String)
693
	 */
694
	@Override
695
	public Boolean dropTransaction(final String mdId, final String idToDrop) throws MDStoreServiceException {
696
		verifyConsistency();
697
		final BasicDBObject query = new BasicDBObject();
698
		query.put("mdId", mdId);
699
		final DBCursor cursor = this.getManagerTable().find(query);
700
		if (cursor.hasNext() == false) throw new MDStoreServiceException("Error, unable to find Mdstore with Id " + mdId);
701
		final DBObject object = cursor.next();
702
		final BasicDBList values = (BasicDBList) object.get("transactions");
703
		for (int i = 0; i < values.size(); i++) {
704
			final DBObject value = (DBObject) values.get(i);
705
			final String currentUsedId = (String) value.get("id");
706
			if (currentUsedId.equals(idToDrop)) {
707
				db.getCollection(idToDrop).drop();
708
				db.getCollection("discarded-" + idToDrop).drop();
709
				values.remove(value);
710
				this.managerTable.save(object);
711
				return true;
712
			}
713
		}
714
		throw new MDStoreServiceException("Error, unable to drop old collection " + idToDrop);
715
	}
716

  
717
	public void garbageTransactionsOnStart() throws MDStoreServiceException {
718
		verifyConsistency();
719
		DBCursor cursor = this.managerTable.find();
720
		while (cursor.hasNext()) {
721
			final DBObject currentObject = cursor.next();
722
			final BasicDBList transactions = (BasicDBList) currentObject.get("transactions");
723
			if ((transactions != null) && (transactions.size() > 0)) {
724
				for (int i = 0; i < transactions.size(); i++) {
725
					final DBObject currentTransactions = (DBObject) transactions.get(i);
726
					final String id = (String) currentTransactions.get("id");
727
					db.getCollection(id).drop();
728
					db.getCollection("discarded-" + id).drop();
729
					log.debug("deleted collection " + id);
730
				}
731
				transactions.clear();
732
				this.managerTable.save(currentObject);
733
			}
734
		}
735
	}
736

  
737
	/**
738
	 * Gets the max transactions.
739
	 * 
740
	 * @return the maxTransactions
741
	 */
742
	public int getMaxTransactions() {
743
		return maxTransactions;
744
	}
745

  
746
	/**
747
	 * Sets the max transactions.
748
	 * 
749
	 * @param maxTransactions
750
	 *            the maxTransactions to set
751
	 */
752
	public void setMaxTransactions(final int maxTransactions) {
753
		this.maxTransactions = maxTransactions;
754
	}
755
}
modules/cnr-mongo-mdstore/tags/cnr-mongo-mdstore-4.1.5/src/main/java/eu/dnetlib/data/mdstore/modular/mongodb/MongoResultSetListener.java
1
package eu.dnetlib.data.mdstore.modular.mongodb;
2

  
3
import static eu.dnetlib.miscutils.collections.MappedCollection.listMap;
4

  
5
import java.util.ArrayList;
6
import java.util.List;
7
import java.util.regex.Pattern;
8

  
9
import org.apache.commons.logging.Log;
10
import org.apache.commons.logging.LogFactory;
11

  
12
import com.google.common.collect.Lists;
13
import com.mongodb.BasicDBObject;
14
import com.mongodb.DBCollection;
15
import com.mongodb.DBCursor;
16
import com.mongodb.DBObject;
17
import com.mongodb.QueryBuilder;
18

  
19
import eu.dnetlib.enabling.resultset.ResultSet;
20
import eu.dnetlib.enabling.resultset.ResultSetAware;
21
import eu.dnetlib.enabling.resultset.ResultSetListener;
22
import eu.dnetlib.miscutils.functional.UnaryFunction;
23
import eu.dnetlib.miscutils.maps.ConcurrentSizedMap;
24

  
25
public class MongoResultSetListener implements ResultSetListener,
26
		ResultSetAware {
27

  
28
	private static final Log log = LogFactory
29
			.getLog(MongoResultSetListener.class); // NOPMD by marko on 11/24/08
30
													// 5:02 PM
31

  
32
	private ConcurrentSizedMap<Integer, String> lastKeys = new ConcurrentSizedMap<Integer, String>();
33
	private final DBObject byId = new BasicDBObject("id", 1);
34

  
35
	private UnaryFunction<String, DBObject> serializer;
36
	private Pattern filter;
37
	private DBCollection collection;
38

  
39
	public MongoResultSetListener(DBCollection collection, Pattern filter,
40
			UnaryFunction<String, DBObject> serializer) {
41
		this.collection = collection;
42
		this.filter = filter;
43
		this.serializer = serializer;
44
	}
45

  
46
	@Override
47
	public List<String> getResult(int fromPosition, int toPosition) {
48
		// log.info("getting mdstore resultset " + fromPosition + ", " +
49
		// toPosition);
50

  
51
		ArrayList<DBObject> page = null;
52

  
53
		String lastKey = lastKeys.get(fromPosition);
54
		if (lastKey != null)
55
			page = continueFrom(lastKey, toPosition - fromPosition + 1);
56
		else
57
			page = fetchNew(fromPosition - 1, toPosition - fromPosition + 1);
58

  
59
		if (!page.isEmpty()) {
60
			DBObject last = page.get(page.size() - 1);
61
			lastKeys.put(toPosition + 1, (String) last.get("id"));
62
		}
63

  
64
		return listMap(page, serializer);
65
	}
66

  
67
	private ArrayList<DBObject> fetchNew(int from, int size) {
68
		// StopWatch stopWatch = new CommonsLogStopWatch(log);
69
		try {
70
			DBCursor cursor = null;
71
			if (filter != null) {
72
				DBObject query = QueryBuilder.start("body").regex(filter).get();
73
				cursor = collection.find(query).sort(byId);
74
			} else
75
				cursor = collection.find().sort(byId);
76

  
77
			return Lists.newArrayList((Iterable<DBObject>) cursor.skip(from)
78
					.limit(size));
79
		} finally {
80
			// stopWatch.stop("mongodb.list.scan");
81
		}
82
	}
83

  
84
	private ArrayList<DBObject> continueFrom(String lastKey, int size) {
85
		// StopWatch stopWatch = new CommonsLogStopWatch(log);
86
		try {
87
			if (log.isDebugEnabled())
88
				log.debug("trying to continue from previous key: " + lastKey);
89

  
90
			DBObject query = null;
91
			if (filter != null)
92
				query = QueryBuilder.start("id").greaterThan(lastKey)
93
						.and("body").regex(filter).get();
94
			else
95
				query = QueryBuilder.start("id").greaterThan(lastKey).get();
96

  
97
			final DBCursor cursor = collection.find(query).sort(byId);
98
			return Lists.newArrayList((Iterable<DBObject>) cursor.limit(size));
99
		} finally {
100
			// stopWatch.stop("mongodb.list.resume");
101
		}
102
	}
103

  
104
	@Override
105
	public int getSize() {
106
		if (filter != null) {
107
			DBObject query = QueryBuilder.start("body").regex(filter).get();
108
			return (int) collection.find(query).count();
109
		}
110
		return (int) collection.getCount();
111
	}
112

  
113
	@Override
114
	public void setResultSet(ResultSet resultSet) {
115
		resultSet.close();
116
	}
117

  
118
}
modules/cnr-mongo-mdstore/tags/cnr-mongo-mdstore-4.1.5/src/main/java/eu/dnetlib/data/mdstore/modular/mongodb/utils/EnsureIndexJob.java
1
package eu.dnetlib.data.mdstore.modular.mongodb.utils;
2

  
3
import eu.dnetlib.data.mdstore.modular.MDStoreDescription;
4
import org.apache.commons.logging.Log;
5
import org.apache.commons.logging.LogFactory;
6
import org.springframework.beans.factory.annotation.Required;
7

  
8
import eu.dnetlib.data.mdstore.MDStoreServiceException;
9
import eu.dnetlib.data.mdstore.modular.connector.MDStoreDao;
10
import eu.dnetlib.data.mdstore.modular.mongodb.MongoMDStore;
11
import eu.dnetlib.enabling.tools.AbstractSchedulable;
12

  
13
public class EnsureIndexJob extends AbstractSchedulable {
14

  
15
	private static final Log log = LogFactory.getLog(EnsureIndexJob.class); // NOPMD by marko on 11/24/08 5:02 PM
16

  
17
	private MDStoreDao dao;
18

  
19
	@Override
20
	protected void doExecute() {
21
		log.info("performing mdstore index check");
22

  
23
		try {
24
			for (MDStoreDescription mdstore : getDao().listMDStores()) {
25
				try {
26
					log.info("ensureindex for mdStoreId:" + mdstore.getId());
27
					((MongoMDStore) getDao().getMDStore(mdstore.getId())).ensureIndices();
28
				} catch (Throwable e) {
29
					log.warn("unable to reindex mdstore: " + mdstore.getId(), e);
30
				}
31
			}
32
		} catch (MDStoreServiceException e) {
33
			log.warn("unable to reindex mdstore ", e);
34
		}
35

  
36
		log.info("mdstore index check completed");
37
	}
38

  
39
	@Required
40
	public void setDao(final MDStoreDao dao) {
41
		this.dao = dao;
42
	}
43

  
44
	public MDStoreDao getDao() {
45
		return dao;
46
	}
47

  
48
}
modules/cnr-mongo-mdstore/tags/cnr-mongo-mdstore-4.1.5/src/main/java/eu/dnetlib/data/mdstore/modular/mongodb/utils/MetadataCheckJob.java
1
package eu.dnetlib.data.mdstore.modular.mongodb.utils;
2

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

  
6
import javax.xml.ws.Endpoint;
7

  
8
import org.apache.commons.logging.Log;
9
import org.apache.commons.logging.LogFactory;
10
import org.dom4j.Document;
11
import org.dom4j.DocumentException;
12
import org.dom4j.io.SAXReader;
13
import org.springframework.beans.factory.annotation.Required;
14

  
15
import com.mongodb.BasicDBObject;
16
import com.mongodb.DBCollection;
17
import com.mongodb.DBObject;
18

  
19
import eu.dnetlib.data.mdstore.MDStoreServiceException;
20
import eu.dnetlib.data.mdstore.modular.connector.MDStoreDao;
21
import eu.dnetlib.data.mdstore.modular.mongodb.MDStoreDaoImpl;
22
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
23
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
24
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
25
import eu.dnetlib.soap.EndpointReferenceBuilder;
26

  
27
public class MetadataCheckJob {
28

  
29
	private static final Log log = LogFactory.getLog(MetadataCheckJob.class); // NOPMD by marko on 11/24/08 5:02 PM
30

  
31
	/**
32
	 * service locator.
33
	 */
34
	private UniqueServiceLocator serviceLocator;
35

  
36
	/**
37
	 * {@link Endpoint}
38
	 */
39
	private Endpoint endpoint;
40

  
41
	/**
42
	 * {@link EndpointReferenceBuilder}
43
	 */
44
	private EndpointReferenceBuilder<Endpoint> eprBuilder;
45

  
46
	/**
47
	 * MDStore dao.
48
	 */
49
	private MDStoreDao dao;
50

  
51
	private boolean runOnStart;
52

  
53
	public void runOnStart() throws MDStoreServiceException {
54
		if (isRunOnStart()) {
55
			log.info("running mdStore metadata check on service start");
56
			repairMetadata();
57
		}
58
	}
59

  
60
	/**
61
	 * Job execution method.
62
	 *
63
	 * @throws MDStoreServiceException
64
	 */
65
	public void repairMetadata() throws MDStoreServiceException {
66
		DBCollection metadata = ((MDStoreDaoImpl) getDao()).getDb().getCollection("metadata");
67
		if (metadata.findOne() != null) {
68
			log.debug("mdStore metadata doesn't need to be repaired");
69
			return;
70
		}
71
		try {
72
			List<String> mdStores =
73
					serviceLocator.getService(ISLookUpService.class).quickSearchProfile(
74
							"//RESOURCE_PROFILE[" + ".//RESOURCE_TYPE/@value='MDStoreDSResourceType' and " + ".//RESOURCE_URI/@value='" + getServiceAddress()
75
							+ "']");
76

  
77
			log.debug("repairing mdstore metadata");
78

  
79
			if (mdStores != null) {
80
				for (String MDStoreProfile : mdStores) {
81
					metadata.save(getMdInfo(MDStoreProfile));
82
				}
83
			}
84

  
85
			log.debug("FINISHED repairing mdstore metadata");
86

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff