• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

openmrs / openmrs-core / 44614243903

19 Nov 2026 08:59PM UTC coverage: 69.114% (-0.2%) from 69.299%
44614243903

Pull #6841

github

web-flow
Merge 5b767c47c into 57615988d
Pull Request #6841: TRUNK-6868: Allow the session timeout to be configured (2.8.x)

24 of 27 new or added lines in 2 files covered. (88.89%)

89 existing lines in 15 files now uncovered.

26837 of 38830 relevant lines covered (69.11%)

0.69 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/api/src/main/java/org/openmrs/api/storage/S3StorageService.java
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
3
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
4
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
5
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
6
 *
7
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
8
 * graphic logo is a trademark of OpenMRS Inc.
9
 */
10

11
package org.openmrs.api.storage;
12

13
import java.io.IOException;
14
import java.io.InputStream;
15
import java.io.InterruptedIOException;
16
import java.io.UncheckedIOException;
17
import java.net.URI;
18
import java.nio.file.FileAlreadyExistsException;
19
import java.util.concurrent.CompletableFuture;
20
import java.util.concurrent.ExecutionException;
21
import java.util.stream.Stream;
22

23
import org.apache.commons.lang.StringUtils;
24
import org.openmrs.api.StorageService;
25
import org.openmrs.api.stream.StreamDataService;
26
import org.slf4j.Logger;
27
import org.slf4j.LoggerFactory;
28
import org.springframework.beans.factory.annotation.Autowired;
29
import org.springframework.beans.factory.annotation.Qualifier;
30
import org.springframework.beans.factory.annotation.Value;
31
import org.springframework.context.annotation.Conditional;
32
import org.springframework.stereotype.Service;
33
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
34
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
35
import software.amazon.awssdk.core.ResponseInputStream;
36
import software.amazon.awssdk.core.async.AsyncRequestBody;
37
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
38
import software.amazon.awssdk.core.async.BlockingInputStreamAsyncRequestBody;
39
import software.amazon.awssdk.regions.Region;
40
import software.amazon.awssdk.services.s3.S3AsyncClient;
41
import software.amazon.awssdk.services.s3.S3AsyncClientBuilder;
42
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
43
import software.amazon.awssdk.services.s3.model.DeleteObjectResponse;
44
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
45
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
46
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
47
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
48
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
49
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
50
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
51
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
52
import software.amazon.awssdk.services.s3.model.S3Exception;
53
import software.amazon.awssdk.services.s3.model.S3Object;
54
import software.amazon.awssdk.services.s3.model.S3Response;
55

56
/**
57
 * Amazon S3-based implementation of {@link StorageService}.
58
 * <p>
59
 * It uses S3AsyncClient under the hood for all operations to handle large files in the most performant way with
60
 * multipart enabled by default.
61
 * 
62
 * <p>It can be configured with the following properties: <i>storage.s3.bucketName, storage.s3.accessKeyId, 
63
 * storage.s3.secretAccessKey, storage.s3.region, storage.s3.multipartEnabled</i>
64
 * <p>
65
 * If not configured, the default bucket name is <i>'openmrs'</i>.
66
 * 
67
 * <p>
68
 * Credentials and region can also be provided by standard S3AsyncClient means. See 
69
 * <a href="https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/regions/providers/DefaultAwsRegionProviderChain.html">DefaultAwsRegionProviderChain</a>
70
 * and 
71
 * <a href="https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/DefaultCredentialsProvider.html">DefaultCredentialsProvider</a>
72
 * 
73
 * @since 2.8.0
74
 */
75
@Service
76
@Qualifier("s3")
77
@Conditional(StorageServiceCondition.class)
78
public class S3StorageService extends BaseStorageService implements StorageService {
79

UNCOV
80
    private static final Logger log = LoggerFactory.getLogger(S3StorageService.class);
×
81

82
    protected S3AsyncClient s3AsyncClient;
83
        
84
    private final String bucketName;
85

86
    @Autowired
87
    public S3StorageService(
88
     StreamDataService streamDataService,
89
        @Value("${storage.s3.accessKeyId:}") String accessKeyId,
90
        @Value("${storage.s3.secretAccessKey:}") String secretAccessKey,
91
        @Value("${storage.s3.region:}") String region,
92
                 @Value("${storage.s3.endpoint:}") String endpoint,
93
                 @Value("${storage.s3.bucketName:openmrs}") String bucketName,
94
                 @Value("${storage.s3.forcePathStyle:false}") boolean forcePathStyle,
95
            @Value("${storage.s3.multipartEnabled:true}") boolean multipartEnabled
96
    ) {
97
        super(streamDataService);
×
98
                this.bucketName = bucketName;
×
99

100
                S3AsyncClientBuilder s3AsyncClientBuilder = S3AsyncClient.builder().multipartEnabled(multipartEnabled)
×
101
                        .forcePathStyle(forcePathStyle);
×
102

103
                if (StringUtils.isNotBlank(accessKeyId) || StringUtils.isNotBlank(secretAccessKey)) {
×
104
                        log.info("Using storage.s3.accessKeyId and storage.s3.secretAccessKey for S3 client");
×
105
                        if (StringUtils.isBlank(accessKeyId) || StringUtils.isBlank(secretAccessKey)) {
×
106
                                throw new IllegalArgumentException("Both storage.s3.accessKeyId and storage.s3.secretAccessKey " +
×
107
                                                "must be provided");
108
                        }
109
                        StaticCredentialsProvider awsCredentials = StaticCredentialsProvider.create(
×
110
                                AwsBasicCredentials.create(accessKeyId, secretAccessKey));
×
111
                        s3AsyncClientBuilder = s3AsyncClientBuilder.credentialsProvider(awsCredentials);
×
112
        }
113
                
114
                if (StringUtils.isNotBlank(endpoint)) {
×
115
                        s3AsyncClientBuilder = s3AsyncClientBuilder.endpointOverride(URI.create(endpoint));
×
116
                }
117

118
                if (StringUtils.isNotBlank(region)) {
×
119
                        log.info("Using storage.s3.region '{}' for S3 client", region);
×
120
                        s3AsyncClientBuilder = s3AsyncClientBuilder.region(Region.of(region));
×
121
                }
122
                
123
                this.s3AsyncClient = s3AsyncClientBuilder.build();
×
124
    }
×
125
        
126
    public S3StorageService(StreamDataService streamService, S3AsyncClient s3AsyncClient, 
127
                                                        String bucketName) {
UNCOV
128
        super(streamService);
×
UNCOV
129
        this.s3AsyncClient = s3AsyncClient;
×
UNCOV
130
        this.bucketName = bucketName;
×
UNCOV
131
    }
×
132

133
    public InputStream getData(String key) throws IOException {
UNCOV
134
                CompletableFuture<ResponseInputStream<GetObjectResponse>> object = s3AsyncClient.getObject(
×
UNCOV
135
                        GetObjectRequest.builder().bucket(bucketName).key(encodeKey(key)).build(), AsyncResponseTransformer.toBlockingInputStream());
×
UNCOV
136
                return waitForResponse(object);
×
137
    }
138

139
        private <T> T waitForResponse(CompletableFuture<T> object) throws IOException {
140
                T result;
141
                try {
UNCOV
142
                        result = object.get();
×
143
                } catch (InterruptedException e) {
×
144
                        throw new InterruptedIOException(e.getMessage());
×
UNCOV
145
                } catch (ExecutionException e) {
×
UNCOV
146
                        throw new IOException(e);
×
UNCOV
147
                }
×
UNCOV
148
                return result;
×
149
        }
150

151
        public ObjectMetadata getMetadata(String key) throws IOException {
152
                HeadObjectRequest request = HeadObjectRequest.builder().bucket(bucketName).key(encodeKey(key)).build();
×
153
                CompletableFuture<HeadObjectResponse> headRequest = s3AsyncClient.headObject(request);
×
154
                HeadObjectResponse awsMetadata = waitForResponse(headRequest);
×
155
                ObjectMetadata metadata = new ObjectMetadata();
×
156
                metadata.setMimeType(awsMetadata.contentType());
×
157
                metadata.setLength(awsMetadata.contentLength());
×
158
                return metadata;
×
159
    }
160

161
    public Stream<String> getKeys(String moduleIdOrGroup, String keyPrefix) throws IOException {
UNCOV
162
                String key = newKey(moduleIdOrGroup, keyPrefix, null);
×
163
                
UNCOV
164
        ListObjectsV2Request req = ListObjectsV2Request.builder().bucket(bucketName)
×
UNCOV
165
                        .prefix(encodeKey(key)).build();
×
UNCOV
166
        CompletableFuture<ListObjectsV2Response> listObjectsRequest = s3AsyncClient.listObjectsV2(req);
×
UNCOV
167
                ListObjectsV2Response listObjects = waitForResponse(listObjectsRequest);
×
168
                
UNCOV
169
                return listObjects.contents().stream().map(S3Object::key).map(foundKey -> {
×
UNCOV
170
                        foundKey = decodeKey(foundKey);
×
UNCOV
171
                        String dirContent = foundKey.substring(key.length());
×
UNCOV
172
                        int subdir = dirContent.indexOf("/");
×
UNCOV
173
                        if (subdir != -1) {
×
174
                                // Return only subdirectories without their content
UNCOV
175
                                String dirOnly = dirContent.substring(0, subdir + 1);
×
UNCOV
176
                                return key + dirOnly;
×
177
                        } else {
UNCOV
178
                                return foundKey;
×
179
                        }
UNCOV
180
                }).distinct(); // Remove duplicate subdirectories
×
181
        }
182

183
    public boolean purgeData(String key) throws IOException {
UNCOV
184
                if (exists(key)) {
×
UNCOV
185
                        DeleteObjectRequest request = DeleteObjectRequest.builder().bucket(bucketName).key(encodeKey(key)).build();
×
UNCOV
186
                        CompletableFuture<DeleteObjectResponse> deleteRequest = s3AsyncClient.deleteObject(request);
×
UNCOV
187
                        return waitForBooleanResponse(deleteRequest);
×
188
                } else {
UNCOV
189
                        return false;
×
190
                }
191
    }
192
        
193
        private boolean waitForBooleanResponse(CompletableFuture<? extends S3Response> request) throws IOException {
194
                try {
UNCOV
195
                        request.get();
×
UNCOV
196
                        return true;
×
197
                } catch (InterruptedException e) {
×
198
                        throw new InterruptedIOException(e.getMessage());
×
UNCOV
199
                } catch (ExecutionException e) {
×
UNCOV
200
                        if (e.getCause() instanceof S3Exception) {
×
UNCOV
201
                                S3Exception s3e = (S3Exception) e.getCause();
×
UNCOV
202
                                if (s3e.statusCode() == 404) {
×
UNCOV
203
                                        return false;
×
204
                                }
205
                        }
206
                        throw new IOException(e);
×
207
                }
208
        }
209

210
    public boolean exists(String key) throws UncheckedIOException {
UNCOV
211
        HeadObjectRequest request = HeadObjectRequest.builder().bucket(bucketName).key(encodeKey(key)).build();
×
UNCOV
212
                CompletableFuture<HeadObjectResponse> headRequest = s3AsyncClient.headObject(request);
×
213
                try {
UNCOV
214
                        return waitForBooleanResponse(headRequest);
×
215
                } catch (IOException e) {
×
216
                        throw new UncheckedIOException(e);
×
217
                }
218
        }
219
        
220
    public String saveData(InputStream inputStream, ObjectMetadata metadata,
221
                           String moduleIdOrGroup, String keySuffix) throws IOException {
UNCOV
222
                metadata = (metadata == null) ? new ObjectMetadata() : metadata;
×
223

UNCOV
224
                String key = newKey(moduleIdOrGroup, keySuffix, metadata.getFilename());
×
225
                
UNCOV
226
                if (exists(key)) {
×
UNCOV
227
                        throw new FileAlreadyExistsException("Key " + key + " already exists");
×
228
                }
229
                
UNCOV
230
                PutObjectRequest request = PutObjectRequest.builder().bucket(bucketName).key(encodeKey(key))
×
UNCOV
231
                        .contentType(metadata.getMimeType()).contentLength(metadata.getLength()).build();
×
232

233
                try {
UNCOV
234
                        BlockingInputStreamAsyncRequestBody requestBody = AsyncRequestBody.forBlockingInputStream(metadata.getLength());
×
UNCOV
235
                        CompletableFuture<PutObjectResponse> putRequest = s3AsyncClient.putObject(request, requestBody);
×
UNCOV
236
                        requestBody.writeInputStream(inputStream);
×
237

UNCOV
238
                        waitForResponse(putRequest);
×
UNCOV
239
                } catch (Exception e) {
×
UNCOV
240
                        throw new IOException(e);
×
UNCOV
241
                }
×
242
                        
UNCOV
243
        return key;
×
244
    }
245
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc