Project

General

Profile

« Previous | Next » 

Revision 56309

[maven-release-plugin] copy for tag dnet-s3-objectStore-2.0.1

View differences:

modules/dnet-s3-objectStore/tags/dnet-s3-objectStore-2.0.1/deploy.info
1
{"type_source": "SVN", "goal": "package -U -T 4C source:jar", "url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet45/modules/dnet-s3-objectStore/trunk/", "deploy_repository": "dnet45-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/dnet45-snapshots", "name": "dnet-s3-objectStore"}
modules/dnet-s3-objectStore/tags/dnet-s3-objectStore-2.0.1/src/test/java/eu/dnetlib/data/objectStore/S3/S3ObjectStoreTest.java
1
package eu.dnetlib.data.objectStore.S3;
2

  
3
import com.amazonaws.ClientConfiguration;
4
import com.amazonaws.Protocol;
5
import com.amazonaws.auth.AWSCredentials;
6
import com.amazonaws.auth.AWSStaticCredentialsProvider;
7
import com.amazonaws.auth.BasicAWSCredentials;
8
import com.amazonaws.client.builder.AwsClientBuilder;
9
import com.amazonaws.services.s3.AmazonS3;
10
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
11
import com.amazonaws.services.s3.model.*;
12
import org.junit.Ignore;
13
import org.junit.Test;
14

  
15
import java.util.List;
16

  
17
public class S3ObjectStoreTest {
18

  
19

  
20
    private static final String S3_REGION = "eu-west-3";
21

  
22

  
23
    @Ignore
24
    public void testConnection() {
25

  
26

  
27
        String s3AccessKey = "API";
28
        String s3SecretKey = "SECRET";
29
        String s3EndPoint = "s3.icm.edu.pl";
30
        final AWSCredentials credentials = new BasicAWSCredentials(s3AccessKey, s3SecretKey);
31
        final ClientConfiguration cfg = new ClientConfiguration().withProtocol(Protocol.HTTPS);
32

  
33
        final AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials))
34
                .withClientConfiguration(cfg)
35
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(s3EndPoint, S3_REGION))
36
                .build();
37

  
38
    ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
39
        List<Bucket> buckets = s3.listBuckets(listBucketsRequest);
40
        buckets.stream().forEach(x -> System.out.println(x.getName()));
41

  
42

  
43
        S3Object object = s3.getObject("openaire-mdstore-beta", "fe6b7e2f-273e-4222-a72a-9d3159326318_T2JqZWN0U3RvcmVEU1Jlc291cmNlcy9PYmplY3RTdG9yZURTUmVzb3VyY2VUeXBl/shareLawArXv::ff18bafffc8ff53da0eb07960b32a9dd::bc6bfd352c354ed64b276f1ae5995041");
44
        System.out.println(object.getObjectMetadata().getETag());
45

  
46
        System.out.println(object.getObjectMetadata().getContentLength());
47

  
48

  
49
//        ObjectMetadata objectMetadata = s3.getObjectMetadata("openaire-mdstore-beta", "fe6b7e2f-273e-4222-a72a-9d3159326318_T2JqZWN0U3RvcmVEU1Jlc291cmNlcy9PYmplY3RTdG9yZURTUmVzb3VyY2VUeXBl/shareLawArXv::ff18bafffc8ff53da0eb07960b32a9dd::bc6bfd352c354ed64b276f1ae5995041");
50
//
51
//        System.out.println(objectMetadata.getContentMD5());
52

  
53

  
54

  
55

  
56
    }
57
}
modules/dnet-s3-objectStore/tags/dnet-s3-objectStore-2.0.1/src/main/java/eu/dnetlib/data/objectstore/s3/ModularObjectStoreRESTService.java
1
package eu.dnetlib.data.objectstore.s3;
2

  
3
import java.io.*;
4
import java.net.URLEncoder;
5
import java.nio.file.Files;
6
import java.nio.file.Path;
7
import javax.servlet.http.HttpServletResponse;
8

  
9
import com.amazonaws.ClientConfiguration;
10
import com.amazonaws.Protocol;
11
import com.amazonaws.auth.AWSCredentials;
12
import com.amazonaws.auth.AWSStaticCredentialsProvider;
13
import com.amazonaws.auth.BasicAWSCredentials;
14
import com.amazonaws.client.builder.AwsClientBuilder;
15
import com.amazonaws.services.s3.AmazonS3;
16
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
17
import com.amazonaws.services.s3.model.S3Object;
18
import eu.dnetlib.data.objectstore.rmi.ObjectStoreServiceException;
19
import eu.dnetlib.miscutils.datetime.HumanTime;
20
import org.apache.commons.io.IOUtils;
21
import org.apache.commons.logging.Log;
22
import org.apache.commons.logging.LogFactory;
23
import org.springframework.beans.factory.annotation.Value;
24
import org.springframework.stereotype.Controller;
25
import org.springframework.web.bind.annotation.RequestMapping;
26
import org.springframework.web.bind.annotation.RequestParam;
27

  
28
/**
29
 * The Class ModularObjectStoreRESTService implement the controller REST of the object Store.
30
 */
31
@Controller
32
public class ModularObjectStoreRESTService {
33

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

  
36

  
37

  
38
    @Value("${dnet.objectStore.s3.accessKey}")
39
    private String accessKey;
40

  
41

  
42
    @Value("${dnet.objectStore.s3.secretKey}")
43
    private String secretKey;
44

  
45
    @Value("${dnet.objectStore.s3.endPoint}")
46
    private String s3EndPoint;
47

  
48
    @Value("${dnet.objectStore.s3.objectStoreBucket}")
49
    private String objectStoreBucket;
50

  
51
    private AmazonS3 client;
52

  
53
    private static final String S3_REGION = "eu-west-3";
54

  
55

  
56
    private AmazonS3 initializeClient() throws ObjectStoreServiceException {
57
        try {
58
            final AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
59
            final ClientConfiguration cfg = new ClientConfiguration().withProtocol(Protocol.HTTPS);
60
            final AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials))
61
                    .withClientConfiguration(cfg)
62
                    .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(this.s3EndPoint, S3_REGION))
63
                    .build();
64
            if (s3 == null)
65
                throw new ObjectStoreServiceException("Cannot initialize s3 client because is NULL");
66
            return s3;
67
        } catch (Throwable e) {
68
            log.error("An Error happen on initialize client ", e);
69
            throw new ObjectStoreServiceException("Cannot initialize s3 client", e);
70
        }
71
    }
72

  
73

  
74
    public static String retrieveURL(final String baseURI, final String basePath, final String objectStoreId, final String objectId)
75
            throws UnsupportedEncodingException {
76
        final StringBuilder sb = new StringBuilder(baseURI)
77
                .append("?objectStore=" + encode(objectStoreId))
78
                .append("&objectId=" + encode(objectId))
79
                .append("&basePath=" + encode(basePath));
80
        return sb.toString();
81
    }
82

  
83
    private static String encode(final String s) throws UnsupportedEncodingException {
84
        return URLEncoder.encode(s, "UTF-8");
85
    }
86

  
87
    /**
88
     *
89
     * @param res
90
     * @param objectStoreId
91
     * @param objectId
92
     * @throws IOException
93
     * @throws ObjectStoreServiceException
94
     */
95
    @RequestMapping(value = "/**/objectStore/retrieve.do")
96
    public void retrieve(final HttpServletResponse res,
97
                         @RequestParam(value = "objectStore", required = true) final String objectStoreId,
98
                         @RequestParam(value = "objectId", required = true) final String objectId) throws IOException, ObjectStoreServiceException {
99

  
100
        final long start = System.currentTimeMillis();
101
        if (client == null)
102
            client = initializeClient();
103
        final S3Object object = this.client.getObject(objectStoreBucket, objectStoreId + "/" + objectId);
104

  
105

  
106

  
107
        if (object == null) {
108
            final String msg = String.format("Object with identifier: %s not found the in %s", objectId, objectStoreId);
109
            res.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
110
            log.warn(msg);
111
        } else {
112
            try ( final InputStream is =  object.getObjectContent()) {
113

  
114
                res.setHeader("Content-Length", String.valueOf(object.getObjectMetadata().getContentLength()));
115
                IOUtils.copyLarge(is, res.getOutputStream());
116
                if (log.isDebugEnabled()) {
117
                    log.debug(String.format("retrive.do completed in %s, objId: %s", HumanTime.exactly(System.currentTimeMillis() - start), objectId));
118
                }
119
            } catch (IOException e) {
120
                final String msg = "unable to close input Stream";
121
                res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
122
                log.error(msg, e);
123
            }
124
        }
125
    }
126
}
modules/dnet-s3-objectStore/tags/dnet-s3-objectStore-2.0.1/src/main/java/eu/dnetlib/data/objectstore/s3/MongoS3OptionsFactory.java
1
package eu.dnetlib.data.objectstore.s3;
2

  
3
import com.mongodb.MongoClientOptions;
4
import org.springframework.beans.BeansException;
5
import org.springframework.beans.factory.FactoryBean;
6

  
7
public class MongoS3OptionsFactory implements FactoryBean<MongoClientOptions> {
8

  
9
	private int connectionsPerHost;
10

  
11
	@Override
12
	public MongoClientOptions getObject() throws BeansException {
13
		return MongoClientOptions.builder().connectionsPerHost(connectionsPerHost).build();
14
	}
15

  
16
	@Override
17
	public Class<MongoClientOptions> getObjectType() {
18
		return MongoClientOptions.class;
19
	}
20

  
21
	@Override
22
	public boolean isSingleton() {
23
		return false;
24
	}
25

  
26
	public int getConnectionsPerHost() {
27
		return connectionsPerHost;
28
	}
29

  
30
	public void setConnectionsPerHost(final int connectionsPerHost) {
31
		this.connectionsPerHost = connectionsPerHost;
32
	}
33

  
34
}
modules/dnet-s3-objectStore/tags/dnet-s3-objectStore-2.0.1/src/main/java/eu/dnetlib/data/objectstore/s3/S3ObjectStore.java
1
package eu.dnetlib.data.objectstore.s3;
2

  
3
import com.amazonaws.ClientConfiguration;
4
import com.amazonaws.Protocol;
5
import com.amazonaws.auth.AWSCredentials;
6
import com.amazonaws.auth.AWSStaticCredentialsProvider;
7
import com.amazonaws.auth.BasicAWSCredentials;
8
import com.amazonaws.client.builder.AwsClientBuilder;
9
import com.amazonaws.services.s3.AmazonS3;
10
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
11
import com.amazonaws.services.s3.model.ListObjectsV2Request;
12
import com.amazonaws.services.s3.model.ListObjectsV2Result;
13
import com.amazonaws.services.s3.model.S3Object;
14
import com.amazonaws.services.s3.model.S3ObjectSummary;
15
import com.google.common.collect.Lists;
16
import com.mongodb.client.MongoCollection;
17
import com.mongodb.client.model.Filters;
18
import eu.dnetlib.data.objectstore.modular.ObjectStoreRecord;
19
import eu.dnetlib.data.objectstore.modular.connector.ObjectStore;
20
import eu.dnetlib.data.objectstore.rmi.MetadataObjectRecord;
21
import eu.dnetlib.data.objectstore.rmi.ObjectStoreFile;
22
import eu.dnetlib.data.objectstore.rmi.ObjectStoreServiceException;
23
import eu.dnetlib.enabling.resultset.ResultSetListener;
24
import org.apache.commons.lang3.StringUtils;
25
import org.apache.commons.lang3.tuple.ImmutableTriple;
26
import org.apache.commons.lang3.tuple.Triple;
27
import org.apache.commons.logging.Log;
28
import org.apache.commons.logging.LogFactory;
29
import org.bson.Document;
30
import org.apache.commons.lang3.exception.ExceptionUtils;
31

  
32

  
33
import java.io.*;
34
import java.nio.file.Files;
35
import java.nio.file.Path;
36
import java.nio.file.StandardCopyOption;
37
import java.util.concurrent.atomic.AtomicInteger;
38
import java.util.regex.Pattern;
39

  
40
public class S3ObjectStore implements ObjectStore {
41

  
42
    //CONSTANT VARIABLE NAME
43
    private static final String S3_REGION = "eu-west-3";
44
    private static final String URI_FIELD = "uri";
45
    private static final String ID_FIELD = "id";
46
    private static final String MIME_FIELD = "mime";
47
    private static final String ORIGINAL_OBJECT_FIELD = "originalObject";
48
    private static final String TIMESTAMP_FIELD = "timestamp";
49
    private static final String MD5_FIELD = "md5Sum";
50
    private static final String SIZE_FIELD = "size";
51

  
52

  
53
    private final String id;
54
    private final String interpretation;
55

  
56
    private final String s3AccessKey;
57
    private final String s3SecretKey;
58
    private final String s3EndPoint;
59
    private final String objectStoreBucket;
60

  
61

  
62
    private final MongoCollection<Document> mongoCollection;
63

  
64
    private AmazonS3 client;
65

  
66
    private static final Log log = LogFactory.getLog(S3ObjectStore.class);
67

  
68
    public S3ObjectStore(final String identifier, final String interpretation, final String s3AccessKey, final String s3SecretKey, final String s3EndPoint, final String objectStoreBucket, final MongoCollection<Document> mongoCollection) throws ObjectStoreServiceException {
69
        this.id = identifier;
70
        this.interpretation = interpretation;
71
        this.s3AccessKey = s3AccessKey;
72
        this.s3SecretKey = s3SecretKey;
73
        this.mongoCollection = mongoCollection;
74
        this.s3EndPoint = s3EndPoint;
75
        this.objectStoreBucket = objectStoreBucket;
76
    }
77

  
78

  
79
    private AmazonS3 initializeClient() throws ObjectStoreServiceException {
80
        try {
81
            final AWSCredentials credentials = new BasicAWSCredentials(this.s3AccessKey, this.s3SecretKey);
82
            final ClientConfiguration cfg = new ClientConfiguration().withProtocol(Protocol.HTTPS);
83
            final AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials))
84
                    .withClientConfiguration(cfg)
85
                    .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(this.s3EndPoint, S3_REGION))
86
                    .build();
87
            if (s3 == null)
88
                throw new ObjectStoreServiceException("Cannot initialize s3 client because is NULL");
89
            return s3;
90
        } catch (Throwable e) {
91
            log.error("An Error happen on initialize client ", e);
92
            throw new ObjectStoreServiceException("Cannot initialize s3 client", e);
93
        }
94
    }
95

  
96

  
97
    @Override
98
    public String getId() {
99
        return this.id;
100
    }
101

  
102
    @Override
103
    public String getInterpretation() {
104
        return this.interpretation;
105
    }
106

  
107
    @Override
108
    public int feed(Iterable<ObjectStoreRecord> iterable, boolean upsert) throws ObjectStoreServiceException {
109
        final AtomicInteger count = new AtomicInteger();
110
        iterable.forEach(objectStoreRecord -> {
111
            try {
112
                feedObjectRecord(objectStoreRecord);
113
                count.incrementAndGet();
114
            } catch (ObjectStoreServiceException e) {
115
                log.error("Error on saving file in a temporary Folder");
116
            }
117
        });
118
        return count.intValue();
119
    }
120

  
121
    @Override
122
    public int feedMetadataRecord(Iterable<MetadataObjectRecord> iterable, boolean b) throws ObjectStoreServiceException {
123
        final AtomicInteger count = new AtomicInteger();
124
        iterable.forEach(mor -> {
125
            final ObjectStoreRecord r = new ObjectStoreRecord();
126
            r.setInputStream(new ByteArrayInputStream(mor.getRecord().getBytes()));
127
            final ObjectStoreFile fileMetadata = new ObjectStoreFile();
128
            fileMetadata.setObjectID(mor.getId());
129
            fileMetadata.setMimeType(mor.getMime());
130
            r.setFileMetadata(fileMetadata);
131
            try {
132
                feedObjectRecord(r);
133
                count.incrementAndGet();
134
            } catch (ObjectStoreServiceException e) {
135
                log.error("Unable to store record r", e);
136
            }
137
        });
138
        return count.intValue();
139
    }
140

  
141
    @Override
142
    public String feedObjectRecord(ObjectStoreRecord objectStoreRecord) throws ObjectStoreServiceException {
143
        if (client == null)
144
            this.client = initializeClient();
145
        try {
146
            long start = System.currentTimeMillis();
147
            if (objectStoreRecord!= null && objectStoreRecord.getInputStream()!= null ) {
148
                log.debug("Saving object with ID: " + objectStoreRecord.getFileMetadata().getObjectID() + " on s3 ");
149
                this.client.putObject(objectStoreBucket, id + "/" + objectStoreRecord.getFileMetadata().getObjectID(), objectStoreRecord.getInputStream(), null);
150
                final S3Object s3Object = this.client.getObject(objectStoreBucket ,id+ "/" + objectStoreRecord.getFileMetadata().getObjectID());
151
                log.debug("Total time to put into the ObjectStore " + (System.currentTimeMillis() - start));
152
                log.debug("Saved object on s3 ");
153
                double timestamp = System.currentTimeMillis();
154
                Document metadata = new Document()
155
                        .append(ID_FIELD, objectStoreRecord.getFileMetadata().getObjectID())
156
                        .append(MIME_FIELD, objectStoreRecord.getFileMetadata().getMimeType())
157
                        .append(ORIGINAL_OBJECT_FIELD, objectStoreRecord.getFileMetadata().toJSON())
158
                        .append(TIMESTAMP_FIELD, timestamp)
159
                        .append(MD5_FIELD, s3Object.getObjectMetadata().getETag())
160
                        .append(SIZE_FIELD, s3Object.getObjectMetadata().getContentLength())
161
                        .append(URI_FIELD, String.format("s3://%s/%s/%s", objectStoreBucket, id, objectStoreRecord.getFileMetadata().getObjectID()));
162
                log.debug("saving metadata object to the collection: " + metadata.toString());
163
                start = System.currentTimeMillis();
164
                mongoCollection.insertOne(metadata);
165
                log.debug("Total time to save in Mongo " + (System.currentTimeMillis() - start));
166

  
167
            }
168
        } catch (Throwable e) {
169
            log.error("Error on put file in the objectStore", e);
170
            log.error(ExceptionUtils.getStackTrace(e));
171
            throw new ObjectStoreServiceException(e);
172

  
173
        }
174
        return null;
175
    }
176

  
177
    @Override
178
    public ResultSetListener deliver(final Long from, final Long until) throws ObjectStoreServiceException {
179
        S3ObjectStoreResultSetListener resultSet = new S3ObjectStoreResultSetListener();
180
        resultSet.setMongoCollection(this.mongoCollection);
181
        resultSet.setObjectStoreID(getId());
182
        resultSet.setFromDate(from);
183
        resultSet.setUntilDate(until);
184
        return resultSet;
185
    }
186

  
187
    @Override
188
    public ResultSetListener deliverIds(final Iterable<String> ids) throws ObjectStoreServiceException {
189
        S3ObjectStoreResultSetListener resultSet = new S3ObjectStoreResultSetListener();
190
        resultSet.setMongoCollection(this.mongoCollection);
191
        resultSet.setObjectStoreID(getId());
192
        resultSet.setRecords(Lists.newArrayList(ids));
193
        return resultSet;
194
    }
195

  
196
    @Override
197
    public ObjectStoreFile deliverObject(String objectId) throws ObjectStoreServiceException {
198
        Document resultQuery = this.mongoCollection.find(Filters.eq("id", objectId)).first();
199
        if (resultQuery!= null)
200
            return ObjectStoreS3Utility.build(resultQuery);
201
        else return null;
202
    }
203

  
204
    @Override
205
    public int getSize() throws ObjectStoreServiceException {
206
        return (int) this.mongoCollection.count();
207
    }
208

  
209
    @Override
210
    public void deleteObject(String objectId) throws ObjectStoreServiceException {
211
        final Document response =this.mongoCollection.findOneAndDelete(Filters.eq("id", objectId));
212
        if (response == null)
213
            throw new ObjectStoreServiceException("Error document not found with objectId: "+objectId);
214

  
215
        if (this.client == null)
216
            this.client = initializeClient();
217

  
218
        this.client.deleteObject(this.objectStoreBucket, String.format("%s/%s", this.id, response.get(ID_FIELD)));
219
    }
220

  
221
    @Override
222
    public String getObject(String objectId) throws ObjectStoreServiceException {
223

  
224
        Document response = this.mongoCollection.find(Filters.eq("id", objectId)).first();
225
        if (response == null || !response.containsKey(URI_FIELD))
226
            return null;
227
        return response.getString(URI_FIELD);
228
    }
229

  
230
    @Override
231
    public boolean existIDStartsWith(String startId) throws ObjectStoreServiceException {
232
        return this.mongoCollection.count(Filters.regex("id", Pattern.compile(startId))) > 0;
233
    }
234

  
235
    @Override
236
    public boolean dropContent() throws ObjectStoreServiceException {
237
        if (this.client == null) {
238
            this.client = initializeClient();
239
        }
240
        final ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(objectStoreBucket).withPrefix(id);
241
        ListObjectsV2Result result;
242
        do {
243
            result = this.client.listObjectsV2(req);
244

  
245
            for (S3ObjectSummary objectSummary : result.getObjectSummaries()) {
246
                log.debug(String.format(" - %s (size: %d)\n", objectSummary.getKey(), objectSummary.getSize()));
247
                this.client.deleteObject(objectStoreBucket, objectSummary.getKey());
248
                log.debug("Object Deleted");
249
            }
250
            String token = result.getNextContinuationToken();
251
            log.debug("Next Continuation Token: " + token);
252
            req.setContinuationToken(token);
253
        } while (result.isTruncated());
254

  
255
        this.mongoCollection.drop();
256
        return true;
257
    }
258
}
modules/dnet-s3-objectStore/tags/dnet-s3-objectStore-2.0.1/src/main/java/eu/dnetlib/data/objectstore/s3/S3ObjectStoreResultSetListener.java
1
package eu.dnetlib.data.objectstore.s3;
2

  
3
import com.google.common.collect.Lists;
4
import com.mongodb.client.FindIterable;
5
import com.mongodb.client.MongoCollection;
6
import com.mongodb.client.MongoCursor;
7
import com.mongodb.client.model.Filters;
8
import com.mongodb.client.model.Sorts;
9
import eu.dnetlib.enabling.resultset.ResultSet;
10
import eu.dnetlib.enabling.resultset.ResultSetAware;
11
import eu.dnetlib.enabling.resultset.ResultSetListener;
12
import eu.dnetlib.miscutils.collections.MappedCollection;
13
import org.apache.commons.logging.Log;
14
import org.apache.commons.logging.LogFactory;
15
import org.bson.Document;
16
import org.bson.conversions.Bson;
17

  
18
import java.util.List;
19

  
20
/**
21
 * The listener interface for receiving fileSystemObjectStoreResultSet events.
22
 * The class that is interested in processing a fileSystemObjectStoreResultSet
23
 * event implements this interface, and the object created
24
 * with that class is registered with a component using the
25
 * component's <code>addFileSystemObjectStoreResultSetListener<code> method. When
26
 * the fileSystemObjectStoreResultSet event occurs, that object's appropriate
27
 * method is invoked.
28
 *
29
 * @author sandro
30
 */
31
public class S3ObjectStoreResultSetListener implements ResultSetListener, ResultSetAware {
32

  
33

  
34
	/** The Constant log. */
35
	private static final Log log = LogFactory.getLog(S3ObjectStoreResultSetListener.class); // NOPMD by marko on 11/24/08 5:02 PM
36

  
37

  
38
	/** The from date. */
39
	private Long fromDate;
40

  
41
	/** The until date. */
42
	private Long untilDate;
43

  
44
	/** The records. */
45
	private List<String> records;
46

  
47
	/** The object store id. */
48
	private String objectStoreID;
49

  
50

  
51
	/** The mongo collection. */
52
	private MongoCollection<Document> mongoCollection;
53

  
54
	/** The base uri. */
55
	private String baseURI;
56

  
57
	/** The current size. */
58
	private int currentSize = -1;
59

  
60
	/** The current cursor. */
61
	private MongoCursor<Document> currentCursor;
62

  
63
	/** The cursor position. */
64
	private long cursorPosition;
65

  
66
	@Override
67
	public List<String> getResult(final int from, final int to) {
68
		if (log.isDebugEnabled()) {
69
			log.debug(String.format("ObjectStoreId :%s, from: %d, to: %d", objectStoreID, from, to));
70
		}
71
		if (records != null) {
72
			List<String> ids = Lists.newArrayList();
73
			for (int i = from-1; i < Math.min(records.size(),to); i++) {
74
				ids.add(records.get(i));
75
			}
76
			Bson q = Filters.in("id", ids);
77
			FindIterable<Document> res = getMongoCollection().find(q);
78
			return MappedCollection.listMap(res, ObjectStoreS3Utility.asJSON());
79
		} else if ((fromDate != null) && (untilDate != null)) {
80
			if ((currentCursor == null) || (cursorPosition > from)) {
81
				createCurrentCursor();
82
			}
83
			while (cursorPosition < from) {
84
				currentCursor.next();
85
				cursorPosition++;
86
			}
87
			List<Document> result = Lists.newArrayList();
88
			for (int i = from; i <= to; i++) {
89
				if (currentCursor.hasNext()) {
90
					result.add(currentCursor.next());
91
					cursorPosition++;
92
				}
93
			}
94
			return MappedCollection.listMap(result, ObjectStoreS3Utility.asJSON());
95
		}
96

  
97
		throw new IllegalArgumentException("Missing parameters on Delivery must provide either from, to, or ObjectStoreIDs");
98
	}
99

  
100
	/**
101
	 * Creates the current cursor.
102
	 */
103
	private void createCurrentCursor() {
104
		Bson timestampQuery = Filters.and(Filters.gt("timestamp", fromDate.doubleValue()), Filters.lt("timestamp", untilDate.doubleValue()));
105
		if (currentCursor != null) {
106
			currentCursor.close();
107
		}
108
		currentCursor = getMongoCollection().find(timestampQuery).sort(Sorts.orderBy(Filters.eq("_id", 1))).iterator();
109
		cursorPosition = 1;
110

  
111
	}
112

  
113
	@Override
114
	public int getSize() {
115
		if (currentSize == -1) {
116
			currentSize = calculateSize();
117
		}
118
		return Math.max(0, currentSize - 1);
119
	}
120

  
121
	/**
122
	 * Calculate size.
123
	 *
124
	 * @return the int
125
	 */
126
	private int calculateSize() {
127
		if (records != null) {
128
			Bson query = Filters.in("id", records);
129
			return (int) getMongoCollection().count(query);
130
		} else if ((fromDate != null) && (untilDate != null)) {
131
			Bson timestampQuery = Filters.and(Filters.gt("timestamp", fromDate.doubleValue()), Filters.lt("timestamp", untilDate.doubleValue()));
132
			return (int) getMongoCollection().count(timestampQuery);
133
		}
134
		return 0;
135
	}
136

  
137

  
138
	/**
139
	 * {@inheritDoc}
140
	 * @see ResultSetAware#setResultSet(ResultSet)
141
	 */
142
	@Override
143
	public void setResultSet(final ResultSet resultSet) {
144
		resultSet.close();
145
	}
146

  
147

  
148
	/**
149
	 * Gets the from date.
150
	 *
151
	 * @return the fromDate
152
	 */
153
	public Long getFromDate() {
154
		return fromDate;
155
	}
156

  
157

  
158
	/**
159
	 * Sets the from date.
160
	 *
161
	 * @param fromDate the fromDate to set
162
	 */
163
	public S3ObjectStoreResultSetListener setFromDate(final Long fromDate) {
164
		this.fromDate = fromDate;
165
		return this;
166
	}
167

  
168

  
169
	/**
170
	 * Gets the until date.
171
	 *
172
	 * @return the untilDate
173
	 */
174
	public Long getUntilDate() {
175
		return untilDate;
176
	}
177

  
178

  
179
	/**
180
	 * Sets the until date.
181
	 *
182
	 * @param untilDate the untilDate to set
183
	 */
184
	public S3ObjectStoreResultSetListener setUntilDate(final Long untilDate) {
185
		this.untilDate = untilDate;
186
		return this;
187
	}
188

  
189

  
190
	/**
191
	 * Gets the records.
192
	 *
193
	 * @return the records
194
	 */
195
	public List<String> getRecords() {
196
		return records;
197
	}
198

  
199

  
200
	/**
201
	 * Sets the records.
202
	 *
203
	 * @param records the records to set
204
	 */
205
	public void setRecords(final List<String> records) {
206
		this.records = records;
207
	}
208

  
209

  
210
	/**
211
	 * Gets the object store id.
212
	 *
213
	 * @return the objectStoreID
214
	 */
215
	public String getObjectStoreID() {
216
		return objectStoreID;
217
	}
218

  
219

  
220
	/**
221
	 * Sets the object store id.
222
	 *
223
	 * @param objectStoreID the objectStoreID to set
224
	 */
225
	public void setObjectStoreID(final String objectStoreID) {
226
		this.objectStoreID = objectStoreID;
227
	}
228

  
229

  
230

  
231

  
232

  
233
	/**
234
	 * Gets the base uri.
235
	 *
236
	 * @return the baseURI
237
	 */
238
	public String getBaseURI() {
239
		return baseURI;
240
	}
241

  
242

  
243
	/**
244
	 * Sets the base uri.
245
	 *
246
	 * @param baseURI the baseURI to set
247
	 */
248
	public void setBaseURI(final String baseURI) {
249
		this.baseURI = baseURI;
250
	}
251

  
252

  
253
	/**
254
	 * Gets the current size.
255
	 *
256
	 * @return the currentSize
257
	 */
258
	public int getCurrentSize() {
259
		return currentSize;
260
	}
261

  
262

  
263
	/**
264
	 * Sets the current size.
265
	 *
266
	 * @param currentSize the currentSize to set
267
	 */
268
	public void setCurrentSize(final int currentSize) {
269
		this.currentSize = currentSize;
270
	}
271

  
272

  
273
	/**
274
	 * Gets the current cursor.
275
	 *
276
	 * @return the currentCursor
277
	 */
278
	public MongoCursor<Document> getCurrentCursor() {
279
		return currentCursor;
280
	}
281

  
282

  
283
	/**
284
	 * Sets the current cursor.
285
	 *
286
	 * @param currentCursor the currentCursor to set
287
	 */
288
	public void setCurrentCursor(final MongoCursor<Document> currentCursor) {
289
		this.currentCursor = currentCursor;
290
	}
291

  
292

  
293
	/**
294
	 * Gets the cursor position.
295
	 *
296
	 * @return the cursorPosition
297
	 */
298
	public long getCursorPosition() {
299
		return cursorPosition;
300
	}
301

  
302

  
303
	/**
304
	 * Sets the cursor position.
305
	 *
306
	 * @param cursorPosition the cursorPosition to set
307
	 */
308
	public void setCursorPosition(final long cursorPosition) {
309
		this.cursorPosition = cursorPosition;
310
	}
311

  
312
	/**
313
	 * Gets the mongo collection.
314
	 *
315
	 * @return the mongo collection
316
	 */
317
	public MongoCollection<Document> getMongoCollection() {
318
		return mongoCollection;
319
	}
320

  
321
	/**
322
	 * Sets the mongo collection.
323
	 *
324
	 * @param mongoCollection the new mongo collection
325
	 */
326
	public void setMongoCollection(final MongoCollection<Document> mongoCollection) {
327
		this.mongoCollection = mongoCollection;
328
	}
329

  
330
}
modules/dnet-s3-objectStore/tags/dnet-s3-objectStore-2.0.1/src/main/java/eu/dnetlib/data/objectstore/s3/ObjectStoreS3Utility.java
1
package eu.dnetlib.data.objectstore.s3;
2

  
3
import eu.dnetlib.data.objectstore.rmi.ObjectStoreFile;
4
import eu.dnetlib.data.objectstore.rmi.Protocols;
5
import eu.dnetlib.miscutils.functional.UnaryFunction;
6
import org.apache.commons.lang3.StringUtils;
7
import org.apache.commons.logging.Log;
8
import org.apache.commons.logging.LogFactory;
9

  
10
import org.bson.Document;
11

  
12

  
13
/**
14
 * The Class ObjectStoreFileBuilder generates an objectStoreFile bean
15
 */
16
public class ObjectStoreS3Utility {
17

  
18
    private static final int KB_SIZE = 1024;
19

  
20
    /**
21
     * The Constant log.
22
     */
23
    private static final Log log = LogFactory.getLog(ObjectStoreS3Utility.class);
24

  
25
    public static ObjectStoreFile build(final Document metadata) {
26

  
27
        final String originalFile = metadata.getString("originalObject");
28
        final ObjectStoreFile original = ObjectStoreFile.createObject(originalFile);
29
        final ObjectStoreFile newFile = new ObjectStoreFile();
30
        newFile.setObjectID(metadata.getString("id"));
31
        newFile.setAccessProtocol(Protocols.None);
32
        newFile.setMimeType( metadata.getString("mime"));
33
        newFile.setMd5Sum(metadata.getString("md5Sum"));
34
        try {
35
            newFile.setFileSizeKB(Long.parseLong(metadata.get("size").toString()) / KB_SIZE);
36
        } catch (Throwable e) {
37
            log.error("Error on getting file size", e);
38
        }
39
        if (originalFile != null) {
40
            newFile.setMetadataRelatedID(original.getMetadataRelatedID());
41
            if (StringUtils.isBlank(original.getDownloadedURL())) {
42
                newFile.setDownloadedURL(original.getURI());
43
            } else {
44
                newFile.setDownloadedURL(original.getDownloadedURL());
45
            }
46
        }
47
        newFile.setURI(metadata.get("uri").toString());
48
        return newFile;
49
    }
50

  
51
    public static UnaryFunction<String, Document> asJSON() {
52
        return input -> build(input).toJSON();
53
    }
54
}
modules/dnet-s3-objectStore/tags/dnet-s3-objectStore-2.0.1/src/main/java/eu/dnetlib/data/objectstore/s3/S3ObjectStoreDao.java
1
package eu.dnetlib.data.objectstore.s3;
2

  
3
import com.mongodb.BasicDBObject;
4
import com.mongodb.client.MongoCollection;
5
import com.mongodb.client.MongoDatabase;
6
import com.mongodb.client.model.Filters;
7
import com.mongodb.client.model.IndexModel;
8
import com.mongodb.client.result.DeleteResult;
9
import com.mongodb.client.result.UpdateResult;
10
import eu.dnetlib.data.objectstore.modular.connector.ObjectStore;
11
import eu.dnetlib.data.objectstore.modular.connector.ObjectStoreDao;
12
import eu.dnetlib.data.objectstore.rmi.ObjectStoreFileNotFoundException;
13
import eu.dnetlib.data.objectstore.rmi.ObjectStoreServiceException;
14
import org.apache.commons.lang3.StringUtils;
15
import org.apache.commons.logging.Log;
16
import org.apache.commons.logging.LogFactory;
17
import org.bson.Document;
18
import org.bson.conversions.Bson;
19
import org.springframework.beans.factory.annotation.Value;
20

  
21
import javax.annotation.Resource;
22
import java.util.Arrays;
23
import java.util.List;
24
import java.util.stream.Collectors;
25
import java.util.stream.StreamSupport;
26

  
27
public class S3ObjectStoreDao implements ObjectStoreDao {
28
    public static final String INTERPRETATION_FIELD = "interpretation";
29
    public final static String OBJECTSTORE_METADATA_NAME_FIELD = "metadataObjectStore";
30
    public final static String OBJECTSTORE_ID_FIELD = "obsId";
31
    private static final String OBJECTSTORE_PROFILE_SUFFIX = "_T2JqZWN0U3RvcmVEU1Jlc291cmNlcy9PYmplY3RTdG9yZURTUmVzb3VyY2VUeXBl";
32
    private static final Log log = LogFactory.getLog(S3ObjectStoreDao.class);
33

  
34
    private static final List<IndexModel> metadataIndexes = Arrays.asList(new IndexModel(new Document().append("id",1)), new IndexModel(new Document().append("timestamp",1)));
35

  
36
    @Resource(name="objectstoreMongoDB")
37
	private MongoDatabase db;
38

  
39
    @Value("${dnet.objectStore.s3.accessKey}")
40
    private String accessKey;
41

  
42

  
43
    @Value("${dnet.objectStore.s3.secretKey}")
44
    private String secretKey;
45

  
46
    @Value("${dnet.objectStore.s3.endPoint}")
47
    private String s3EndPoint;
48

  
49
    @Value("${dnet.objectStore.s3.objectStoreBucket}")
50
    private String objectStoreBucket;
51

  
52

  
53
	private Document getObjectStoreMetadata(final String objectStoreId) {
54
        String find_id = objectStoreId;
55
        if (objectStoreId.length() == 36) {
56
            find_id += OBJECTSTORE_PROFILE_SUFFIX;
57
        }
58
        final MongoCollection<Document> metadataObjectStore = getDb().getCollection(OBJECTSTORE_METADATA_NAME_FIELD);
59
        final Bson query = Filters.eq(OBJECTSTORE_ID_FIELD, find_id);
60
        log.debug("QUERY :" + query.toString());
61
        final Document resultQuery = metadataObjectStore.find(query).first();
62
        log.debug("result " + resultQuery);
63
        return resultQuery;
64
    }
65

  
66
    @Override
67
    public ObjectStore getObjectStore(final String objectStoreId) throws ObjectStoreServiceException {
68
        if (StringUtils.isBlank(objectStoreId)) throw new ObjectStoreServiceException("Error on getting ObjectStore, id is Blank");
69
        final Document resultQuery = getObjectStoreMetadata(objectStoreId);
70
        if ((resultQuery == null)) throw new ObjectStoreFileNotFoundException("the objectStore with identifier: "+objectStoreId+" was not found");
71
        final MongoCollection<Document> collection = getDb().getCollection(objectStoreId.substring(0,36));
72
        collection.createIndexes(metadataIndexes);
73
        return new S3ObjectStore(resultQuery.getString(OBJECTSTORE_ID_FIELD),resultQuery.getString(INTERPRETATION_FIELD),accessKey, secretKey, s3EndPoint, objectStoreBucket, collection);
74
    }
75

  
76
    @Override
77
    public List<String> listObjectStores() {
78
        MongoCollection<Document> metadata = getDb().getCollection(OBJECTSTORE_METADATA_NAME_FIELD);
79
        Iterable<Document> tmp = () -> metadata.find().iterator();
80
        return StreamSupport.stream(tmp.spliterator(), false).map(it-> it.getString(OBJECTSTORE_ID_FIELD)).collect(Collectors.toList());
81
    }
82

  
83

  
84
    @Override
85
    public boolean createObjectStore(final String obsId, final String interpretation, final String basePath) throws ObjectStoreServiceException {
86
        if (getObjectStoreMetadata(obsId)!= null)
87
            throw new ObjectStoreServiceException("Error unable to create an ObjectStore that already exists in mongo");
88
        final MongoCollection<Document> metadata = getDb().getCollection(OBJECTSTORE_METADATA_NAME_FIELD);
89
        final Document item = new Document()
90
                .append(OBJECTSTORE_ID_FIELD, obsId)
91
                .append(INTERPRETATION_FIELD, interpretation);
92
        metadata.insertOne(item);
93
        MongoCollection<Document> objectStore = getDb().getCollection(obsId.substring(0, 36));
94
        objectStore.createIndex(new BasicDBObject("id", 1));
95
        objectStore.createIndex(new BasicDBObject("timestamp", 1));
96
        return true;
97
    }
98

  
99
    @Override
100
    public boolean updateObjectStore(final String obsId, final String interpretation) {
101
        MongoCollection<Document> coll = getDb().getCollection(OBJECTSTORE_METADATA_NAME_FIELD);
102
        final Document update = new Document().append("$set", new Document(INTERPRETATION_FIELD, interpretation));
103
        final UpdateResult updateResult = coll.updateOne(Filters.eq(OBJECTSTORE_ID_FIELD, obsId), update);
104
        if (updateResult.isModifiedCountAvailable()) {
105
            log.debug("Matched / Modified " + updateResult.getMatchedCount() + " / " + updateResult.getModifiedCount());
106
        }
107
        return true;
108
    }
109

  
110
    @Override
111
    public boolean deleteObjectStore(String obsId) throws ObjectStoreServiceException {
112
        final Document objectStoreMetadata = getObjectStoreMetadata(obsId);
113
        if (objectStoreMetadata== null)
114
            throw new ObjectStoreServiceException("ObjectStore not found with Identifier "+obsId);
115
        log.debug("Start to deleting all the object on the ObjectStore in teh bucket");
116
        getObjectStore(obsId.substring(0,36)).dropContent();
117
        log.debug("All object Deleted");
118
        log.debug("Deleting mongo collection");
119
        MongoCollection<Document> objectStoreCollection = db.getCollection(objectStoreMetadata.getString(OBJECTSTORE_ID_FIELD));
120
        objectStoreCollection.drop();
121
        log.debug("Deleting item on mongo metadata Collection");
122
        final MongoCollection<Document> metadata = getDb().getCollection(OBJECTSTORE_METADATA_NAME_FIELD);
123
        DeleteResult deleteResult = metadata.deleteOne(Filters.eq(OBJECTSTORE_ID_FIELD, obsId));
124
        if (deleteResult.getDeletedCount() != 1)
125
            throw new ObjectStoreServiceException("Unexpected number of Deleting object on ObjectStoreMetadata, should be 1 instead of"+deleteResult.getDeletedCount());
126
        return true;
127
    }
128

  
129
    @Override
130
    public boolean dropContent(String obsId) throws ObjectStoreServiceException {
131
        return getObjectStore(obsId).dropContent();
132
    }
133

  
134
    public MongoDatabase getDb() {
135
        return db;
136
    }
137

  
138
    public void setDb(MongoDatabase db) {
139
        this.db = db;
140
    }
141
}
modules/dnet-s3-objectStore/tags/dnet-s3-objectStore-2.0.1/src/main/resources/eu/dnetlib/data/objectsore/s3/applicationContext-s3-objectstore.properties
1
services.objectStore.mongodb.host=localhost
2
services.objectStore.mongodb.port=27017
3
services.objectStore.mongodb.db=objectStore
4
services.objectStore.mongodb.connectionsPerHost=20
modules/dnet-s3-objectStore/tags/dnet-s3-objectStore-2.0.1/src/main/resources/eu/dnetlib/data/objectsore/s3/applicationContext-s3-objectstore.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
       xmlns:p="http://www.springframework.org/schema/p"
4
       xmlns="http://www.springframework.org/schema/beans"
5
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
6

  
7
	<bean id="S3ObjectstoreDao"
8
	      class="eu.dnetlib.data.objectstore.s3.S3ObjectStoreDao"
9
	      p:db-ref="objectstoreMongoDB"/>
10

  
11

  
12

  
13
	<bean id="objectStoreMongoClient" class="com.mongodb.MongoClient">
14
		<constructor-arg index="0" type="com.mongodb.ServerAddress">
15
			<bean class="com.mongodb.ServerAddress">
16
				<constructor-arg index="0" value="${services.objectStore.mongodb.host}"/>
17
				<constructor-arg index="1" value="${services.objectStore.mongodb.port}"/>
18
			</bean>
19
		</constructor-arg>
20
		<constructor-arg index="1" type="com.mongodb.MongoClientOptions">
21
			<bean class="eu.dnetlib.data.objectstore.s3.MongoS3OptionsFactory"
22
			      p:connectionsPerHost="${services.objectStore.mongodb.connectionsPerHost}"/>
23
		</constructor-arg>
24
	</bean>
25

  
26
	<bean id="objectstoreMongoDB" factory-bean="objectStoreMongoClient" factory-method="getDatabase">
27
		<constructor-arg index="0" type="java.lang.String" value="${services.objectStore.mongodb.db}"/>
28
	</bean>
29

  
30
</beans>
modules/dnet-s3-objectStore/tags/dnet-s3-objectStore-2.0.1/pom.xml
1
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2
    <modelVersion>4.0.0</modelVersion>
3
    <parent>
4
        <groupId>eu.dnetlib</groupId>
5
        <artifactId>dnet45-parent</artifactId>
6
        <version>1.0.0</version>
7
    </parent>
8
    <groupId>eu.dnetlib</groupId>
9
    <artifactId>dnet-s3-objectStore</artifactId>
10
    <version>2.0.1</version>
11
    <scm>
12
        <developerConnection>scm:svn:https://svn.driver.research-infrastructures.eu/driver/dnet45/modules/dnet-s3-objectStore/tags/dnet-s3-objectStore-2.0.1</developerConnection>
13
    </scm>
14
    <dependencies>
15
        <dependency>
16
            <groupId>com.amazonaws</groupId>
17
            <artifactId>aws-java-sdk</artifactId>
18
            <version>1.11.478</version>
19
        </dependency>
20

  
21
        <dependency>
22
            <groupId>eu.dnetlib</groupId>
23
            <artifactId>dnet-modular-objectstore-service</artifactId>
24
            <version>[5.0.0,6.0.0)</version>
25
        </dependency>
26
        <dependency>
27
            <groupId>eu.dnetlib</groupId>
28
            <artifactId>cnr-resultset-service</artifactId>
29
            <version>[2.0.0,3.0.0)</version>
30
        </dependency>
31
        <dependency>
32
            <groupId>eu.dnetlib</groupId>
33
            <artifactId>cnr-resultset-client</artifactId>
34
            <version>[2.0.0,3.0.0)</version>
35
        </dependency>
36
        <dependency>
37
            <groupId>junit</groupId>
38
            <artifactId>junit</artifactId>
39
            <version>${junit.version}</version>
40
            <scope>test</scope>
41
        </dependency>
42
        <dependency>
43
            <groupId>org.mongodb</groupId>
44
            <artifactId>mongo-java-driver</artifactId>
45
            <version>${mongodb.driver.version}</version>
46
        </dependency>
47
        <dependency>
48
            <groupId>javax.servlet</groupId>
49
            <artifactId>javax.servlet-api</artifactId>
50
            <version>${javax.servlet.version}</version>
51
            <scope>provided</scope>
52
        </dependency>
53

  
54
    </dependencies>
55
</project>

Also available in: Unified diff