[IMPORTANT] Aggiornamento di alcune librerie (MinIO, Guava, Firebase, Jackson)

This commit is contained in:
2024-05-08 18:15:32 +02:00
parent b5a7ba0054
commit e14cbb49c3
102 changed files with 173 additions and 12976 deletions

3
.idea/misc.xml generated
View File

@@ -8,5 +8,8 @@
</list>
</option>
</component>
<component name="PWA">
<option name="wasEnabledAtLeastOnce" value="true" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK" />
</project>

View File

@@ -154,6 +154,11 @@
<version>1.13</version>
</dependency>
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.4.3</version>
</dependency>
<!-- SWAGGER
@@ -216,7 +221,7 @@
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.10</version>
<version>0.10.2</version>
</dependency>
<!-- Mail -->
@@ -426,6 +431,11 @@
<artifactId>jackson-dataformat-csv</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
@@ -537,7 +547,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
<version>3.14.0</version>
</dependency>
<dependency>
@@ -555,11 +565,11 @@
</dependency>
<!-- UTILS -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.google.guava</groupId>-->
<!-- <artifactId>guava</artifactId>-->
<!-- <version>${guava.version}</version>-->
<!-- </dependency>-->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
@@ -686,7 +696,7 @@
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>7.0.1</version>
<version>9.2.0</version>
</dependency>

View File

@@ -6,16 +6,9 @@ import it.integry.annotations.PostContextAutowired;
import it.integry.annotations.PostContextConstruct;
import it.integry.annotations.PostWebServerConstruct;
import it.integry.ems.properties.EmsProperties;
import it.integry.ems.schedule.new_cron_job.dto.AutomatedOperationTypeEnum;
import it.integry.ems.schedule.new_cron_job.dto.operations.ServiceCallAutomatedOperationDTO;
import it.integry.ems.schedule.new_cron_job.dto.operations.base_classes.BaseAutomatedOperationDTO;
import it.integry.ems.schedule.new_cron_job.service.AutomatedOperationHandlerComponent;
import it.integry.ems.settings.Model.AvailableConnectionsModel;
import it.integry.ems.settings.Model.SettingsModel;
import it.integry.ems.settings.SettingsController;
import it.integry.ems.sync.MultiDBTransaction.AdvancedDataSource;
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
import it.integry.ems.utility.UtilityDebug;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.postgresql.Driver;
@@ -33,11 +26,12 @@ import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import static org.reflections.scanners.Scanners.TypesAnnotated;
@Component
public class EmsCoreContext implements ApplicationListener<ContextRefreshedEvent> {
@@ -116,13 +110,11 @@ public class EmsCoreContext implements ApplicationListener<ContextRefreshedEvent
private void dispatchPostContextConstruct(MultiDBTransactionManager multiDBTransactionManager) throws InvocationTargetException, IllegalAccessException {
Reflections reflections = new Reflections("it.integry");
final Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Component.class);
typesAnnotatedWith.addAll(reflections.getTypesAnnotatedWith(Service.class));
final Set<Class<?>> typesAnnotatedWith = reflections.get(TypesAnnotated.with(Component.class, Service.class).asClass());
List<Class<?>> classesWithPostContextConstruct = Stream.of(typesAnnotatedWith)
.filter(x -> Stream.of(x.getDeclaredMethods()).anyMatch(y -> y.isAnnotationPresent(PostContextConstruct.class)))
.sortBy(x -> Stream.of(x.getDeclaredMethods())
.filter(x -> Arrays.stream(x.getDeclaredMethods()).anyMatch(y -> y.isAnnotationPresent(PostContextConstruct.class)))
.sortBy(x -> Arrays.stream(x.getDeclaredMethods())
.filter(y -> y.isAnnotationPresent(PostContextConstruct.class))
.findFirst()
.get()
@@ -159,13 +151,11 @@ public class EmsCoreContext implements ApplicationListener<ContextRefreshedEvent
private void dispatchPostWebServerConstruct(MultiDBTransactionManager multiDBTransactionManager) throws InvocationTargetException, IllegalAccessException {
Reflections reflections = new Reflections("it.integry");
final Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Component.class);
typesAnnotatedWith.addAll(reflections.getTypesAnnotatedWith(Service.class));
final Set<Class<?>> typesAnnotatedWith = reflections.get(TypesAnnotated.with(Component.class, Service.class).asClass());
List<Class<?>> classesWithPostWebServerConstruct = Stream.of(typesAnnotatedWith)
.filter(x -> Stream.of(x.getDeclaredMethods()).anyMatch(y -> y.isAnnotationPresent(PostWebServerConstruct.class)))
.sortBy(x -> Stream.of(x.getDeclaredMethods())
.filter(x -> Arrays.stream(x.getDeclaredMethods()).anyMatch(y -> y.isAnnotationPresent(PostWebServerConstruct.class)))
.sortBy(x -> Arrays.stream(x.getDeclaredMethods())
.filter(y -> y.isAnnotationPresent(PostWebServerConstruct.class))
.findFirst()
.get()

View File

@@ -18,6 +18,9 @@ import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Set;
import java.util.stream.Collectors;
import static org.reflections.scanners.Scanners.SubTypes;
public class CommonObjectMapper extends ObjectMapper {
@@ -27,10 +30,14 @@ public class CommonObjectMapper extends ObjectMapper {
registerModule(module);
SimpleModule moduleSubType = new SimpleModule("test", Version.unknownVersion());
Reflections reflections = new Reflections("it.integry");
Set<Class<? extends EntityBase>> clssList = reflections.getSubTypesOf(EntityBase.class);
final Set<Class<? extends ComposedEntityBase>> subTypesOfComposed = reflections.getSubTypesOf(ComposedEntityBase.class);
clssList.addAll(subTypesOfComposed);
Set<Class<? extends EntityBase>> clssList =
reflections.get(SubTypes.of(EntityBase.class, ComposedEntityBase.class).asClass())
.stream()
.map(x -> (Class<? extends EntityBase>) x)
.collect(Collectors.toSet());
for (Class<? extends EntityBase> clazz : clssList) {
try {
Field f = clazz.getDeclaredField("ENTITY");

View File

@@ -32,6 +32,8 @@ import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
import static org.reflections.scanners.Scanners.SubTypes;
@Component
public class MigrationComponent {
@@ -60,11 +62,12 @@ public class MigrationComponent {
public void init() {
Reflections reflections = new Reflections("it.integry.ems.migration.model");
allMigrationsList = new ArrayList<>(Stream.of(reflections.getSubTypesOf(MigrationModelInterface.class))
.map(x -> x)
allMigrationsList = reflections.get(SubTypes.of(MigrationModelInterface.class).asClass())
.stream()
.map(x -> (Class<? extends MigrationModelInterface>) x)
.filter(x -> !Modifier.isAbstract(x.getModifiers()))
.sortBy(Class::getSimpleName)
.toList());
.sorted(Comparator.comparing(Class::getSimpleName))
.collect(Collectors.toList());
if (UtilityDebug.isDebugExecution())
return;

View File

@@ -0,0 +1,8 @@
package it.integry.ems.object_storage.minio;
public class MinIONotEnabledException extends Exception {
public MinIONotEnabledException() {
super("MinIO is not enabled");
}
}

View File

@@ -3,14 +3,12 @@ package it.integry.ems.object_storage.minio;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.ByteStreams;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.DeleteObject;
import it.integry.annotations.PostContextConstruct;
import it.integry.ems.exception.PrimaryDatabaseNotPresentException;
import it.integry.ems.json.JSONObjectMapper;
import it.integry.ems.object_storage.interfaces.IObjectStorageService;
import it.integry.ems.object_storage.minio.sdk.ErrorCode;
import it.integry.ems.object_storage.minio.sdk.MinioClient;
import it.integry.ems.object_storage.minio.sdk.errors.ErrorResponseException;
import it.integry.ems.object_storage.minio.sdk.errors.MinioException;
import it.integry.ems.service.HttpRestWrapper;
import it.integry.ems.settings.Model.MinIOSettingsModel;
import it.integry.ems.settings.Model.SettingsModel;
@@ -21,7 +19,6 @@ import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.xmlpull.v1.XmlPullParserException;
import javax.annotation.Nonnull;
import java.io.ByteArrayInputStream;
@@ -36,6 +33,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Component
public class MinIOService implements IObjectStorageService {
@@ -92,14 +90,23 @@ public class MinIOService implements IObjectStorageService {
String host = String.format("http://%s:%d", ip, port);
// Create a minioClient with the MinIO Server name, Port, Access key and Secret key.
mMinioClient = new MinioClient(host, accessKey, secretKey);
mMinioClient = MinioClient.builder()
.endpoint(host)
.credentials(accessKey, secretKey)
.build();
mMinioClient.ignoreCertCheck();
// Check if the bucket already exists.
boolean isExist = mMinioClient.bucketExists(mDefaultBucketName);
boolean isExist = mMinioClient.bucketExists(
BucketExistsArgs.builder()
.bucket(mDefaultBucketName)
.build());
if (!isExist) {
// Make a new bucket called asiatrip to hold a zip file of photos.
mMinioClient.makeBucket(mDefaultBucketName);
mMinioClient.makeBucket(
MakeBucketArgs.builder()
.bucket(mDefaultBucketName)
.build());
}
// mMinioClient.traceOn(new LogOutputStream(logger));
@@ -143,17 +150,17 @@ public class MinIOService implements IObjectStorageService {
}
@Override
public byte[] downloadObject(@Nonnull String objectName) throws MinioException, XmlPullParserException, NoSuchAlgorithmException, IOException, InvalidKeyException {
public byte[] downloadObject(@Nonnull String objectName) throws Exception {
return internalDownloadObject(objectName, mDefaultBucketName);
}
@Override
public byte[] downloadObject(@Nonnull String objectName, @Nonnull MultiDBTransactionManager multiDBTransactionManager) throws SQLException, MinioException, XmlPullParserException, IOException, NoSuchAlgorithmException, InvalidKeyException, PrimaryDatabaseNotPresentException {
public byte[] downloadObject(@Nonnull String objectName, @Nonnull MultiDBTransactionManager multiDBTransactionManager) throws Exception {
return internalDownloadObject(objectName, getBucketName(multiDBTransactionManager));
}
@Override
public byte[] downloadObject(@Nonnull String objectName, @Nonnull Connection connection) throws SQLException, MinioException, XmlPullParserException, NoSuchAlgorithmException, IOException, InvalidKeyException {
public byte[] downloadObject(@Nonnull String objectName, @Nonnull Connection connection) throws Exception {
return internalDownloadObject(objectName, getBucketName(connection));
}
@@ -165,16 +172,24 @@ public class MinIOService implements IObjectStorageService {
InputStream dataInputStream = new ByteArrayInputStream(data);
long length = dataInputStream.available();
this.mMinioClient.putObject(bucketName, objectName, dataInputStream, length, null, null, null);
this.mMinioClient.putObject(
PutObjectArgs.builder()
.stream(dataInputStream, length, -1)
.bucket(bucketName)
.object(objectName)
.build());
return objectName;
}
private byte[] internalDownloadObject(@Nonnull String objectName, @Nonnull String bucketName) throws MinioException, XmlPullParserException, NoSuchAlgorithmException, IOException, InvalidKeyException {
private byte[] internalDownloadObject(@Nonnull String objectName, @Nonnull String bucketName) throws Exception {
this.checkStatus();
this.checkConnection();
InputStream data = this.mMinioClient.getObject(bucketName, objectName, 0);
InputStream data = this.mMinioClient.getObject(GetObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build());
byte[] bytes = ByteStreams.toByteArray(data);
return bytes;
}
@@ -196,7 +211,10 @@ public class MinIOService implements IObjectStorageService {
this.checkStatus();
this.checkConnection();
this.mMinioClient.removeObject(getBucketName(connection), objectName);
this.mMinioClient.removeObject(RemoveObjectArgs.builder()
.bucket(getBucketName(connection))
.object(objectName)
.build());
return true;
}
@@ -206,7 +224,10 @@ public class MinIOService implements IObjectStorageService {
this.checkStatus();
this.checkConnection();
this.mMinioClient.removeObject(getBucketName(multiDBTransactionManager), objectName);
this.mMinioClient.removeObject(RemoveObjectArgs.builder()
.bucket(getBucketName(multiDBTransactionManager))
.object(objectName)
.build());
return true;
}
@@ -216,7 +237,14 @@ public class MinIOService implements IObjectStorageService {
this.checkStatus();
this.checkConnection();
this.mMinioClient.removeObjects(getBucketName(multiDBTransactionManager), objectNameList);
final List<DeleteObject> objectsToDelete = objectNameList.stream()
.map(DeleteObject::new)
.collect(Collectors.toList());
this.mMinioClient.removeObjects(RemoveObjectsArgs.builder()
.bucket(getBucketName(multiDBTransactionManager))
.objects(objectsToDelete)
.build());
return true;
}
@@ -277,8 +305,8 @@ public class MinIOService implements IObjectStorageService {
} else return false;
}
private void checkStatus() throws MinioException {
if (!this.mIsEnabled) throw new MinioException("MinIO is not enabled");
private void checkStatus() throws MinIONotEnabledException {
if (!this.mIsEnabled) throw new MinIONotEnabledException();
}
private void checkConnection() {
@@ -304,16 +332,19 @@ public class MinIOService implements IObjectStorageService {
exists = true;
try {
this.mMinioClient.statObject(bucketName, uuid);
this.mMinioClient.statObject(StatObjectArgs.builder()
.bucket(bucketName)
.object(uuid)
.build());
} catch (ErrorResponseException ex) {
exists = ex.errorResponse().errorCode() != ErrorCode.NO_SUCH_KEY;
exists = !ex.errorResponse().code().equalsIgnoreCase("NoSuchKey");
}
}
return uuid;
}
private String getBucketName(Connection connection) throws MinioException, SQLException, XmlPullParserException, NoSuchAlgorithmException, IOException, InvalidKeyException {
private String getBucketName(Connection connection) throws SQLException, NoSuchAlgorithmException, IOException, InvalidKeyException, MinIONotEnabledException, ServerException, InsufficientDataException, InvalidResponseException, XmlParserException, InternalException, ErrorResponseException {
this.checkStatus();
this.checkConnection();
@@ -325,16 +356,21 @@ public class MinIOService implements IObjectStorageService {
} else bucketName = mDefaultBucketName;
// Check if the bucket already exists.
boolean isExist = mMinioClient.bucketExists(bucketName);
boolean isExist = mMinioClient.bucketExists(
BucketExistsArgs.builder()
.bucket(bucketName)
.build());
if (!isExist) {
// Make a new bucket called asiatrip to hold a zip file of photos.
mMinioClient.makeBucket(bucketName);
mMinioClient.makeBucket(MakeBucketArgs.builder()
.bucket(bucketName)
.build());
}
return bucketName;
}
private String getBucketName(MultiDBTransactionManager multiDBTransactionManager) throws SQLException, IOException, PrimaryDatabaseNotPresentException, MinioException, XmlPullParserException, NoSuchAlgorithmException, InvalidKeyException {
private String getBucketName(MultiDBTransactionManager multiDBTransactionManager) throws SQLException, IOException, PrimaryDatabaseNotPresentException, NoSuchAlgorithmException, InvalidKeyException, ServerException, InsufficientDataException, MinIONotEnabledException, ErrorResponseException, InvalidResponseException, XmlParserException, InternalException {
String bucketName = null;
if (multiDBTransactionManager != null) {
@@ -342,10 +378,15 @@ public class MinIOService implements IObjectStorageService {
} else bucketName = mDefaultBucketName;
// Check if the bucket already exists.
boolean isExist = mMinioClient.bucketExists(bucketName);
boolean isExist = mMinioClient.bucketExists(
BucketExistsArgs.builder()
.bucket(bucketName)
.build());
if (!isExist) {
// Make a new bucket called asiatrip to hold a zip file of photos.
mMinioClient.makeBucket(bucketName);
mMinioClient.makeBucket(MakeBucketArgs.builder()
.bucket(bucketName)
.build());
}
return bucketName;

View File

@@ -1,75 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import java.util.HashMap;
import java.util.Map;
/**
* Amazon AWS S3 endpoints for various regions.
*/
enum AwsS3Endpoints {
INSTANCE;
private final Map<String, String> endpoints = new HashMap<>();
AwsS3Endpoints() {
// ap-northeast-1
endpoints.put("ap-northeast-1", "s3-ap-northeast-1.amazonaws.com");
// ap-northeast-2
endpoints.put("ap-northeast-2", "s3-ap-northeast-2.amazonaws.com");
//ap-south-1
endpoints.put("ap-south-1", "s3-ap-south-1.amazonaws.com");
// ap-southeast-1
endpoints.put("ap-southeast-1", "s3-ap-southeast-1.amazonaws.com");
// ap-southeast-2
endpoints.put("ap-southeast-2", "s3-ap-southeast-2.amazonaws.com");
// eu-central-1
endpoints.put("eu-central-1", "s3-eu-central-1.amazonaws.com");
// eu-west-1
endpoints.put("eu-west-1", "s3-eu-west-1.amazonaws.com");
// eu-west-2
endpoints.put("eu-west-2", "s3-eu-west-2.amazonaws.com");
// sa-east-1
endpoints.put("sa-east-1", "s3-sa-east-1.amazonaws.com");
// us-west-1
endpoints.put("us-west-1", "s3-us-west-1.amazonaws.com");
// us-west-2
endpoints.put("us-west-2", "s3-us-west-2.amazonaws.com");
// us-east-1
endpoints.put("us-east-1", "s3.amazonaws.com");
// us-east-2
endpoints.put("us-east-2", "s3-us-east-2.amazonaws.com");
//ca-central-1
endpoints.put("ca-central-1", "s3.ca-central-1.amazonaws.com");
// cn-north-1
endpoints.put("cn-north-1", "s3.cn-north-1.amazonaws.com.cn");
// cn-northwest-1
endpoints.put("cn-northwest-1", "s3.cn-northwest-1.amazonaws.com.cn");
}
/**
* Gets Amazon S3 endpoint for the relevant region.
*/
public String endpoint(String region) {
String s = AwsS3Endpoints.INSTANCE.endpoints.get(region);
if (s == null) {
s = "s3.amazonaws.com";
}
return s;
}
}

View File

@@ -1,26 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import it.integry.ems.object_storage.minio.sdk.notification.NotificationInfo;
public interface BucketEventListener {
void updateEvent(NotificationInfo info);
}

View File

@@ -1,71 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* A singleton bucket/region cache map.
*/
enum BucketRegionCache {
INSTANCE;
private final Map<String, String> regionMap = new ConcurrentHashMap<>();
/**
* Returns AWS region for given bucket name.
*/
public String region(String bucketName) {
if (bucketName == null) {
return "us-east-1";
}
String region = this.regionMap.get(bucketName);
if (region == null) {
return "us-east-1";
} else {
return region;
}
}
/**
* Sets bucket name and its region to BucketRegionCache.
*/
public void set(String bucketName, String region) {
this.regionMap.put(bucketName, region);
}
/**
* Removes region cache of the bucket if any.
*/
public void remove(String bucketName) {
if (bucketName != null) {
this.regionMap.remove(bucketName);
}
}
/**
* Returns true if given bucket name is in the map else false.
*/
public boolean exists(String bucketName) {
return this.regionMap.get(bucketName) != null;
}
}

View File

@@ -1,211 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import it.integry.ems.object_storage.minio.sdk.errors.InsufficientDataException;
import it.integry.ems.object_storage.minio.sdk.errors.InternalException;
import org.joda.time.DateTime;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
class ChunkedInputStream extends InputStream {
// Chunk size in chunked upload for PUT object is 64KiB
private static final int CHUNK_SIZE = 64 * 1024;
// Each chunk body should be like
// CHUNK_SIZE_IN_HEX_STRING + ";chunk-signature=" + SIGNATURE + "\r\n" + CHUNK_DATA + "\r\n"
// e.g. for 64KiB of chunk
// 10000;chunk-signature=ad80c730a21e5b8d04586a2213dd63b9a0e99e0e2307b0ade35a65485a288648\r\n<65536-bytes>\r\n
// From the above value, a full chunk size 65626 is by
// len(hex string of 64KiB) = 5 (+)
// len(;chunk-signature=ad80c730a21e5b8d04586a2213dd63b9a0e99e0e2307b0ade35a65485a288648\r\n) = 83 (+)
// <65536 bytes> = 65536 (+)
// len(\r\n) = 2
private static final int FULL_CHUNK_LEN = 65626;
// Data in last chunk might be less than 64KiB. In this case, ignoring variable length of chunk
// body components, remaining length is constant
private static final int CHUNK_SIGNATURE_METADATA_LEN = 85;
// As final additional chunk must be like
// 0;chunk-signature=b6c6ea8a5354eaf15b3cb7646744f4275b71ea724fed81ceb9323e279d449df9\r\n\r\n
// the length is 86
private static final int FINAL_ADDITIONAL_CHUNK_LEN = 1 + CHUNK_SIGNATURE_METADATA_LEN;
private InputStream inputStream;
private int streamSize;
private int length;
private DateTime date;
private String region;
private String secretKey;
private String prevSignature;
// Counter denotes how many bytes read from given input stream.
private int streamBytesRead = 0;
// Initialize to avoid findbugs warning.
private byte[] chunkBody = new byte[0];
private int chunkPos = 0;
private boolean isEof = false;
// Counter denotes how many bytes the consumer read from this stream.
private int bytesRead = 0;
/**
* Create new ChunkedInputStream for given input stream.
*/
public ChunkedInputStream(InputStream inputStream, int streamSize, DateTime date, String region, String secretKey,
String seedSignature) throws IOException {
this.inputStream = inputStream;
this.streamSize = streamSize;
this.date = date;
this.region = region;
this.secretKey = secretKey;
this.prevSignature = seedSignature;
// Calculate stream length.
int fullChunks = this.streamSize / CHUNK_SIZE;
this.length = fullChunks * FULL_CHUNK_LEN;
int lastChunkLen = this.streamSize % CHUNK_SIZE;
if (lastChunkLen > 0) {
this.length += Integer.toHexString(lastChunkLen).getBytes(StandardCharsets.UTF_8).length;
this.length += CHUNK_SIGNATURE_METADATA_LEN;
this.length += lastChunkLen;
}
this.length += FINAL_ADDITIONAL_CHUNK_LEN;
}
private int readData(byte[] buf) throws IOException {
if (this.isEof) {
return -1;
}
int pos = 0;
int len = buf.length;
int totalBytesRead = 0;
int bytesRead = 0;
while (totalBytesRead < buf.length) {
bytesRead = inputStream.read(buf, pos, len);
if (bytesRead < 0) {
this.isEof = true;
break;
}
totalBytesRead += bytesRead;
pos += bytesRead;
len = buf.length - totalBytesRead;
}
return totalBytesRead;
}
private void createChunkBody(byte[] chunk)
throws IOException, NoSuchAlgorithmException, InvalidKeyException, InsufficientDataException, InternalException {
String chunkSha256 = Digest.sha256Hash(chunk, chunk.length);
String signature = Signer.getChunkSignature(chunkSha256, this.date, this.region, this.secretKey,
this.prevSignature);
ByteArrayOutputStream os = new ByteArrayOutputStream();
// Add metadata.
os.write(Integer.toHexString(chunk.length).getBytes(StandardCharsets.UTF_8));
os.write(";chunk-signature=".getBytes(StandardCharsets.UTF_8));
os.write(signature.getBytes(StandardCharsets.UTF_8));
os.write("\r\n".getBytes(StandardCharsets.UTF_8));
// Add chunk data.
os.write(chunk, 0, chunk.length);
os.write("\r\n".getBytes(StandardCharsets.UTF_8));
this.chunkBody = os.toByteArray();
this.chunkPos = 0;
this.prevSignature = signature;
}
private int readChunk(int chunkSize)
throws IOException, NoSuchAlgorithmException, InvalidKeyException, InsufficientDataException, InternalException {
byte[] chunk = new byte[chunkSize];
int len = readData(chunk);
if (len < 0) {
return -1;
}
if (len != chunkSize) {
throw new InsufficientDataException("Insufficient data. read = " + len + " expected = " + chunkSize);
}
createChunkBody(chunk);
return this.chunkBody.length;
}
/**
* read single byte from chunk body.
*/
public int read() throws IOException {
if (this.bytesRead == this.length) {
// All chunks and final additional chunk are read.
// This means we have reached EOF.
return -1;
}
try {
// Read a chunk from given input stream when
// it is first chunk or all bytes in chunk body is read
if (this.streamBytesRead == 0 || this.chunkPos == this.chunkBody.length) {
// Check if there are data available to read from given input stream.
if (this.streamBytesRead != this.streamSize) {
// Send all data chunks.
int chunkSize = CHUNK_SIZE;
if (this.streamBytesRead + chunkSize > this.streamSize) {
chunkSize = this.streamSize - this.streamBytesRead;
}
if (readChunk(chunkSize) < 0) {
return -1;
}
this.streamBytesRead += chunkSize;
} else {
// Send final additional chunk to complete chunk upload.
byte[] chunk = new byte[0];
createChunkBody(chunk);
}
}
this.bytesRead++;
// Value must be between 0 to 255.
int value = this.chunkBody[this.chunkPos] & 0xFF;
this.chunkPos++;
return value;
} catch (NoSuchAlgorithmException | InvalidKeyException | InsufficientDataException | InternalException e) {
throw new IOException(e.getCause());
}
}
/**
* return length of data ChunkedInputStream supposes to produce.
*/
public int length() {
return this.length;
}
}

View File

@@ -1,186 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import it.integry.ems.object_storage.minio.sdk.errors.InvalidArgumentException;
import java.util.Map;
import java.util.TreeMap;
public class ComposeSource {
private String bucketName;
private String objectName;
private Long offset;
private Long length;
private Map<String, String> headerMap;
private CopyConditions copyConditions;
private ServerSideEncryption sse;
private long objectSize;
private Map<String, String> headers;
/**
* Create new ComposeSource for given bucket and object.
*/
public ComposeSource(String bucketName, String objectName) throws InvalidArgumentException {
this(bucketName, objectName, null, null, null, null, null);
}
/**
* Create new ComposeSource for given bucket, object, offset and length.
*/
public ComposeSource(String bucketName, String objectName, Long offset, Long length)
throws InvalidArgumentException {
this(bucketName, objectName, offset, length, null, null, null);
}
/**
* Create new ComposeSource for given bucket, object, offset, length and headerMap.
*/
public ComposeSource(String bucketName, String objectName, Long offset, Long length,
Map<String, String> headerMap) throws InvalidArgumentException {
this(bucketName, objectName, offset, length, headerMap, null, null);
}
/**
* Create new ComposeSource for given bucket, object, offset, length, headerMap and CopyConditions.
*/
public ComposeSource(String bucketName, String objectName, Long offset, Long length,
Map<String, String> headerMap, CopyConditions copyConditions) throws InvalidArgumentException {
this(bucketName, objectName, offset, length, headerMap, copyConditions, null);
}
/**
* Creates new ComposeSource for given bucket, object, offset, length, headerMap, CopyConditions
* and server side encryption.
*
* @throws InvalidArgumentException upon invalid value is passed to a method.
*/
public ComposeSource(String bucketName, String objectName, Long offset, Long length, Map<String, String> headerMap,
CopyConditions copyConditions, ServerSideEncryption sse) throws InvalidArgumentException {
if (bucketName == null) {
throw new InvalidArgumentException("Source bucket name cannot be empty");
}
if (objectName == null) {
throw new InvalidArgumentException("Source object name cannot be empty");
}
if (offset != null && offset < 0) {
throw new InvalidArgumentException("Offset cannot be negative");
}
if (length != null && length < 0) {
throw new InvalidArgumentException("Length cannot be negative");
}
if (length != null && offset == null) {
offset = 0L;
}
this.bucketName = bucketName;
this.objectName = objectName;
this.offset = offset;
this.length = length;
this.headerMap = headerMap;
this.copyConditions = copyConditions;
this.sse = sse;
}
/**
* Constructs header .
*/
public void buildHeaders(long objectSize, String etag) throws InvalidArgumentException {
if (offset != null && offset >= objectSize) {
throw new InvalidArgumentException("source " + bucketName + "/" + objectName + ": offset " + offset
+ " is beyond object size " + objectSize);
}
if (length != null) {
if (length > objectSize) {
throw new InvalidArgumentException("source " + bucketName + "/" + objectName + ": length " + length
+ " is beyond object size " + objectSize);
}
if (offset + length > objectSize) {
throw new InvalidArgumentException("source " + bucketName + "/" + objectName + ": compose size "
+ (offset + length) + " is beyond object size " + objectSize);
}
}
Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
headers.put("x-amz-copy-source", S3Escaper.encodePath(bucketName + "/" + objectName));
headers.put("x-amz-copy-source-if-match", etag);
if (headerMap != null) {
headers.putAll(headerMap);
}
if (copyConditions != null) {
headers.putAll(copyConditions.getConditions());
}
if (sse != null) {
headers.putAll(sse.copySourceHeaders());
}
this.objectSize = objectSize;
this.headers = headers;
}
public String bucketName() {
return bucketName;
}
public String objectName() {
return objectName;
}
public Long offset() {
return offset;
}
public Long length() {
return length;
}
public CopyConditions copyConditions() {
return copyConditions;
}
public ServerSideEncryption sse() {
return sse;
}
/**
* Returns header.
*/
public Map<String, String> headers() {
Map<String, String> headers = null;
if (this.headers != null) {
headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
headers.putAll(this.headers);
}
return headers;
}
public long objectSize() {
return objectSize;
}
}

View File

@@ -1,104 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2017 MinIO,Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import it.integry.ems.object_storage.minio.sdk.errors.InvalidArgumentException;
import org.joda.time.DateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* A container class to hold all the Conditions to be checked
* before copying an object.
*/
public class CopyConditions {
// Metadata directive "REPLACE" used to replace metadata on
// destination object in copyObject().
private static final String METADATA_DIRECTIVE_REPLACE = "REPLACE";
private Map<String, String> copyConditions = new HashMap<>();
/**
* Set modified condition, copy object modified since given time.
*
* @throws InvalidArgumentException When date is null
*/
public void setModified(DateTime date) throws InvalidArgumentException {
if (date == null) {
throw new InvalidArgumentException("Date cannot be empty");
}
copyConditions.put("x-amz-copy-source-if-modified-since", date.toString(DateFormat.HTTP_HEADER_DATE_FORMAT));
}
/**
* Sets object unmodified condition, copy object unmodified since given time.
*
* @throws InvalidArgumentException When date is null
*/
public void setUnmodified(DateTime date) throws InvalidArgumentException {
if (date == null) {
throw new InvalidArgumentException("Date can not be null");
}
copyConditions.put("x-amz-copy-source-if-unmodified-since", date.toString(DateFormat.HTTP_HEADER_DATE_FORMAT));
}
/**
* Set matching ETag condition, copy object which matches
* the following ETag.
*
* @throws InvalidArgumentException When etag is null
*/
public void setMatchETag(String etag) throws InvalidArgumentException {
if (etag == null) {
throw new InvalidArgumentException("ETag cannot be empty");
}
copyConditions.put("x-amz-copy-source-if-match", etag);
}
/**
* Set matching ETag none condition, copy object which does not
* match the following ETag.
*
* @throws InvalidArgumentException When etag is null
*/
public void setMatchETagNone(String etag) throws InvalidArgumentException {
if (etag == null) {
throw new InvalidArgumentException("ETag cannot be empty");
}
copyConditions.put("x-amz-copy-source-if-none-match", etag);
}
/**
* Set replace metadata directive which specifies that
* destination object after copyObject() sets new
* metadata provided in the request.
*/
public void setReplaceMetadataDirective() {
copyConditions.put("x-amz-metadata-directive", METADATA_DIRECTIVE_REPLACE);
}
/**
* Get all the set copy conditions map.
*/
public Map<String, String> getConditions() {
return Collections.unmodifiableMap(copyConditions);
}
}

View File

@@ -1,45 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Locale;
/**
* Global constants for various date formats. They are used to convert string to DateTime object and vise verse.
*/
public class DateFormat {
public static final DateTimeFormatter AMZ_DATE_FORMAT =
DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss'Z'").withZoneUTC().withLocale(Locale.US);
public static final DateTimeFormatter EXPIRATION_DATE_FORMAT =
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH':'mm':'ss'.'SSS'Z'").withZoneUTC().withLocale(Locale.US);
public static final DateTimeFormatter RESPONSE_DATE_FORMAT = EXPIRATION_DATE_FORMAT;
public static final DateTimeFormatter SIGNER_DATE_FORMAT =
DateTimeFormat.forPattern("yyyyMMdd").withZoneUTC().withLocale(Locale.US);
public static final DateTimeFormatter HTTP_HEADER_DATE_FORMAT =
DateTimeFormat.forPattern("EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'").withZoneUTC().withLocale(Locale.US);
private DateFormat() {
}
}

View File

@@ -1,191 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import com.google.common.io.BaseEncoding;
import it.integry.ems.object_storage.minio.sdk.errors.InsufficientDataException;
import it.integry.ems.object_storage.minio.sdk.errors.InternalException;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
/**
* Various global static functions used.
*/
class Digest {
/**
* Private constructor.
*/
private Digest() {
}
/**
* Returns SHA-256 hash of given string.
*/
public static String sha256Hash(String string) throws NoSuchAlgorithmException {
byte[] data = string.getBytes(StandardCharsets.UTF_8);
MessageDigest sha256Digest = MessageDigest.getInstance("SHA-256");
sha256Digest.update((byte[]) data, 0, data.length);
return BaseEncoding.base16().encode(sha256Digest.digest()).toLowerCase(Locale.US);
}
/**
* Returns SHA-256 hash of given data and it's length.
*
* @param data must be {@link RandomAccessFile}, {@link BufferedInputStream} or byte array.
* @param len length of data to be read for hash calculation.
*/
public static String sha256Hash(Object data, int len)
throws NoSuchAlgorithmException, IOException, InsufficientDataException, InternalException {
MessageDigest sha256Digest = MessageDigest.getInstance("SHA-256");
if (data instanceof BufferedInputStream || data instanceof RandomAccessFile) {
updateDigests(data, len, sha256Digest, null);
} else if (data instanceof byte[]) {
sha256Digest.update((byte[]) data, 0, len);
} else {
throw new InternalException("Unknown data source to calculate sha256 hash. This should not happen, "
+ "please report this issue at https://github.com/minio/minio-java/issues");
}
return BaseEncoding.base16().encode(sha256Digest.digest()).toLowerCase(Locale.US);
}
/**
* Returns SHA-256 and MD5 hashes of given data and it's length.
*
* @param data must be {@link RandomAccessFile}, {@link BufferedInputStream} or byte array.
* @param len length of data to be read for hash calculation.
*/
public static String[] sha256Md5Hashes(Object data, int len)
throws NoSuchAlgorithmException, IOException, InsufficientDataException, InternalException {
MessageDigest sha256Digest = MessageDigest.getInstance("SHA-256");
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
if (data instanceof BufferedInputStream || data instanceof RandomAccessFile) {
updateDigests(data, len, sha256Digest, md5Digest);
} else if (data instanceof byte[]) {
sha256Digest.update((byte[]) data, 0, len);
md5Digest.update((byte[]) data, 0, len);
} else {
throw new InternalException("Unknown data source to calculate sha256 hash. This should not happen, "
+ "please report this issue at https://github.com/minio/minio-java/issues");
}
return new String[]{BaseEncoding.base16().encode(sha256Digest.digest()).toLowerCase(Locale.US),
BaseEncoding.base64().encode(md5Digest.digest())};
}
/**
* Returns MD5 hash of given data and it's length.
*
* @param data must be {@link RandomAccessFile}, {@link BufferedInputStream} or byte array.
* @param len length of data to be read for hash calculation.
*/
public static String md5Hash(Object data, int len)
throws NoSuchAlgorithmException, IOException, InsufficientDataException, InternalException {
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
if (data instanceof BufferedInputStream || data instanceof RandomAccessFile) {
updateDigests(data, len, null, md5Digest);
} else if (data instanceof byte[]) {
md5Digest.update((byte[]) data, 0, len);
} else {
throw new InternalException("Unknown data source to calculate sha256 hash. This should not happen, "
+ "please report this issue at https://github.com/minio/minio-java/issues");
}
return BaseEncoding.base64().encode(md5Digest.digest());
}
/**
* Updated MessageDigest with bytes read from file and stream.
*/
private static int updateDigests(Object inputStream, int len, MessageDigest sha256Digest, MessageDigest md5Digest)
throws IOException, InsufficientDataException {
RandomAccessFile file = null;
BufferedInputStream stream = null;
if (inputStream instanceof RandomAccessFile) {
file = (RandomAccessFile) inputStream;
} else if (inputStream instanceof BufferedInputStream) {
stream = (BufferedInputStream) inputStream;
}
// hold current position of file/stream to reset back to this position.
long pos = 0;
if (file != null) {
pos = file.getFilePointer();
} else {
stream.mark(len);
}
// 16KiB buffer for optimization
byte[] buf = new byte[16384];
int bytesToRead = buf.length;
int bytesRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < len) {
if ((len - totalBytesRead) < bytesToRead) {
bytesToRead = len - totalBytesRead;
}
if (file != null) {
bytesRead = file.read(buf, 0, bytesToRead);
} else {
bytesRead = stream.read(buf, 0, bytesToRead);
}
if (bytesRead < 0) {
// reached EOF
throw new InsufficientDataException("Insufficient data. bytes read " + totalBytesRead + " expected "
+ len);
}
if (bytesRead > 0) {
if (sha256Digest != null) {
sha256Digest.update(buf, 0, bytesRead);
}
if (md5Digest != null) {
md5Digest.update(buf, 0, bytesRead);
}
totalBytesRead += bytesRead;
}
}
// reset back to saved position.
if (file != null) {
file.seek(pos);
} else {
stream.reset();
}
return totalBytesRead;
}
}

View File

@@ -1,161 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
/**
* Amazon AWS S3 error codes.
*/
public enum ErrorCode {
// custom error codes
NO_SUCH_OBJECT("NoSuchKey", "Object does not exist"),
RESOURCE_NOT_FOUND("ResourceNotFound", "Request resource not found"),
RESOURCE_CONFLICT("ResourceConflict", "Request resource conflicts"),
// S3 error codes
ACCESS_DENIED("AccessDenied", "Access denied"),
ACCOUNT_PROBLEM("AccountProblem", "Problem with provided account"),
AMBIGUOUS_GRANT_BY_EMAIL_ADDRESS("AmbiguousGrantByEmailAddress",
"The email address you provided is associated with more than one account"),
AUTHORIZATION_HEADER_MALFORMED("AuthorizationHeaderMalformed", "The authorization header is malformed"),
BAD_DIGEST("BadDigest", "Specified Content-MD5 does not match"),
BUCKET_ALREADY_EXISTS("BucketAlreadyExists", "Bucket already exists"),
BUCKET_ALREADY_OWNED_BY_YOU("BucketAlreadyOwnedByYou", "Bucket is already owned by you"),
BUCKET_NOT_EMPTY("BucketNotEmpty", "Bucket is not empty"),
CREDENTIALS_NOT_SUPPORTED("CredentialsNotSupported", "Request does not support credentials"),
CROSS_LOCATION_LOGGING_PROHIBITED("CrossLocationLoggingProhibited", "Cross-location logging not allowed"),
ENTITY_TOO_SMALL("EntityTooSmall", "Upload is smaller than the minimum allowed object size"),
ENTITY_TOO_LARGE("EntityTooLarge", "Upload exceeds the maximum allowed object size"),
EXPIRED_TOKEN("ExpiredToken", "The provided token has expired"),
ILLEGAL_VERSIONING_CONFIGURATION_EXCEPTION("IllegalVersioningConfigurationException",
"The versioning configuration specified in the request is invalid."),
INCOMPLETE_BODY("IncompleteBody", "HTTP body size does not match with the Content-Length HTTP header"),
INCORRECT_NUMBER_OF_FILES_IN_POST_REQUEST("IncorrectNumberOfFilesInPostRequest",
"POST requires exactly one file upload per request"),
INLINE_DATA_TOO_LARGE("InlineDataTooLarge", "Inline data exceeds the maximum allowed size"),
INTERNAL_ERROR("InternalError", "Internal error. Please try again"),
INVALID_ACCESS_KEY_ID("InvalidAccessKeyId", "access key does not exist"),
INVALID_ADDRESSING_HEADER("InvalidAddressingHeader", "Invalid addressing header. Specify the Anonymous role"),
INVALID_ARGUMENT("InvalidArgument", "Invalid Argument"),
INVALID_BUCKET_NAME("InvalidBucketName", "Bucket name is not valid"),
INVALID_BUCKET_STATE("InvalidBucketState", "The request is not valid with the current state of the bucket"),
INVALID_DIGEST("InvalidDigest", "Specified Content-MD5 is not valid"),
INVALID_ENCRYPTION_ALGORITHM_ERROR("InvalidEncryptionAlgorithmError", "Invalid encryption algorithm error"),
INVALID_LOCATION_CONSTRAINT("InvalidLocationConstraint", "The specified location constraint is not valid"),
INVALID_OBJECT_STATE("InvalidObjectState", "The operation is not valid for the current state of the object"),
INVALID_PART("InvalidPart", "One or more of the specified parts could not be found"),
INVALID_PART_ORDER("InvalidPartOrder", "The list of parts was not in ascending order. "
+ "Parts list must specified in order by part number"),
INVALID_PAYER("InvalidPayer", "All access to this object has been disabled"),
INVALID_POLICY_DOCUMENT("InvalidPolicyDocument",
"The content of the form does not meet the conditions specified in the policy document"),
INVALID_RANGE("InvalidRange", "The requested range cannot be satisfied"),
INVALID_REQUEST("InvalidRequest", "SOAP requests must be made over an HTTPS connection"),
INVALID_SECURITY("InvalidSecurity", "The provided security credentials are not valid"),
INVALID_SOAP_REQUEST("InvalidSOAPRequest", "The SOAP request body is invalid"),
INVALID_STORAGE_CLASS("InvalidStorageClass", "The storage class you specified is not valid"),
INVALID_TARGET_BUCKET_FOR_LOGGING("InvalidTargetBucketForLogging",
"The target bucket for logging does not exist, is not owned by you, or does not "
+ "have the appropriate grants for the log-delivery group."),
INVALID_TOKEN("InvalidToken", "malformed or invalid token"),
INVALID_URI("InvalidURI", "Couldn't parse the specified URI"),
KEY_TOO_LONG("KeyTooLong", "Key is too long"),
MALFORMED_ACL_ERROR("MalformedACLError",
"The XML provided was not well-formed or did not validate against published schema"),
MALFORMED_POST_REQUEST("MalformedPOSTRequest", "The body of POST request is not well-formed multipart/form-data"),
MALFORMED_XML("MalformedXML", "Malformed XML"),
MAX_MESSAGE_LENGTH_EXCEEDED("MaxMessageLengthExceeded", "Request was too big"),
MAX_POST_PRE_DATA_LENGTH_EXCEEDED_ERROR("MaxPostPreDataLengthExceededError",
"POST request fields preceding the upload file were too large"),
METADATA_TOO_LARGE("MetadataTooLarge", "Metadata headers exceed the maximum allowed metadata size"),
METHOD_NOT_ALLOWED("MethodNotAllowed", "The specified method is not allowed against this resource"),
MISSING_ATTACHMENT("MissingAttachment", "A SOAP attachment was expected, but none were found"),
MISSING_CONTENT_LENGTH("MissingContentLength", "missing the Content-Length HTTP header"),
MISSING_REQUEST_BODY_ERROR("MissingRequestBodyError", "Request body is empty"),
MISSING_SECURITY_ELEMENT("MissingSecurityElement", "The SOAP 1.1 request is missing a security element"),
MISSING_SECURITY_HEADER("MissingSecurityHeader", "Request is missing a required header"),
NO_LOGGING_STATUS_FOR_KEY("NoLoggingStatusForKey",
"There is no such thing as a logging status subresource for a key"),
NO_SUCH_BUCKET("NoSuchBucket", "Bucket does not exist"),
NO_SUCH_KEY("NoSuchKey", "Object does not exist"),
NO_SUCH_LIFECYCLE_CONFIGURATION("NoSuchLifecycleConfiguration", "The lifecycle configuration does not exist"),
NO_SUCH_UPLOAD("NoSuchUpload", "Multipart upload does not exist"),
NO_SUCH_VERSION("NoSuchVersion", "Specified version ID does not match an existing version"),
NOT_IMPLEMENTED("NotImplemented", "A header you provided implies functionality that is not implemented."),
NOT_SIGNED_UP("NotSignedUp", "Account is not signed up"),
NO_SUCH_BUCKET_POLICY("NoSuchBucketPolicy", "Bucket does not have a bucket policy"),
OPERATION_ABORTED("OperationAborted", "A conflicting conditional operation is currently in progress "
+ "against this resource. Try again"),
PERMANENT_REDIRECT("PermanentRedirect", "Access to the bucket permanently redirected to this endpoint"),
PRECONDITION_FAILED("PreconditionFailed", "One of the preconditions specified did not hold"),
REDIRECT("Redirect", "Temporary redirect"),
RESTORE_ALREADY_IN_PROGRESS("RestoreAlreadyInProgress", "Object restore is already in progress"),
REQUEST_IS_NOT_MULTI_PART_CONTENT("RequestIsNotMultiPartContent",
"Bucket POST must be of the enclosure-type multipart/form-data"),
REQUEST_TIMEOUT("RequestTimeout", "request timed out"),
REQUEST_TIME_TOO_SKEWED("RequestTimeTooSkewed",
"The difference between the request time and the server's time is too large"),
REQUEST_TORRENT_OF_BUCKET_ERROR("RequestTorrentOfBucketError",
"Requesting the torrent file of a bucket is not permitted"),
SIGNATURE_DOES_NOT_MATCH("SignatureDoesNotMatch", "The request signature does not match"),
SERVICE_UNAVAILABLE("ServiceUnavailable", "Service unavailable. Retry again"),
SLOW_DOWN("SlowDown", "Reduce request rate"),
TEMPORARY_REDIRECT("TemporaryRedirect", "Temporary redirect due to DNS updates in progress"),
TOKEN_REFRESH_REQUIRED("TokenRefreshRequired", "The provided token must be refreshed"),
TOO_MANY_BUCKETS("TooManyBuckets", "Bucket creation is not allowed due to maximum limit reached"),
UNEXPECTED_CONTENT("UnexpectedContent", "Request does not support content"),
UNRESOLVABLE_GRANT_BY_EMAIL_ADDRESS("UnresolvableGrantByEmailAddress", "The email address provided does not match"),
USER_KEY_MUST_BE_SPECIFIED("UserKeyMustBeSpecified",
"The bucket POST must contain the specified field name or check the order of the fields"),
X_AMZ_CONTENT_SHA256_MISMATCH("XAmzContentSHA256Mismatch",
"content SHA256 mismatch");
private final String code;
private final String message;
private ErrorCode(String code, String message) {
this.code = code;
this.message = message;
}
/**
* Returns ErrorCode of given code string.
*/
public static ErrorCode fromString(String codeString) {
if (codeString == null) {
return null;
}
for (ErrorCode ec : ErrorCode.values()) {
if (codeString.equals(ec.code)) {
return ec;
}
}
// Unknown error code string. Its not a standard Amazon S3 error.
return null;
}
public String code() {
return this.code;
}
public String message() {
return this.message;
}
}

View File

@@ -1,85 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
import okio.Okio;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.channels.Channels;
/**
* RequestBody that wraps a single data object.
*/
class HttpRequestBody extends RequestBody {
private final String contentType;
private final Object data;
private final int len;
HttpRequestBody(final String contentType, final Object data, final int len) {
this.contentType = contentType;
this.data = data;
this.len = len;
}
@Override
public MediaType contentType() {
MediaType mediaType = null;
if (contentType != null) {
mediaType = MediaType.parse(contentType);
}
if (mediaType == null) {
mediaType = MediaType.parse("application/octet-stream");
}
return mediaType;
}
@Override
public long contentLength() {
if (data instanceof InputStream || data instanceof RandomAccessFile || data instanceof byte[]) {
return len;
}
if (len == 0) {
return -1;
} else {
return len;
}
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
if (data instanceof InputStream) {
InputStream stream = (InputStream) data;
sink.writeAll(Okio.source(stream));
} else if (data instanceof RandomAccessFile) {
RandomAccessFile file = (RandomAccessFile) data;
sink.write(Okio.source(Channels.newInputStream(file.getChannel())), len);
} else if (data instanceof byte[]) {
byte[] bytes = (byte[]) data;
sink.write(bytes, 0, len);
} else {
sink.writeUtf8(data.toString());
}
}
}

View File

@@ -1,68 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.util.List;
import java.util.Map;
/**
* Packs {@link ResponseHeader} and {@link Response} into one object to pass/return in various methods.
*/
class HttpResponse {
ResponseHeader header;
Response response;
public HttpResponse(ResponseHeader header, Response response) {
this.header = header;
this.response = response;
}
/**
* Gets header.
*/
public ResponseHeader header() {
return this.header;
}
/**
* Gets body.
*/
public ResponseBody body() {
return this.response.body();
}
/**
* Gets Response.
*/
public Response response() {
return this.response;
}
/**
* Gets HTTP headers.
*/
public Map<String, List<String>> httpHeaders() {
return this.response.headers().toMultimap();
}
}

View File

@@ -1,79 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicReference;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Identifies and stores version information of minio-java package at run time.
*/
enum MinioProperties {
INSTANCE;
private static final Logger LOGGER = Logger.getLogger(MinioProperties.class.getName());
private final AtomicReference<String> version = new AtomicReference<>(null);
public String getVersion() {
String result = version.get();
if (result == null) {
synchronized (INSTANCE) {
if (version.get() == null) {
try {
ClassLoader classLoader = getClass().getClassLoader();
setMinioClientJavaVersion(classLoader);
setDevelopmentVersion();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "IOException occured", e);
version.set("unknown");
}
result = version.get();
}
}
}
return result;
}
private void setDevelopmentVersion() {
if (version.get() == null) {
version.set("dev");
}
}
private void setMinioClientJavaVersion(ClassLoader classLoader) throws IOException {
if (classLoader != null) {
Enumeration<URL> resources = classLoader.getResources("META-INF/MANIFEST.MF");
while (resources.hasMoreElements()) {
Manifest manifest = new Manifest(resources.nextElement().openStream());
for (Object k : manifest.getMainAttributes().keySet()) {
String versionString = "MinIO-Client-Java-Version";
if (k.toString().equals(versionString)) {
version.set(manifest.getMainAttributes().getValue((Attributes.Name) k));
}
}
}
}
}
}

View File

@@ -1,205 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Object stat information.
*/
@SuppressWarnings("unused")
public class ObjectStat {
private final String bucketName;
private final String name;
private final Date createdTime;
private final long length;
private final String etag;
private final String contentType;
private final Map<String, List<String>> httpHeaders;
/**
* Creates ObjectStat with given bucket name, object name, and available response header information.
*/
public ObjectStat(String bucketName, String name, ResponseHeader header) {
this(bucketName, name, header, null);
}
/**
* Creates ObjectStat with given bucket name, object name, available response header and HTTP Headers from response.
*/
public ObjectStat(String bucketName, String name, ResponseHeader header, Map<String, List<String>> httpHeaders) {
this.bucketName = bucketName;
this.name = name;
this.contentType = header.contentType();
this.createdTime = (Date) header.lastModified().clone();
this.length = header.contentLength();
if (header.etag() != null) {
this.etag = header.etag().replaceAll("\"", "");
} else {
this.etag = "";
}
this.httpHeaders = httpHeaders;
}
/**
* Creates ObjectStat with given bucket name, object name, created time, object length, Etag and content type.
*/
public ObjectStat(String bucketName, String name, Date createdTime, long length, String etag, String contentType) {
this.bucketName = bucketName;
this.name = name;
this.contentType = contentType;
this.createdTime = (Date) createdTime.clone();
this.length = length;
if (etag != null) {
this.etag = etag.replaceAll("\"", "");
} else {
this.etag = "";
}
this.httpHeaders = null;
}
/**
* Checks whether given object is same as this ObjectStat.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ObjectStat that = (ObjectStat) o;
if (length != that.length) {
return false;
}
if (!bucketName.equals(that.bucketName)) {
return false;
}
if (!name.equals(that.name)) {
return false;
}
if (!createdTime.equals(that.createdTime)) {
return false;
}
if (!etag.equals(that.etag)) {
return false;
}
return contentType.equals(that.contentType);
}
/**
* Returns hash of this ObjectStat.
*/
@Override
public int hashCode() {
int result = bucketName.hashCode();
result = 31 * result + name.hashCode();
result = 31 * result + createdTime.hashCode();
result = 31 * result + (int) (length ^ (length >>> 32));
result = 31 * result + etag.hashCode();
result = 31 * result + contentType.hashCode();
return result;
}
/**
* Returns bucket name.
*/
public String bucketName() {
return bucketName;
}
/**
* Returns object name.
*/
public String name() {
return name;
}
/**
* Returns created time.
*/
public Date createdTime() {
return (Date) createdTime.clone();
}
/**
* Returns object length.
*/
public long length() {
return length;
}
/**
* Returns ETag.
*/
public String etag() {
return etag;
}
/**
* Returns content type of object.
*/
public String contentType() {
return contentType;
}
/**
* Returns ObjectStat as string.
*/
@Override
public String toString() {
return "ObjectStat{"
+ "bucket='"
+ bucketName
+ '\''
+ ", name='"
+ name + '\''
+ ", contentType='"
+ contentType
+ '\''
+ ", createdTime="
+ createdTime
+ ", length="
+ length
+ ", etag='"
+ etag
+ '\''
+ '}';
}
/**
* Gets HTTP headers.
*/
public Map<String, List<String>> httpHeaders() {
return httpHeaders;
}
}

View File

@@ -1,255 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.io.BaseEncoding;
import it.integry.ems.object_storage.minio.sdk.errors.InvalidArgumentException;
import org.joda.time.DateTime;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.ListIterator;
import java.util.Map;
/**
* Post policy information to be used to generate presigned post policy form-data.
*/
public class PostPolicy {
private static final String ALGORITHM = "AWS4-HMAC-SHA256";
private final String bucketName;
private final String objectName;
private final boolean startsWith;
private final DateTime expirationDate;
private String contentType;
private int successActionStatus;
private String contentEncoding;
private long contentRangeStart;
private long contentRangeEnd;
public PostPolicy(String bucketName, String objectName, DateTime expirationDate)
throws InvalidArgumentException {
this(bucketName, objectName, false, expirationDate);
}
/**
* Creates PostPolicy for given bucket name, object name, string to match object name starting with
* and expiration time.
*/
public PostPolicy(String bucketName, String objectName, boolean startsWith, DateTime expirationDate)
throws InvalidArgumentException {
if (bucketName == null) {
throw new InvalidArgumentException("null bucket name");
}
this.bucketName = bucketName;
if (objectName == null) {
throw new InvalidArgumentException("null object name or prefix");
}
this.objectName = objectName;
this.startsWith = startsWith;
if (expirationDate == null) {
throw new InvalidArgumentException("null expiration date");
}
this.expirationDate = expirationDate;
}
/**
* Sets content type.
*/
public void setContentType(String contentType) throws InvalidArgumentException {
if (Strings.isNullOrEmpty(contentType)) {
throw new InvalidArgumentException("empty content type");
}
this.contentType = contentType;
}
/**
* Sets success action status.
*/
public void setSuccessActionStatus(int successActionStatus) throws InvalidArgumentException {
if (!(successActionStatus == SuccessActionStatus.SuccessActionStatus200.getValue()
|| successActionStatus == SuccessActionStatus.SuccessActionStatus201.getValue()
|| successActionStatus == SuccessActionStatus.SuccessActionStatus204.getValue())) {
throw new InvalidArgumentException("Invalid action status, acceptable values are 200, 201, or 204");
}
this.successActionStatus = successActionStatus;
}
/**
* Sets content encoding.
*/
public void setContentEncoding(String contentEncoding) throws InvalidArgumentException {
if (Strings.isNullOrEmpty(contentEncoding)) {
throw new InvalidArgumentException("empty content encoding");
}
this.contentEncoding = contentEncoding;
}
/**
* Sets content length.
*/
public void setContentLength(long contentLength) throws InvalidArgumentException {
if (contentLength <= 0) {
throw new InvalidArgumentException("negative content length");
}
this.setContentRange(contentLength, contentLength);
}
/**
* Sets content range.
*/
public void setContentRange(long startRange, long endRange) throws InvalidArgumentException {
if (startRange <= 0 || endRange <= 0) {
throw new InvalidArgumentException("negative start/end range");
}
if (startRange > endRange) {
throw new InvalidArgumentException("start range is higher than end range");
}
this.contentRangeStart = startRange;
this.contentRangeEnd = endRange;
}
/**
* Returns bucket name.
*/
public String bucketName() {
return this.bucketName;
}
private byte[] marshalJson(ArrayList<String[]> conditions) {
StringBuilder sb = new StringBuilder();
Joiner joiner = Joiner.on("\",\"");
sb.append("{");
if (expirationDate != null) {
sb.append("\"expiration\":" + "\"" + expirationDate.toString(DateFormat.EXPIRATION_DATE_FORMAT) + "\"");
}
if (!conditions.isEmpty()) {
sb.append(",\"conditions\":[");
ListIterator<String[]> iterator = conditions.listIterator();
while (iterator.hasNext()) {
sb.append("[\"" + joiner.join(iterator.next()) + "\"]");
if (iterator.hasNext()) {
sb.append(",");
}
}
sb.append("]");
}
sb.append("}");
return sb.toString().getBytes(StandardCharsets.UTF_8);
}
/**
* Returns form data of this post policy setting the provided region.
*/
public Map<String, String> formData(String accessKey, String secretKey, String region)
throws NoSuchAlgorithmException, InvalidKeyException, InvalidArgumentException {
if (Strings.isNullOrEmpty(region)) {
throw new InvalidArgumentException("empty region");
}
return makeFormData(accessKey, secretKey, region);
}
protected Map<String, String> makeFormData(String accessKey, String secretKey, String region)
throws NoSuchAlgorithmException, InvalidKeyException {
ArrayList<String[]> conditions = new ArrayList<>();
Map<String, String> formData = new HashMap<>();
conditions.add(new String[]{"eq", "$bucket", this.bucketName});
formData.put("bucket", this.bucketName);
if (this.startsWith) {
conditions.add(new String[]{"starts-with", "$key", this.objectName});
formData.put("key", this.objectName);
} else {
conditions.add(new String[]{"eq", "$key", this.objectName});
formData.put("key", this.objectName);
}
if (this.contentType != null) {
conditions.add(new String[]{"eq", "$Content-Type", this.contentType});
formData.put("Content-Type", this.contentType);
}
if (this.contentEncoding != null) {
conditions.add(new String[]{"eq", "$Content-Encoding", this.contentEncoding});
formData.put("Content-Encoding", this.contentEncoding);
}
if (this.successActionStatus > 0) {
conditions.add(new String[]{"eq", "$success_action_status", Integer.toString(this.successActionStatus)});
formData.put("success_action_status", Integer.toString(this.successActionStatus));
}
if (this.contentRangeStart > 0 && this.contentRangeEnd > 0) {
conditions.add(new String[]{"content-length-range", Long.toString(this.contentRangeStart),
Long.toString(this.contentRangeEnd)});
}
conditions.add(new String[]{"eq", "$x-amz-algorithm", ALGORITHM});
formData.put("x-amz-algorithm", ALGORITHM);
DateTime date = new DateTime();
String credential = Signer.credential(accessKey, date, region);
conditions.add(new String[]{"eq", "$x-amz-credential", credential});
formData.put("x-amz-credential", credential);
String amzDate = date.toString(DateFormat.AMZ_DATE_FORMAT);
conditions.add(new String[]{"eq", "$x-amz-date", amzDate});
formData.put("x-amz-date", amzDate);
String policybase64 = BaseEncoding.base64().encode(this.marshalJson(conditions));
String signature = Signer.postPresignV4(policybase64, secretKey, date, region);
formData.put("policy", policybase64);
formData.put("x-amz-signature", signature);
return formData;
}
}

View File

@@ -1,229 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import it.integry.ems.object_storage.minio.sdk.http.Header;
import org.joda.time.DateTime;
import java.util.Date;
/**
* HTTP response header class.
*/
@SuppressFBWarnings(value = "UwF", justification = "Everything in this class is initialized with reflections.")
public class ResponseHeader {
@Header("Content-Length")
private long contentLength;
@Header("Content-Type")
private String contentType;
@Header("Date")
private DateTime date;
@Header("ETag")
private String etag;
@Header("Last-Modified")
private DateTime lastModified;
@Header("Server")
private String server;
@Header("Status Code")
private String statusCode;
@Header("Transfer-Encoding")
private String transferEncoding;
@Header("x-amz-bucket-region")
private String xamzBucketRegion;
@Header("x-amz-id-2")
private String xamzId2;
@Header("x-amz-request-id")
private String xamzRequestId;
/**
* Sets content length.
*/
public void setContentLength(String contentLength) {
this.contentLength = Long.parseLong(contentLength);
}
/**
* Returns content length.
*/
public long contentLength() {
return this.contentLength;
}
/**
* Sets content type.
*/
public void setContentType(String contentType) {
this.contentType = contentType;
}
/**
* Returns content type.
*/
public String contentType() {
return this.contentType;
}
/**
* Sets date.
*/
public void setDate(String date) {
this.date = DateFormat.HTTP_HEADER_DATE_FORMAT.parseDateTime(date);
}
/**
* Returns date.
*/
public Date date() {
return this.date.toDate();
}
/**
* Sets ETag.
*/
public void setEtag(String etag) {
this.etag = etag.replaceAll("\"", "");
}
/**
* Returns ETag.
*/
public String etag() {
return this.etag;
}
/**
* Sets last modified time.
*/
public void setLastModified(String lastModified) {
this.lastModified = DateFormat.HTTP_HEADER_DATE_FORMAT.parseDateTime(lastModified);
}
/**
* Returns last modified time.
*/
public Date lastModified() {
return this.lastModified.toDate();
}
/**
* Sets server name.
*/
public void setServer(String server) {
this.server = server;
}
/**
* Returns server name.
*/
public String server() {
return this.server;
}
/**
* Sets status code.
*/
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
/**
* Returns status code.
*/
public String statusCode() {
return this.statusCode;
}
/**
* Sets transfer encoding.
*/
public void setTransferEncoding(String transferEncoding) {
this.transferEncoding = transferEncoding;
}
/**
* Returns transfer encoding.
*/
public String transferEncoding() {
return this.transferEncoding;
}
/**
* Sets Amazon bucket region.
*/
public void setXamzBucketRegion(String xamzBucketRegion) {
this.xamzBucketRegion = xamzBucketRegion;
}
/**
* Returns Amazon bucket region.
*/
public String xamzBucketRegion() {
return this.xamzBucketRegion;
}
/**
* Sets Amazon ID2.
*/
public void setXamzId2(String xamzId2) {
this.xamzId2 = xamzId2;
}
/**
* Returns Amazon ID2.
*/
public String xamzId2() {
return this.xamzId2;
}
/**
* Sets Amazon request ID.
*/
public void setXamzRequestId(String xamzRequestId) {
this.xamzRequestId = xamzRequestId;
}
/**
* Returns Amazon request ID.
*/
public String xamzRequestId() {
return this.xamzRequestId;
}
}

View File

@@ -1,72 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import it.integry.ems.object_storage.minio.sdk.errors.*;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* A container class keeps any type and exception occured.
*/
public class Result<T> {
private final T type;
private final Exception ex;
public Result(T type, Exception ex) {
this.type = type;
this.ex = ex;
}
/**
* Returns given Type if exception is null, else respective exception is thrown.
*/
public T get()
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException {
if (ex == null) {
return type;
}
if (ex instanceof InvalidBucketNameException) {
throw (InvalidBucketNameException) ex;
} else if (ex instanceof NoSuchAlgorithmException) {
throw (NoSuchAlgorithmException) ex;
} else if (ex instanceof InsufficientDataException) {
throw (InsufficientDataException) ex;
} else if (ex instanceof IOException) {
throw (IOException) ex;
} else if (ex instanceof InvalidKeyException) {
throw (InvalidKeyException) ex;
} else if (ex instanceof NoResponseException) {
throw (NoResponseException) ex;
} else if (ex instanceof XmlPullParserException) {
throw (XmlPullParserException) ex;
} else if (ex instanceof ErrorResponseException) {
throw (ErrorResponseException) ex;
} else {
throw (InternalException) ex;
}
}
}

View File

@@ -1,76 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2016 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import com.google.common.escape.Escaper;
import com.google.common.net.UrlEscapers;
class S3Escaper {
private static final Escaper ESCAPER = UrlEscapers.urlPathSegmentEscaper();
/**
* Returns S3 encoded string.
*/
public static String encode(String str) {
if (str == null) {
return "";
}
return ESCAPER.escape(str)
.replaceAll("\\!", "%21")
.replaceAll("\\$", "%24")
.replaceAll("\\&", "%26")
.replaceAll("\\'", "%27")
.replaceAll("\\(", "%28")
.replaceAll("\\)", "%29")
.replaceAll("\\*", "%2A")
.replaceAll("\\+", "%2B")
.replaceAll("\\,", "%2C")
.replaceAll("\\/", "%2F")
.replaceAll("\\:", "%3A")
.replaceAll("\\;", "%3B")
.replaceAll("\\=", "%3D")
.replaceAll("\\@", "%40")
.replaceAll("\\[", "%5B")
.replaceAll("\\]", "%5D");
}
/**
* Returns S3 encoded string of given path where multiple '/' are trimmed.
*/
public static String encodePath(String path) {
StringBuffer encodedPathBuf = new StringBuffer();
for (String pathSegment : path.split("/")) {
if (!pathSegment.isEmpty()) {
if (encodedPathBuf.length() > 0) {
encodedPathBuf.append("/");
}
encodedPathBuf.append(S3Escaper.encode(pathSegment));
}
}
if (path.startsWith("/")) {
encodedPathBuf.insert(0, "/");
}
if (path.endsWith("/")) {
encodedPathBuf.append("/");
}
return encodedPathBuf.toString();
}
}

View File

@@ -1,328 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import com.google.common.io.BaseEncoding;
import it.integry.ems.object_storage.minio.sdk.errors.InvalidArgumentException;
import javax.crypto.SecretKey;
import javax.security.auth.DestroyFailedException;
import javax.security.auth.Destroyable;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
/**
* ServerSideEncryption represents a form of server-side encryption.
*/
public abstract class ServerSideEncryption implements Destroyable {
protected boolean destroyed = false;
private static boolean isCustomerKeyValid(SecretKey key) {
if (key == null) {
return false;
}
return !key.isDestroyed() && key.getAlgorithm().equals("AES") && key.getEncoded().length == 32;
}
/**
* Create a new server-side-encryption object for encryption with customer
* provided keys (a.k.a. SSE-C).
*
* @param key The secret AES-256 key.
* @return An instance of ServerSideEncryption implementing SSE-C.
* @throws InvalidKeyException if the provided secret key is not a 256 bit AES key.
* @throws NoSuchAlgorithmException if the crypto provider does not implement MD5.
*/
public static ServerSideEncryption withCustomerKey(SecretKey key)
throws InvalidKeyException, NoSuchAlgorithmException {
if (!isCustomerKeyValid(key)) {
throw new InvalidKeyException("The secret key is not a 256 bit AES key");
}
return new ServerSideEncryptionWithCustomerKey(key, MessageDigest.getInstance(("MD5")));
}
/**
* Create a new server-side-encryption object for encryption with customer
* provided keys (a.k.a. SSE-C).
*
* @param key The secret AES-256 key.
* @return An instance of ServerSideEncryption implementing SSE-C.
* @throws InvalidKeyException if the provided secret key is not a 256 bit AES key.
* @throws NoSuchAlgorithmException if the crypto provider does not implement MD5.
* @deprecated As of release 7.0
*/
@Deprecated
public static ServerSideEncryption copyWithCustomerKey(SecretKey key)
throws InvalidKeyException, NoSuchAlgorithmException {
if (!isCustomerKeyValid(key)) {
throw new InvalidKeyException("The secret key is not a 256 bit AES key");
}
return new ServerSideEncryptionCopyWithCustomerKey(key, MessageDigest.getInstance(("MD5")));
}
/**
* Create a new server-side-encryption object for encryption at rest (a.k.a. SSE-S3).
*
* @return an instance of ServerSideEncryption implementing SSE-S3
*/
public static ServerSideEncryption atRest() {
return new ServerSideEncryptionS3();
}
/**
* Create a new server-side-encryption object for encryption using a KMS (a.k.a. SSE-KMS).
*
* @param keyId specifies the customer-master-key (CMK) and must not be null.
* @param context is the encryption context. If the context is null no context is used.
* @return an instance of ServerSideEncryption implementing SSE-KMS.
*/
public static ServerSideEncryption withManagedKeys(String keyId, Map<String, String> context)
throws InvalidArgumentException, UnsupportedEncodingException {
if (keyId == null) {
throw new InvalidArgumentException("The key-ID cannot be null");
}
if (context == null) {
return new ServerSideEncryptionKms(keyId, Optional.empty());
}
StringBuilder builder = new StringBuilder();
int i = 0;
builder.append('{');
for (Entry<String, String> entry : context.entrySet()) {
builder.append('"');
builder.append(entry.getKey());
builder.append('"');
builder.append(':');
builder.append('"');
builder.append(entry.getValue());
builder.append('"');
if (i < context.entrySet().size() - 1) {
builder.append(',');
}
}
builder.append('}');
String contextString = BaseEncoding.base64().encode(builder.toString().getBytes("UTF-8"));
return new ServerSideEncryptionKms(keyId, Optional.of(contextString));
}
/**
* Returns server side encryption type.
*/
public abstract Type type();
/**
* Returns server side encryption headers.
*/
public abstract Map<String, String> headers();
/**
* Returns server side encryption headers for source object in Put Object - Copy.
*/
public Map<String, String> copySourceHeaders() throws InvalidArgumentException {
throw new InvalidArgumentException(this.type().name() + " is not supported in copy source");
}
/**
* Returns the type of server-side encryption.
*
* @return the type of server-side encryption.
* @deprecated As of release 7.0
*/
@Deprecated
public Type getType() {
return this.type();
}
/**
* Set the server-side-encryption headers of this specific encryption.
*
* @param headers The metadata key-value map.
* @deprecated As of release 7.0
*/
@Deprecated
public void marshal(Map<String, String> headers) {
headers.putAll(this.headers());
}
@Override
public boolean isDestroyed() {
return this.destroyed;
}
/**
* The types of server-side encryption.
*/
public static enum Type {
SSE_C, SSE_S3, SSE_KMS;
/**
* Returns true if the server-side encryption requires a TLS connection.
*
* @return true if the type of server-side encryption requires TLS.
*/
public boolean requiresTls() {
return this.equals(SSE_C) || this.equals(SSE_KMS);
}
/**
* Returns true if the server-side encryption requires signature V4.
*
* @return true if the type of server-side encryption requires signature V4.
* @deprecated As of release 7.0
*/
@Deprecated
public boolean requiresV4() {
return this.equals(SSE_KMS);
}
}
static class ServerSideEncryptionWithCustomerKey extends ServerSideEncryption {
protected final SecretKey secretKey;
protected final MessageDigest md5;
public ServerSideEncryptionWithCustomerKey(SecretKey key, MessageDigest md5) {
this.secretKey = key;
this.md5 = md5;
}
@Override
public final Type type() {
return Type.SSE_C;
}
@Override
public final Map<String, String> headers() {
if (this.isDestroyed()) {
throw new IllegalStateException("object is already destroyed");
}
Map<String, String> headers = new HashMap<>();
try {
final byte[] key = secretKey.getEncoded();
md5.update(key);
headers.put("X-Amz-Server-Side-Encryption-Customer-Algorithm", "AES256");
headers.put("X-Amz-Server-Side-Encryption-Customer-Key", BaseEncoding.base64().encode(key));
headers.put("X-Amz-Server-Side-Encryption-Customer-Key-Md5", BaseEncoding.base64().encode(md5.digest()));
} finally {
md5.reset();
}
return headers;
}
@Override
public final Map<String, String> copySourceHeaders() {
if (this.isDestroyed()) {
throw new IllegalStateException("object is already destroyed");
}
Map<String, String> headers = new HashMap<>();
try {
final byte[] key = secretKey.getEncoded();
md5.update(key);
headers.put("X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm", "AES256");
headers.put("X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key", BaseEncoding.base64().encode(key));
headers.put("X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5",
BaseEncoding.base64().encode(md5.digest()));
} finally {
md5.reset();
}
return headers;
}
@Override
public final void destroy() throws DestroyFailedException {
secretKey.destroy();
this.destroyed = true;
}
}
/**
* @deprecated As of release 7.0
*/
@Deprecated
static final class ServerSideEncryptionCopyWithCustomerKey extends ServerSideEncryptionWithCustomerKey {
public ServerSideEncryptionCopyWithCustomerKey(SecretKey key, MessageDigest md5) {
super(key, md5);
}
}
static final class ServerSideEncryptionS3 extends ServerSideEncryption {
@Override
public final Type type() {
return Type.SSE_S3;
}
@Override
public final Map<String, String> headers() {
Map<String, String> headers = new HashMap<>();
headers.put("X-Amz-Server-Side-Encryption", "AES256");
return headers;
}
@Override
public final void destroy() throws DestroyFailedException {
this.destroyed = true;
}
}
static final class ServerSideEncryptionKms extends ServerSideEncryption {
final String keyId;
final Optional<String> context;
public ServerSideEncryptionKms(String keyId, Optional<String> context) {
this.keyId = keyId;
this.context = context;
}
@Override
public final Type type() {
return Type.SSE_KMS;
}
@Override
public final Map<String, String> headers() {
if (this.isDestroyed()) {
throw new IllegalStateException("object is already destroyed");
}
Map<String, String> headers = new HashMap<>();
headers.put("X-Amz-Server-Side-Encryption", "aws:kms");
headers.put("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id", keyId);
if (context.isPresent()) {
headers.put("X-Amz-Server-Side-Encryption-Context", context.get());
}
return headers;
}
@Override
public final void destroy() throws DestroyFailedException {
this.destroyed = true;
}
}
}

View File

@@ -1,357 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
import com.google.common.base.Joiner;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import com.google.common.io.BaseEncoding;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Request;
import org.joda.time.DateTime;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
/**
* Amazon AWS S3 signature V4 signer.
*/
class Signer {
//
// Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258
//
// User-Agent:
//
// This is ignored from signing because signing this causes problems with generating pre-signed URLs
// (that are executed by other agents) or when customers pass requests through proxies, which may
// modify the user-agent.
//
// Content-Length:
//
// This is ignored from signing because generating a pre-signed URL should not provide a content-length
// constraint, specifically when vending a S3 pre-signed PUT URL. The corollary to this is that when
// sending regular requests (non-pre-signed), the signature contains a checksum of the body, which
// implicitly validates the payload length (since changing the number of bytes would change the checksum)
// and therefore this header is not valuable in the signature.
//
// Content-Type:
//
// Signing this header causes quite a number of problems in browser environments, where browsers
// like to modify and normalize the content-type header in different ways. There is more information
// on this in https://github.com/aws/aws-sdk-js/issues/244. Avoiding this field simplifies logic
// and reduces the possibility of future bugs
//
// Authorization:
//
// Is skipped for obvious reasons
//
private static final Set<String> IGNORED_HEADERS = new HashSet<>();
static {
IGNORED_HEADERS.add("authorization");
IGNORED_HEADERS.add("content-type");
IGNORED_HEADERS.add("content-length");
IGNORED_HEADERS.add("user-agent");
}
private Request request;
private String contentSha256;
private DateTime date;
private String region;
private String accessKey;
private String secretKey;
private String prevSignature;
private String scope;
private Map<String, String> canonicalHeaders;
private String signedHeaders;
private HttpUrl url;
private String canonicalQueryString;
private String canonicalRequest;
private String canonicalRequestHash;
private String stringToSign;
private byte[] signingKey;
private String signature;
private String authorization;
/**
* Create new Signer object for V4.
*
* @param request HTTP Request object.
* @param contentSha256 SHA-256 hash of request payload.
* @param date Date to be used to sign the request.
* @param region Amazon AWS region for the request.
* @param accessKey Access Key string.
* @param secretKey Secret Key string.
* @param prevSignature Previous signature of chunk upload.
*/
public Signer(Request request, String contentSha256, DateTime date, String region, String accessKey,
String secretKey, String prevSignature) {
this.request = request;
this.contentSha256 = contentSha256;
this.date = date;
this.region = region;
this.accessKey = accessKey;
this.secretKey = secretKey;
this.prevSignature = prevSignature;
}
/**
* Returns chunk signature calculated using given arguments.
*/
public static String getChunkSignature(String chunkSha256, DateTime date, String region, String secretKey,
String prevSignature)
throws NoSuchAlgorithmException, InvalidKeyException {
Signer signer = new Signer(null, chunkSha256, date, region, null, secretKey, prevSignature);
signer.setScope();
signer.setChunkStringToSign();
signer.setSigningKey();
signer.setSignature();
return signer.signature;
}
/**
* Returns seed signature for given request.
*/
public static String getChunkSeedSignature(Request request, String region, String secretKey)
throws NoSuchAlgorithmException, InvalidKeyException {
String contentSha256 = request.header("x-amz-content-sha256");
DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date"));
Signer signer = new Signer(request, contentSha256, date, region, null, secretKey, null);
signer.setScope();
signer.setCanonicalRequest();
signer.setStringToSign();
signer.setSigningKey();
signer.setSignature();
return signer.signature;
}
/**
* Returns signed request object for given request, region, access key and secret key.
*/
public static Request signV4(Request request, String region, String accessKey, String secretKey)
throws NoSuchAlgorithmException, InvalidKeyException {
String contentSha256 = request.header("x-amz-content-sha256");
DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date"));
Signer signer = new Signer(request, contentSha256, date, region, accessKey, secretKey, null);
signer.setScope();
signer.setCanonicalRequest();
signer.setStringToSign();
signer.setSigningKey();
signer.setSignature();
signer.setAuthorization();
return request.newBuilder().header("Authorization", signer.authorization).build();
}
/**
* Returns pre-signed HttpUrl object for given request, region, access key, secret key and expires time.
*/
public static HttpUrl presignV4(Request request, String region, String accessKey, String secretKey, int expires)
throws NoSuchAlgorithmException, InvalidKeyException {
String contentSha256 = "UNSIGNED-PAYLOAD";
DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date"));
Signer signer = new Signer(request, contentSha256, date, region, accessKey, secretKey, null);
signer.setScope();
signer.setPresignCanonicalRequest(expires);
signer.setStringToSign();
signer.setSigningKey();
signer.setSignature();
return signer.url.newBuilder()
.addEncodedQueryParameter(S3Escaper.encode("X-Amz-Signature"), S3Escaper.encode(signer.signature))
.build();
}
/**
* Returns credential string of given access key, date and region.
*/
public static String credential(String accessKey, DateTime date, String region) {
return accessKey + "/" + date.toString(DateFormat.SIGNER_DATE_FORMAT) + "/" + region + "/s3/aws4_request";
}
/**
* Returns pre-signed post policy string for given stringToSign, secret key, date and region.
*/
public static String postPresignV4(String stringToSign, String secretKey, DateTime date, String region)
throws NoSuchAlgorithmException, InvalidKeyException {
Signer signer = new Signer(null, null, date, region, null, secretKey, null);
signer.stringToSign = stringToSign;
signer.setSigningKey();
signer.setSignature();
return signer.signature;
}
/**
* Returns HMacSHA256 digest of given key and data.
*/
public static byte[] sumHmac(byte[] key, byte[] data)
throws NoSuchAlgorithmException, InvalidKeyException {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
mac.update(data);
return mac.doFinal();
}
private void setScope() {
this.scope = this.date.toString(DateFormat.SIGNER_DATE_FORMAT) + "/" + this.region + "/s3/aws4_request";
}
private void setCanonicalHeaders() {
this.canonicalHeaders = new TreeMap<>();
Headers headers = this.request.headers();
for (String name : headers.names()) {
String signedHeader = name.toLowerCase(Locale.US);
if (!IGNORED_HEADERS.contains(signedHeader)) {
this.canonicalHeaders.put(signedHeader, headers.get(name));
}
}
this.signedHeaders = Joiner.on(";").join(this.canonicalHeaders.keySet());
}
private void setCanonicalQueryString() {
String encodedQuery = this.url.encodedQuery();
if (encodedQuery == null) {
this.canonicalQueryString = "";
return;
}
// Building a multimap which only order keys, ordering values is not performed
// until MinIO server supports it.
Multimap<String, String> signedQueryParams = MultimapBuilder.treeKeys().arrayListValues().build();
for (String queryParam : encodedQuery.split("&")) {
String[] tokens = queryParam.split("=");
if (tokens.length > 1) {
signedQueryParams.put(tokens[0], tokens[1]);
} else {
signedQueryParams.put(tokens[0], "");
}
}
this.canonicalQueryString = Joiner.on("&").withKeyValueSeparator("=").join(signedQueryParams.entries());
}
private void setCanonicalRequest() throws NoSuchAlgorithmException {
setCanonicalHeaders();
this.url = this.request.url();
setCanonicalQueryString();
// CanonicalRequest =
// HTTPRequestMethod + '\n' +
// CanonicalURI + '\n' +
// CanonicalQueryString + '\n' +
// CanonicalHeaders + '\n' +
// SignedHeaders + '\n' +
// HexEncode(Hash(RequestPayload))
this.canonicalRequest = this.request.method() + "\n"
+ this.url.encodedPath() + "\n"
+ this.canonicalQueryString + "\n"
+ Joiner.on("\n").withKeyValueSeparator(":").join(this.canonicalHeaders) + "\n\n"
+ this.signedHeaders + "\n"
+ this.contentSha256;
this.canonicalRequestHash = Digest.sha256Hash(this.canonicalRequest);
}
private void setStringToSign() {
this.stringToSign = "AWS4-HMAC-SHA256" + "\n"
+ this.date.toString(DateFormat.AMZ_DATE_FORMAT) + "\n"
+ this.scope + "\n"
+ this.canonicalRequestHash;
}
private void setChunkStringToSign() throws NoSuchAlgorithmException {
this.stringToSign = "AWS4-HMAC-SHA256-PAYLOAD" + "\n"
+ this.date.toString(DateFormat.AMZ_DATE_FORMAT) + "\n"
+ this.scope + "\n"
+ this.prevSignature + "\n"
+ Digest.sha256Hash("") + "\n"
+ this.contentSha256;
}
private void setSigningKey() throws NoSuchAlgorithmException, InvalidKeyException {
String aws4SecretKey = "AWS4" + this.secretKey;
byte[] dateKey = sumHmac(aws4SecretKey.getBytes(StandardCharsets.UTF_8),
this.date.toString(DateFormat.SIGNER_DATE_FORMAT).getBytes(StandardCharsets.UTF_8));
byte[] dateRegionKey = sumHmac(dateKey, this.region.getBytes(StandardCharsets.UTF_8));
byte[] dateRegionServiceKey = sumHmac(dateRegionKey, "s3".getBytes(StandardCharsets.UTF_8));
this.signingKey = sumHmac(dateRegionServiceKey, "aws4_request".getBytes(StandardCharsets.UTF_8));
}
private void setSignature() throws NoSuchAlgorithmException, InvalidKeyException {
byte[] digest = sumHmac(this.signingKey, this.stringToSign.getBytes(StandardCharsets.UTF_8));
this.signature = BaseEncoding.base16().encode(digest).toLowerCase(Locale.US);
}
private void setAuthorization() {
this.authorization = "AWS4-HMAC-SHA256 Credential=" + this.accessKey + "/" + this.scope + ", SignedHeaders="
+ this.signedHeaders + ", Signature=" + this.signature;
}
private void setPresignCanonicalRequest(int expires) throws NoSuchAlgorithmException {
this.canonicalHeaders = new TreeMap<>();
this.canonicalHeaders.put("host", this.request.headers().get("Host"));
this.signedHeaders = "host";
HttpUrl.Builder urlBuilder = this.request.url().newBuilder();
// order of queryparam addition is important ie has to be sorted.
urlBuilder.addEncodedQueryParameter(S3Escaper.encode("X-Amz-Algorithm"),
S3Escaper.encode("AWS4-HMAC-SHA256"));
urlBuilder.addEncodedQueryParameter(S3Escaper.encode("X-Amz-Credential"),
S3Escaper.encode(this.accessKey + "/" + this.scope));
urlBuilder.addEncodedQueryParameter(S3Escaper.encode("X-Amz-Date"),
S3Escaper.encode(this.date.toString(DateFormat.AMZ_DATE_FORMAT)));
urlBuilder.addEncodedQueryParameter(S3Escaper.encode("X-Amz-Expires"),
S3Escaper.encode(Integer.toString(expires)));
urlBuilder.addEncodedQueryParameter(S3Escaper.encode("X-Amz-SignedHeaders"),
S3Escaper.encode(this.signedHeaders));
this.url = urlBuilder.build();
setCanonicalQueryString();
this.canonicalRequest = this.request.method() + "\n"
+ this.url.encodedPath() + "\n"
+ this.canonicalQueryString + "\n"
+ Joiner.on("\n").withKeyValueSeparator(":").join(this.canonicalHeaders) + "\n\n"
+ this.signedHeaders + "\n"
+ this.contentSha256;
this.canonicalRequestHash = Digest.sha256Hash(this.canonicalRequest);
}
}

View File

@@ -1,33 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk;
public enum SuccessActionStatus {
SuccessActionStatus201(201), SuccessActionStatus200(200), SuccessActionStatus204(204);
private final int value;
private SuccessActionStatus(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}

View File

@@ -1,40 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
/**
* Thrown to indicate that given bucket name is not valid.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class BucketPolicyTooLargeException extends MinioException {
private final String bucketName;
/**
* Constructs a new BucketPolicyTooLargeException with bucket name caused the error and error message.
*/
public BucketPolicyTooLargeException(String bucketName) {
super();
this.bucketName = bucketName;
}
@Override
public String toString() {
return String.format("Bucket policy is too large for bucket %s", this.bucketName);
}
}

View File

@@ -1,70 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import it.integry.ems.object_storage.minio.sdk.messages.ErrorResponse;
import okhttp3.Request;
import okhttp3.Response;
/**
* Thrown to indicate that error response is received when executing Amazon S3 operation.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class ErrorResponseException extends MinioException {
private final ErrorResponse errorResponse;
@SuppressFBWarnings(value = "Se", justification = "There's really no excuse except that nobody has complained")
private final Response response;
/**
* Constructs a new ErrorResponseException with error response and HTTP response object.
*/
public ErrorResponseException(ErrorResponse errorResponse, Response response) {
super(errorResponse.message());
this.errorResponse = errorResponse;
this.response = response;
}
/**
* Returns ErrorResponse contains detail of what error occured.
*/
public ErrorResponse errorResponse() {
return this.errorResponse;
}
@Override
public String toString() {
Request request = response.request();
return "error occurred\n"
+ errorResponse.getString() + "\n"
+ "request={"
+ "method=" + request.method() + ", "
+ "url=" + request.url() + ", "
+ "headers=" + request.headers().toString()
.replaceAll("Signature=([0-9a-f]+)", "Signature=*REDACTED*")
.replaceAll("Credential=([^/]+)", "Credential=*REDACTED*")
+ "}\n"
+ "response={"
+ "code=" + response.code() + ", "
+ "headers=" + response.headers()
+ "}\n";
}
}

View File

@@ -1,30 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
/**
* Thrown to indicate that reading given InputStream gets EOFException before reading given length.
*/
public class InsufficientDataException extends MinioException {
/**
* Constructs a new InsufficientDataException with given error message.
*/
public InsufficientDataException(String message) {
super(message);
}
}

View File

@@ -1,30 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
/**
* Thrown to indicate that unexpected internal library error occured while processing given request.
*/
public class InternalException extends MinioException {
/**
* Constructs a new InternalException with given error message.
*/
public InternalException(String message) {
super(message);
}
}

View File

@@ -1,30 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
/**
* Thrown to indicate that invalid value is passed to a method.
*/
public class InvalidArgumentException extends MinioException {
/**
* Constructs a new InvalidArgumentException with given error message.
*/
public InvalidArgumentException(String message) {
super(message);
}
}

View File

@@ -1,41 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
/**
* Thrown to indicate that given bucket name is not valid.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class InvalidBucketNameException extends MinioException {
private final String bucketName;
/**
* Constructs a new InvalidBucketNameException with bucket name caused the error and error message.
*/
public InvalidBucketNameException(String bucketName, String message) {
super(message);
this.bucketName = bucketName;
}
@Override
public String toString() {
return this.bucketName + ": " + super.toString();
}
}

View File

@@ -1,41 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
/**
* Thrown to indicate that given endpoint is not valid.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class InvalidEndpointException extends MinioException {
private final String endpoint;
/**
* Constructs a new InvalidEndpointException with endpoint caused the error and error message.
*/
public InvalidEndpointException(String endpoint, String message) {
super(message);
this.endpoint = endpoint;
}
@Override
public String toString() {
return this.endpoint + ": " + super.toString();
}
}

View File

@@ -1,40 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
/**
* Thrown to indicate that given expires value is out of range to set in presigned GET/PUT/POST.
*/
public class InvalidExpiresRangeException extends MinioException {
private final int expires;
/**
* Constructs a new InvalidExpiresRangeException with expires value caused the error and error message.
*/
public InvalidExpiresRangeException(int expires, String message) {
super(message);
this.expires = expires;
}
@Override
public String toString() {
return this.expires + ": " + super.toString();
}
}

View File

@@ -1,41 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
/**
* Thrown to indicate that given port number is not valid.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class InvalidPortException extends MinioException {
private final int port;
/**
* Constructs a new InvalidPortException with port number caused the error and error message.
*/
public InvalidPortException(int port, String message) {
super(message);
this.port = port;
}
@Override
public String toString() {
return this.port + ": " + super.toString();
}
}

View File

@@ -1,48 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import okhttp3.Request;
/**
* Thrown to indicate that non-xml response thrown from server.
*/
public class InvalidResponseException extends MinioException {
@SuppressFBWarnings(value = "Se", justification = "Non-XML response from server")
private Request request;
public InvalidResponseException() {
super("Non-XML response from server");
}
/**
* Constructs a new InvalidResponseException with HTTP request object causes the error.
*/
public InvalidResponseException(Request request) {
this();
this.request = request;
}
public Request request() {
return this.request;
}
}

View File

@@ -1,38 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
/**
* Base Exception class for all minio-java exceptions.
*/
public class MinioException extends Exception {
/**
* Constructs a new MinioException.
*/
public MinioException() {
super();
}
/**
* Constructs a new MinioException with given error message.
*/
public MinioException(String message) {
super(message);
}
}

View File

@@ -1,47 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import okhttp3.Request;
/**
* Thrown to indicate that no response is received from Amazon AWS S3 service.
*/
public class NoResponseException extends MinioException {
@SuppressFBWarnings(value = "Se", justification = "There's really no excuse except that nobody has complained")
private Request request;
public NoResponseException() {
super("no response from server");
}
/**
* Constructs a new NoResponseException with HTTP request object causes the error.
*/
public NoResponseException(Request request) {
this();
this.request = request;
}
public Request request() {
return this.request;
}
}

View File

@@ -1,30 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.errors;
/**
* Thrown to indicate that passed region conflicts with the one previously specified.
*/
public class RegionConflictException extends MinioException {
/**
* Constructs a new RegionConflictException with given error message.
*/
public RegionConflictException(String message) {
super(message);
}
}

View File

@@ -1,40 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.http;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* HTTP header annotation interface.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Header {
/**
* HTTP header name.
*/
String value();
/**
* Setter method name. 'setFieldName' is used if empty.
*/
String setter() default "";
}

View File

@@ -1,86 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.http;
import okhttp3.Headers;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* HTTP header parser class.
*/
public class HeaderParser {
private static final Logger LOGGER = Logger.getLogger(HeaderParser.class.getName());
/* private constructor */
private HeaderParser() {
}
/**
* Sets destination object from Headers object.
*/
public static void set(Headers headers, Object destination) {
Field[] publicFields;
Field[] privateFields;
Field[] fields;
Class<?> cls = destination.getClass();
publicFields = cls.getFields();
privateFields = cls.getDeclaredFields();
fields = new Field[publicFields.length + privateFields.length];
System.arraycopy(publicFields, 0, fields, 0, publicFields.length);
System.arraycopy(privateFields, 0, fields, publicFields.length, privateFields.length);
for (Field field : fields) {
Annotation annotation = field.getAnnotation(Header.class);
if (annotation == null) {
continue;
}
Header httpHeader = (Header) annotation;
String value = httpHeader.value();
String setter = httpHeader.setter();
if (setter.isEmpty()) {
// assume setter name as 'setFieldName'
String name = field.getName();
setter = "set" + name.substring(0, 1).toUpperCase(Locale.US) + name.substring(1);
}
try {
Method setterMethod = cls.getMethod(setter, new Class[]{String.class});
String valueString = headers.get(value);
if (valueString != null) {
setterMethod.invoke(destination, valueString);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
| IllegalArgumentException e) {
LOGGER.log(Level.SEVERE, "exception occured: ", e);
LOGGER.log(Level.INFO, "setter: " + setter);
LOGGER.log(Level.INFO, "annotation: " + value);
LOGGER.log(Level.INFO, "value: " + headers.get(value));
}
}
}
}

View File

@@ -1,30 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.http;
/**
* HTTP methods.
*/
public enum Method {
GET("GET"), HEAD("HEAD"), POST("POST"), PUT("PUT"), DELETE("DELETE");
private final String value;
private Method(String value) {
this.value = value;
}
}

View File

@@ -1,49 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.http;
/**
* HTTP schemes.
*/
public enum Scheme {
HTTP("http"), HTTPS("https");
private final String value;
private Scheme(String value) {
this.value = value;
}
/**
* Returns Scheme enum of given string.
*/
public static Scheme fromString(String scheme) {
if (scheme == null) {
throw new IllegalArgumentException("null scheme");
}
for (Scheme s : Scheme.values()) {
if (scheme.equalsIgnoreCase(s.value)) {
return s;
}
}
throw new IllegalArgumentException("invalid HTTP scheme '" + scheme + "'");
}
}

View File

@@ -1,57 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import it.integry.ems.object_storage.minio.sdk.DateFormat;
import org.xmlpull.v1.XmlPullParserException;
import java.util.Date;
/**
* Helper class to parse Amazon AWS S3 response XML containing bucket information.
*/
@SuppressWarnings("SameParameterValue")
public class Bucket extends XmlEntity {
@Key("Name")
private String name;
@Key("CreationDate")
private String creationDate;
public Bucket() throws XmlPullParserException {
super();
super.name = "Bucket";
}
/**
* Returns bucket name.
*/
public String name() {
return name;
}
/**
* Returns creation date.
*/
public Date creationDate() {
return DateFormat.RESPONSE_DATE_FORMAT.parseDateTime(creationDate).toDate();
}
}

View File

@@ -1,47 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
import java.util.LinkedList;
import java.util.List;
/**
* Helper class to parse Amazon AWS S3 response XML containing list of bucket information.
*/
@SuppressWarnings("WeakerAccess")
public class Buckets extends XmlEntity {
@Key("Bucket")
private List<Bucket> bucketList = new LinkedList<>();
public Buckets() throws XmlPullParserException {
super();
super.name = "Buckets";
}
/**
* Returns List of Buckets.
*/
public List<Bucket> bucketList() {
return bucketList;
}
}

View File

@@ -1,109 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import it.integry.ems.object_storage.minio.sdk.errors.InvalidArgumentException;
import org.xmlpull.v1.XmlPullParserException;
import java.util.LinkedList;
import java.util.List;
/**
* Helper class to parse Amazon AWS S3 response XML containing cloud function configuration.
*/
public class CloudFunctionConfiguration extends XmlEntity {
@Key("Id")
private String id;
@Key("CloudFunction")
private String cloudFunction;
@Key("Event")
private List<String> events = new LinkedList<>();
@Key("Filter")
private Filter filter;
public CloudFunctionConfiguration() throws XmlPullParserException {
super();
super.name = "CloudFunctionConfiguration";
}
/**
* Returns id.
*/
public String id() {
return id;
}
/**
* Sets id.
*/
public void setId(String id) {
this.id = id;
}
/**
* Returns cloudFunction.
*/
public String cloudFunction() {
return cloudFunction;
}
/**
* Sets cloudFunction.
*/
public void setCloudFunction(String cloudFunction) {
this.cloudFunction = cloudFunction;
}
/**
* Returns events.
*/
public List<EventType> events() throws InvalidArgumentException {
return EventType.fromStringList(events);
}
/**
* Sets event.
*/
public void setEvents(List<EventType> events) {
this.events = EventType.toStringList(events);
}
/**
* Returns filter.
*/
public Filter filter() {
return filter;
}
/**
* Sets filter.
*/
public void setFilter(Filter filter) {
this.filter = filter;
}
}

View File

@@ -1,62 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
import java.util.Arrays;
import java.util.List;
/**
* Helper class to construct complete multipart upload request XML for Amazon AWS S3.
*/
@SuppressWarnings("unused")
public class CompleteMultipartUpload extends XmlEntity {
@Key("Part")
private List<Part> partList;
public CompleteMultipartUpload() throws XmlPullParserException {
this(null);
}
/**
* Constucts a new CompleteMultipartUpload object with given parts.
*/
public CompleteMultipartUpload(Part[] parts) throws XmlPullParserException {
super();
super.name = "CompleteMultipartUpload";
super.namespaceDictionary.set("", "http://s3.amazonaws.com/doc/2006-03-01/");
if (parts == null) {
this.partList = null;
} else {
this.partList = Arrays.asList(parts);
}
}
/**
* Returns List of Parts of mulitpart upload.
*/
public List<Part> partList() {
return partList;
}
}

View File

@@ -1,54 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import it.integry.ems.object_storage.minio.sdk.DateFormat;
import org.joda.time.DateTime;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to parse Amazon AWS S3 response XML containing
* object item information.
*/
@SuppressWarnings({"SameParameterValue", "unused"})
public class CopyObjectResult extends XmlEntity {
@Key("ETag")
private String etag;
@Key("LastModified")
private String lastModified;
public CopyObjectResult() throws XmlPullParserException {
super();
super.name = "CopyObjectResult";
}
/**
* Returns last modified time of the object.
*/
public DateTime lastModified() {
return DateFormat.RESPONSE_DATE_FORMAT.parseDateTime(lastModified).toDateTime();
}
/**
* Returns ETag of the object.
*/
public String etag() {
return etag;
}
}

View File

@@ -1,55 +0,0 @@
/*
* Minio Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2019 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import it.integry.ems.object_storage.minio.sdk.DateFormat;
import org.joda.time.DateTime;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to parse Amazon AWS S3 response XML containing
* object item information.
*/
@SuppressWarnings({"SameParameterValue", "unused"})
public class CopyPartResult extends XmlEntity {
@Key("ETag")
private String etag;
@Key("LastModified")
private String lastModified;
public CopyPartResult() throws XmlPullParserException {
super();
super.name = "CopyPartResult";
}
/**
* Returns last modified time of the object.
*/
public DateTime lastModified() {
return DateFormat.RESPONSE_DATE_FORMAT.parseDateTime(lastModified).toDateTime();
}
/**
* Returns ETag of the object.
*/
public String etag() {
return etag;
}
}

View File

@@ -1,50 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to construct create bucket configuration request XML for Amazon AWS S3.
*/
public class CreateBucketConfiguration extends XmlEntity {
@Key("LocationConstraint")
private String locationConstraint;
/**
* Constructs a new CreateBucketConfiguration object with given location constraint.
*/
public CreateBucketConfiguration(String locationConstraint) throws XmlPullParserException {
super();
super.name = "CreateBucketConfiguration";
super.namespaceDictionary.set("", "http://s3.amazonaws.com/doc/2006-03-01/");
this.locationConstraint = locationConstraint;
}
/**
* Returns location constraint.
*/
@SuppressWarnings("unused")
public String locationConstraint() {
return locationConstraint;
}
}

View File

@@ -1,82 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to parse Amazon AWS S3 response XML containing DefaultRetention information.
*/
@SuppressWarnings("SameParameterValue")
public class DefaultRetention extends XmlEntity {
@Key("Mode")
private String mode;
@Key("Days")
private Integer days;
@Key("Years")
private Integer years;
public DefaultRetention() throws XmlPullParserException {
super();
this.name = "DefaultRetention";
}
/**
* Constructs a new DefaultRetention object with given retention.
*/
public DefaultRetention(RetentionMode mode, int duration, DurationUnit unit) throws XmlPullParserException {
this();
if (mode != null) {
this.mode = mode.toString();
}
if (unit == DurationUnit.DAYS) {
this.days = duration;
} else {
this.years = duration;
}
}
/**
* Returns mode.
*/
public RetentionMode mode() {
return RetentionMode.fromString(mode);
}
/**
* Returns days.
*/
public Integer days() {
return days;
}
/**
* Returns years.
*/
public Integer years() {
return years;
}
}

View File

@@ -1,46 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.Reader;
/**
* Helper class to parse Amazon AWS S3 error response XML.
*/
@SuppressWarnings("unused")
public class DeleteError extends ErrorResponse {
/**
* Constructs a new ErrorResponse object by reading given reader stream.
*/
public DeleteError() throws XmlPullParserException {
super();
super.name = "Error";
}
/**
* Constructs a new ErrorResponse object by reading given reader stream.
*/
public DeleteError(Reader reader) throws IOException, XmlPullParserException {
this();
this.parseXml(reader);
}
}

View File

@@ -1,49 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to create Amazon AWS S3 request XML containing object information for Multiple object deletion.
*/
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "URF_UNREAD_FIELD")
public class DeleteObject extends XmlEntity {
@Key("Key")
private String name;
@Key("VersionId")
private String versionId;
public DeleteObject(String name) throws XmlPullParserException {
this(name, null);
}
/**
* Constructs new delete object for given name and version ID.
*/
public DeleteObject(String name, String versionId) throws XmlPullParserException {
super();
super.name = "Object";
this.name = name;
this.versionId = versionId;
}
}

View File

@@ -1,52 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
import java.util.List;
/**
* Helper class to create Amazon AWS S3 request XML containing information for Multiple object deletion.
*/
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "URF_UNREAD_FIELD")
public class DeleteRequest extends XmlEntity {
@Key("Quiet")
private boolean quiet;
@Key("Object")
private List<DeleteObject> objectList;
public DeleteRequest(List<DeleteObject> objectList) throws XmlPullParserException {
this(objectList, true);
}
/**
* Constructs new delete request for given object list and quiet flag.
*/
public DeleteRequest(List<DeleteObject> objectList, boolean quiet) throws XmlPullParserException {
super();
super.name = "Delete";
super.namespaceDictionary.set("", "http://s3.amazonaws.com/doc/2006-03-01/");
this.objectList = objectList;
this.quiet = quiet;
}
}

View File

@@ -1,57 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.Reader;
import java.util.LinkedList;
import java.util.List;
/**
* Helper class to create Amazon AWS S3 request XML containing information for Multiple object deletion.
*/
@SuppressWarnings({"SameParameterValue", "unused"})
public class DeleteResult extends XmlEntity {
@Key("Deleted")
private List<DeletedObject> objectList = new LinkedList<>();
@Key("Error")
private List<DeleteError> errorList = new LinkedList<>();
/**
* Constructs new delete result by parsing content on given reader.
*/
public DeleteResult(Reader reader) throws IOException, XmlPullParserException {
super();
super.name = "DeleteResult";
this.parseXml(reader);
}
public List<DeletedObject> objectList() {
return objectList;
}
public List<DeleteError> errorList() {
return errorList;
}
}

View File

@@ -1,47 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to create Amazon AWS S3 request XML containing information for Multiple object deletion.
*/
@SuppressWarnings({"SameParameterValue", "unused"})
public class DeletedObject extends XmlEntity {
@Key("Key")
private String name;
@Key("VersionId")
private String versionId;
@Key("DeleteMarker")
private boolean deleteMarker;
@Key("DeleteMarkerVersionId")
private String deleteMarkerVersionId;
public DeletedObject() throws XmlPullParserException {
super();
super.name = "Deleted";
}
public String name() {
return name;
}
}

View File

@@ -1,25 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
/**
* DurationUnit of default retention configuration.
*/
public enum DurationUnit {
DAYS, YEARS;
}

View File

@@ -1,175 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import com.google.api.client.xml.XmlNamespaceDictionary;
import it.integry.ems.object_storage.minio.sdk.ErrorCode;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.Reader;
/**
* Helper class to parse Amazon AWS S3 error response XML.
*/
@SuppressWarnings("unused")
public class ErrorResponse extends XmlEntity {
@Key("Code")
protected String code;
@Key("Message")
protected String message;
@Key("BucketName")
protected String bucketName;
@Key("Key")
protected String objectName;
@Key("Resource")
protected String resource;
@Key("RequestId")
protected String requestId;
@Key("HostId")
protected String hostId;
protected ErrorCode errorCode;
public ErrorResponse() throws XmlPullParserException {
super();
super.name = "ErrorResponse";
}
/**
* Constructs a new ErrorResponse object by reading given reader stream.
*/
public ErrorResponse(Reader reader) throws IOException, XmlPullParserException {
this();
this.parseXml(reader);
}
/**
* Constructs a new ErrorResponse object with error code, bucket name, object name, resource, request ID and host ID.
*/
public ErrorResponse(ErrorCode errorCode, String bucketName, String objectName, String resource, String requestId,
String hostId) throws XmlPullParserException {
this();
this.errorCode = errorCode;
this.code = errorCode.code();
this.message = errorCode.message();
this.bucketName = bucketName;
this.objectName = objectName;
this.resource = resource;
this.requestId = requestId;
this.hostId = hostId;
}
/**
* Returns error code.
*/
public ErrorCode errorCode() {
if (this.errorCode == null) {
this.errorCode = ErrorCode.fromString(this.code);
}
return this.errorCode;
}
/**
* Returns error code string.
*/
public String code() {
return this.code;
}
/**
* Returns error message.
*/
public String message() {
return this.message;
}
/**
* Returns bucket name.
*/
public String bucketName() {
return bucketName;
}
/**
* Returns object name.
*/
public String objectName() {
return objectName;
}
/**
* Returns host ID.
*/
public String hostId() {
return hostId;
}
/**
* Returns request ID.
*/
public String requestId() {
return requestId;
}
/**
* Returns resource.
*/
public String resource() {
return resource;
}
/**
* Fills up this ErrorResponse object's fields by reading/parsing values from given Reader input stream.
*/
@Override
public void parseXml(Reader reader) throws IOException, XmlPullParserException {
XmlNamespaceDictionary namespaceDictionary = new XmlNamespaceDictionary();
namespaceDictionary.set("", "");
super.parseXml(reader, namespaceDictionary);
}
/**
* Returns string with field values.
*/
public String getString() {
return "ErrorResponse("
+ "code=" + code + ", "
+ "message=" + message + ", "
+ "bucketName=" + bucketName + ", "
+ "objectName=" + objectName + ", "
+ "resource=" + resource + ", "
+ "requestId=" + requestId + ", "
+ "hostId=" + hostId
+ ")";
}
}

View File

@@ -1,90 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import it.integry.ems.object_storage.minio.sdk.errors.InvalidArgumentException;
import java.util.LinkedList;
import java.util.List;
/**
* Amazon AWS S3 event types for notifications.
*/
public enum EventType {
OBJECT_CREATED_ANY("s3:ObjectCreated:*"),
OBJECT_CREATED_PUT("s3:ObjectCreated:Put"),
OBJECT_CREATED_POST("s3:ObjectCreated:Post"),
OBJECT_CREATED_COPY("s3:ObjectCreated:Copy"),
OBJECT_CREATED_COMPLETE_MULTIPART_UPLOAD("s3:ObjectCreated:CompleteMultipartUpload"),
OBJECT_ACCESSED_GET("s3:ObjectAccessed:Get"),
OBJECT_ACCESSED_HEAD("s3:ObjectAccessed:Head"),
OBJECT_ACCESSED_ANY("s3:ObjectAccessed:*"),
OBJECT_REMOVED_ANY("s3:ObjectRemoved:*"),
OBJECT_REMOVED_DELETE("s3:ObjectRemoved:Delete"),
OBJECT_REMOVED_DELETED_MARKER_CREATED("s3:ObjectRemoved:DeleteMarkerCreated"),
REDUCED_REDUNDANCY_LOST_OBJECT("s3:ReducedRedundancyLostObject");
private final String value;
private EventType(String value) {
this.value = value;
}
/**
* Returns EventType of given string.
*/
public static EventType fromString(String eventTypeString) throws InvalidArgumentException {
for (EventType et : EventType.values()) {
if (eventTypeString.equals(et.value)) {
return et;
}
}
throw new InvalidArgumentException("unknown event '" + eventTypeString + "'");
}
/**
* Returns List&lt;EventType&gt; of given List&lt;String&gt;.
*/
public static List<EventType> fromStringList(List<String> eventList) throws InvalidArgumentException {
List<EventType> eventTypeList = new LinkedList<EventType>();
for (String event : eventList) {
eventTypeList.add(EventType.fromString(event));
}
return eventTypeList;
}
/**
* Returns List&lt;String&gt; of given List&lt;EventType&gt;.
*/
public static List<String> toStringList(List<EventType> eventTypeList) {
List<String> events = new LinkedList<String>();
for (EventType eventType : eventTypeList) {
events.add(eventType.toString());
}
return events;
}
public String toString() {
return this.value;
}
}

View File

@@ -1,63 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import it.integry.ems.object_storage.minio.sdk.errors.InvalidArgumentException;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to parse Amazon AWS S3 response XML containing Filter.
*/
@SuppressWarnings("WeakerAccess")
public class Filter extends XmlEntity {
@Key("S3Key")
private S3Key s3Key = new S3Key();
public Filter() throws XmlPullParserException {
super();
super.name = "Filter";
}
/**
* Returns S3 Key.
*/
public S3Key s3Key() {
return s3Key;
}
/**
* Sets S3 Key.
*/
public void setS3Key(S3Key s3Key) {
this.s3Key = s3Key;
}
public void setPrefixRule(String value) throws InvalidArgumentException, XmlPullParserException {
s3Key.setPrefixRule(value);
}
public void setSuffixRule(String value) throws InvalidArgumentException, XmlPullParserException {
s3Key.setSuffixRule(value);
}
}

View File

@@ -1,69 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to parse Amazon AWS S3 response XML containing filter rule.
*/
public class FilterRule extends XmlEntity {
@Key("Name")
private String name;
@Key("Value")
private String value;
public FilterRule() throws XmlPullParserException {
super();
super.name = "FilterRule";
}
/**
* Returns filter name.
*/
public String name() {
return name;
}
/**
* Sets filter name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns filter value.
*/
public String value() {
return value;
}
/**
* Sets filter value.
*/
public void setValue(String value) {
this.value = value;
}
}

View File

@@ -1,54 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to parse Amazon AWS S3 response XML containing Grant information.
*/
@SuppressWarnings({"SameParameterValue", "unused"})
public class Grant extends XmlEntity {
@Key("Grantee")
private Grantee grantee;
@Key("Permission")
private String permission;
public Grant() throws XmlPullParserException {
super();
this.name = "Grant";
}
/**
* Returns Grantee.
*/
public Grantee grantee() {
return grantee;
}
/**
* Returns permission.
*/
public String permission() {
return permission;
}
}

View File

@@ -1,84 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to parse Amazon AWS S3 response XML containing Grantee information.
*/
@SuppressWarnings({"SameParameterValue", "unused"})
public class Grantee extends XmlEntity {
@Key("ID")
private String id;
@Key("DisplayName")
private String displayName;
@Key("EmailAddress")
private String emailAddress;
@Key("Type")
private String type;
@Key("URI")
private String uri;
public Grantee() throws XmlPullParserException {
super();
this.name = "Grantee";
}
/**
* Returns grantee id.
*/
public String id() {
return id;
}
/**
* Returns grantee display name.
*/
public String displayName() {
return displayName;
}
/**
* Returns grantee email address.
*/
public String emailAddress() {
return emailAddress;
}
/**
* Returns grantee type.
*/
public String type() {
return type;
}
/**
* Returns grantee URI.
*/
public String uri() {
return uri;
}
}

View File

@@ -1,64 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to parse Amazon AWS S3 response XML containing initiate multipart upload result.
*/
@SuppressWarnings({"SameParameterValue", "unused"})
public class InitiateMultipartUploadResult extends XmlEntity {
@Key("Bucket")
private String bucketName;
@Key("Key")
private String objectName;
@Key("UploadId")
private String uploadId;
public InitiateMultipartUploadResult() throws XmlPullParserException {
super();
this.name = "InitiateMultipartUploadResult";
}
/**
* Returns bucket name.
*/
public String bucketName() {
return bucketName;
}
/**
* Returns object name.
*/
public String objectName() {
return objectName;
}
/**
* Returns upload ID.
*/
public String uploadId() {
return uploadId;
}
}

View File

@@ -1,54 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to parse Amazon AWS S3 response XML containing initator information.
*/
@SuppressWarnings("unused")
public class Initiator extends XmlEntity {
@Key("ID")
private String id;
@Key("DisplayName")
private String displayName;
public Initiator() throws XmlPullParserException {
super();
this.name = "Initiator";
}
/**
* Returns initiator ID.
*/
public String id() {
return id;
}
/**
* Returns initiator display name.
*/
public String displayName() {
return displayName;
}
}

View File

@@ -1,117 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import it.integry.ems.object_storage.minio.sdk.DateFormat;
import org.xmlpull.v1.XmlPullParserException;
import java.util.Date;
/**
* Helper class to parse Amazon AWS S3 response XML containing object item information.
*/
@SuppressWarnings({"SameParameterValue", "unused"})
public class Item extends XmlEntity {
@Key("Key")
private String objectName;
@Key("LastModified")
private String lastModified;
@Key("ETag")
private String etag;
@Key("Size")
private long size;
@Key("StorageClass")
private String storageClass;
@Key("Owner")
private Owner owner;
private boolean isDir = false;
public Item() throws XmlPullParserException {
this(null, false);
}
/**
* Constructs a new Item object with given object name and IsDir flag.
*/
public Item(String objectName, boolean isDir) throws XmlPullParserException {
super();
this.name = "Item";
this.objectName = objectName;
this.isDir = isDir;
}
/**
* Returns object name.
*/
public String objectName() {
return objectName;
}
/**
* Returns last modified time of the object.
*/
public Date lastModified() {
return DateFormat.RESPONSE_DATE_FORMAT.parseDateTime(lastModified).toDate();
}
/**
* Returns ETag of the object.
*/
public String etag() {
return etag;
}
/**
* Returns object size.
*/
public long objectSize() {
return size;
}
/**
* Returns storage class of the object.
*/
public String storageClass() {
return storageClass;
}
/**
* Returns owner object of given the object.
*/
public Owner owner() {
return owner;
}
/**
* Returns whether the object is a directory or not.
*/
public boolean isDir() {
return isDir;
}
}

View File

@@ -1,61 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
import java.util.LinkedList;
import java.util.List;
/**
* Helper class to parse Amazon AWS S3 response XML containing ListAllMyBucketsResult information.
*/
public class ListAllMyBucketsResult extends XmlEntity {
@Key("Owner")
private Owner owner;
@Key("Buckets")
private Buckets buckets;
public ListAllMyBucketsResult() throws XmlPullParserException {
super();
this.name = "ListAllMyBucketsResult";
}
/**
* Returns owner.
*/
@SuppressWarnings("unused")
public Owner owner() {
return owner;
}
/**
* Returns List of buckets.
*/
public List<Bucket> buckets() {
if (buckets == null) {
return new LinkedList<>();
}
return buckets.bucketList();
}
}

View File

@@ -1,153 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015, 2016, 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
import java.util.LinkedList;
import java.util.List;
/**
* Helper class to parse Amazon AWS S3 response XML containing ListBucketResult Version 2 information.
*/
@SuppressWarnings({"SameParameterValue", "unused"})
public class ListBucketResult extends XmlEntity {
@Key("Name")
private String name;
@Key("Prefix")
private String prefix;
@Key("ContinuationToken")
private String continuationToken;
@Key("NextContinuationToken")
private String nextContinuationToken;
@Key("StartAfter")
private String startAfter;
@Key("KeyCount")
private String keyCount;
@Key("MaxKeys")
private int maxKeys;
@Key("Delimiter")
private String delimiter;
@Key("IsTruncated")
private boolean isTruncated;
@Key("Contents")
private List<Item> contents;
@Key("CommonPrefixes")
private List<Prefix> commonPrefixes;
public ListBucketResult() throws XmlPullParserException {
super();
super.name = "ListBucketResult";
}
/**
* Returns bucket name.
*/
public String name() {
return name;
}
/**
* Returns prefix.
*/
public String prefix() {
return prefix;
}
/**
* Returns continuation token.
*/
public String continuationToken() {
return continuationToken;
}
/**
* Returns next continuation token.
*/
public String nextContinuationToken() {
return nextContinuationToken;
}
/**
* Returns start after.
*/
public String startAfter() {
return startAfter;
}
/**
* Returns key count.
*/
public String keyCount() {
return keyCount;
}
/**
* Returns max keys.
*/
public int maxKeys() {
return maxKeys;
}
/**
* Returns delimiter.
*/
public String delimiter() {
return delimiter;
}
/**
* Returns whether the result is truncated or not.
*/
public boolean isTruncated() {
return isTruncated;
}
/**
* Returns List of Items.
*/
public List<Item> contents() {
if (contents == null) {
return new LinkedList<>();
}
return contents;
}
/**
* Returns List of Prefix.
*/
public List<Prefix> commonPrefixes() {
if (commonPrefixes == null) {
return new LinkedList<>();
}
return commonPrefixes;
}
}

View File

@@ -1,133 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015, 2016, 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
import java.util.LinkedList;
import java.util.List;
/**
* Helper class to parse Amazon AWS S3 response XML containing ListBucketResult Version 1 information.
*/
@SuppressWarnings({"SameParameterValue", "unused"})
public class ListBucketResultV1 extends XmlEntity {
@Key("Name")
private String name;
@Key("Prefix")
private String prefix;
@Key("Marker")
private String marker;
@Key("NextMarker")
private String nextMarker;
@Key("MaxKeys")
private int maxKeys;
@Key("Delimiter")
private String delimiter;
@Key("IsTruncated")
private boolean isTruncated;
@Key("Contents")
private List<Item> contents;
@Key("CommonPrefixes")
private List<Prefix> commonPrefixes;
public ListBucketResultV1() throws XmlPullParserException {
super();
super.name = "ListBucketResult";
}
/**
* Returns next marker.
*/
public String nextMarker() {
return nextMarker;
}
/**
* Returns bucket name.
*/
public String name() {
return name;
}
/**
* Returns prefix.
*/
public String prefix() {
return prefix;
}
/**
* Returns marker.
*/
public String marker() {
return marker;
}
/**
* Returns max keys.
*/
public int maxKeys() {
return maxKeys;
}
/**
* Returns delimiter.
*/
public String delimiter() {
return delimiter;
}
/**
* Returns whether the result is truncated or not.
*/
public boolean isTruncated() {
return isTruncated;
}
/**
* Returns List of Items.
*/
public List<Item> contents() {
if (contents == null) {
return new LinkedList<>();
}
return contents;
}
/**
* Returns List of Prefix.
*/
public List<Prefix> commonPrefixes() {
if (commonPrefixes == null) {
return new LinkedList<>();
}
return commonPrefixes;
}
}

View File

@@ -1,120 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
import java.util.ArrayList;
import java.util.List;
/**
* Helper class to parse Amazon AWS S3 response XML containing ListMultipartUploadResult information.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class ListMultipartUploadsResult extends XmlEntity {
@Key("Upload")
List<Upload> uploads;
@Key("Bucket")
private String bucketName;
@Key("KeyMarker")
private String keyMarker;
@Key("UploadIdMarker")
private String uploadIdMarker;
@Key("NextKeyMarker")
private String nextKeyMarker;
@Key("NextUploadIdMarker")
private String nextUploadIdMarker;
@Key("MaxUploads")
private int maxUploads;
@Key("IsTruncated")
private boolean isTruncated;
public ListMultipartUploadsResult() throws XmlPullParserException {
super();
super.name = "ListMultipartUploadsResult";
}
/**
* Returns whether the result is truncated or not.
*/
public boolean isTruncated() {
return isTruncated;
}
/**
* Returns bucket name.
*/
public String bucketName() {
return bucketName;
}
/**
* Returns key marker.
*/
public String keyMarker() {
return keyMarker;
}
/**
* Returns upload ID marker.
*/
public String uploadIdMarker() {
return uploadIdMarker;
}
/**
* Returns next key marker.
*/
public String nextKeyMarker() {
return nextKeyMarker;
}
/**
* Returns next upload ID marker.
*/
public String nextUploadIdMarker() {
return nextUploadIdMarker;
}
/**
* Returns max uploads received.
*/
public int maxUploads() {
return maxUploads;
}
/**
* Returns List of Upload.
*/
public List<Upload> uploads() {
if (uploads == null) {
return new ArrayList<>();
}
return uploads;
}
}

View File

@@ -1,141 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
import java.util.LinkedList;
import java.util.List;
/**
* Helper class to parse Amazon AWS S3 response XML containing ListPartsResult information.
*/
@SuppressWarnings("unused")
public class ListPartsResult extends XmlEntity {
@Key("Bucket")
private String bucketName;
@Key("Key")
private String objectName;
@Key("Initiator")
private Initiator initiator;
@Key("Owner")
private Owner owner;
@Key("StorageClass")
private String storageClass;
@Key("PartNumberMarker")
private int partNumberMarker;
@Key("NextPartNumberMarker")
private int nextPartNumberMarker;
@Key("MaxParts")
private int maxParts;
@Key("IsTruncated")
private boolean isTruncated;
@Key("Part")
private List<Part> partList;
public ListPartsResult() throws XmlPullParserException {
super();
this.name = "ListPartsResult";
}
/**
* Returns bucket name.
*/
public String bucketName() {
return bucketName;
}
/**
* Returns object name.
*/
public String objectName() {
return objectName;
}
/**
* Returns storage class.
*/
public String storageClass() {
return storageClass;
}
/**
* Returns initator information.
*/
public Initiator initiator() {
return initiator;
}
/**
* Returns owner information.
*/
public Owner owner() {
return owner;
}
/**
* Returns maximum parts information received.
*/
public int maxParts() {
return maxParts;
}
/**
* Returns whether the result is truncated or not.
*/
public boolean isTruncated() {
return isTruncated;
}
/**
* Returns part number marker.
*/
public int partNumberMarker() {
return partNumberMarker;
}
/**
* Returns next part number marker.
*/
public int nextPartNumberMarker() {
return nextPartNumberMarker;
}
/**
* Returns List of Part.
*/
public List<Part> partList() {
if (partList == null) {
return new LinkedList<>();
}
return partList;
}
}

View File

@@ -1,93 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
import java.util.LinkedList;
import java.util.List;
/**
* Helper class to parse Amazon AWS S3 response XML containing notification configuration.
*/
public class NotificationConfiguration extends XmlEntity {
@Key("CloudFunctionConfiguration")
private List<CloudFunctionConfiguration> cloudFunctionConfigurationList = new LinkedList<>();
@Key("QueueConfiguration")
private List<QueueConfiguration> queueConfigurationList = new LinkedList<>();
@Key("TopicConfiguration")
private List<TopicConfiguration> topicConfigurationList = new LinkedList<>();
/**
* Constructs a new notification configuration with default namespace.
*/
public NotificationConfiguration() throws XmlPullParserException {
super();
super.name = "NotificationConfiguration";
super.namespaceDictionary.set("", "http://s3.amazonaws.com/doc/2006-03-01/");
}
/**
* Returns cloud function configuration.
*/
public List<CloudFunctionConfiguration> cloudFunctionConfigurationList() {
return cloudFunctionConfigurationList;
}
/**
* Sets cloud function configuration list.
*/
public void setCloudFunctionConfigurationList(List<CloudFunctionConfiguration> cloudFunctionConfigurationList) {
this.cloudFunctionConfigurationList = cloudFunctionConfigurationList;
}
/**
* Returns queue configuration list.
*/
public List<QueueConfiguration> queueConfigurationList() {
return queueConfigurationList;
}
/**
* Sets queue configuration list.
*/
public void setQueueConfigurationList(List<QueueConfiguration> queueConfigurationList) {
this.queueConfigurationList = queueConfigurationList;
}
/**
* Returns topic configuration list.
*/
public List<TopicConfiguration> topicConfigurationList() {
return topicConfigurationList;
}
/**
* Sets topic configuration list.
*/
public void setTopicConfigurationList(List<TopicConfiguration> topicConfigurationList) {
this.topicConfigurationList = topicConfigurationList;
}
}

View File

@@ -1,88 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to construct create bucket configuration request XML for Amazon AWS S3.
*/
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "URF_UNREAD_FIELD")
public class ObjectLockConfiguration extends XmlEntity {
@Key("ObjectLockEnabled")
private String objectLockEnabled = "Enabled";
@Key("Rule")
private Rule rule;
/**
* Constructs a new ObjectLockConfiguration object.
*/
public ObjectLockConfiguration() throws XmlPullParserException {
super();
super.name = "ObjectLockConfiguration";
super.namespaceDictionary.set("", "http://s3.amazonaws.com/doc/2006-03-01/");
}
/**
* Constructs a new ObjectLockConfiguration object with given retention.
*/
public ObjectLockConfiguration(RetentionMode mode, int duration, DurationUnit unit) throws XmlPullParserException {
this();
this.rule = new Rule(mode, duration, unit);
}
/**
* Returns mode.
*/
public RetentionMode mode() {
if (rule == null) {
return null;
}
return rule.mode();
}
/**
* Returns days.
*/
public Integer days() {
if (rule == null) {
return null;
}
return rule.days();
}
/**
* Returns years.
*/
public Integer years() {
if (rule == null) {
return null;
}
return rule.years();
}
}

View File

@@ -1,54 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to parse Amazon AWS S3 response XML containing Owner information.
*/
@SuppressWarnings("SameParameterValue")
public class Owner extends XmlEntity {
@Key("ID")
private String id;
@Key("DisplayName")
private String displayName;
public Owner() throws XmlPullParserException {
super();
this.name = "Owner";
}
/**
* Returns owner ID.
*/
public String id() {
return id;
}
/**
* Returns owner display name.
*/
public String displayName() {
return displayName;
}
}

View File

@@ -1,88 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import it.integry.ems.object_storage.minio.sdk.DateFormat;
import org.xmlpull.v1.XmlPullParserException;
import java.util.Date;
/**
* Helper class to parse Amazon AWS S3 response XML containing Part information.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Part extends XmlEntity {
@Key("PartNumber")
private int partNumber;
@Key("ETag")
private String etag;
@Key("LastModified")
private String lastModified;
@Key("Size")
private Long size;
public Part() throws XmlPullParserException {
this(0, null);
}
/**
* Constructs a new Part object with given part number and ETag.
*/
public Part(int partNumber, String etag) throws XmlPullParserException {
super();
super.name = "Part";
this.partNumber = partNumber;
this.etag = etag;
}
/**
* Returns part number.
*/
public int partNumber() {
return partNumber;
}
/**
* Returns ETag.
*/
public String etag() {
return etag.replaceAll("\"", "");
}
/**
* Returns last modified time.
*/
public Date lastModified() {
return DateFormat.RESPONSE_DATE_FORMAT.parseDateTime(lastModified).toDate();
}
/**
* Returns part size.
*/
public long partSize() {
return size;
}
}

View File

@@ -1,44 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to parse Amazon AWS S3 response XML containing Prefix information.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Prefix extends XmlEntity {
@Key("Prefix")
private String prefix;
public Prefix() throws XmlPullParserException {
super();
super.name = "Prefix";
}
/**
* Returns prefix.
*/
public String prefix() {
return prefix;
}
}

View File

@@ -1,110 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import it.integry.ems.object_storage.minio.sdk.errors.InvalidArgumentException;
import org.xmlpull.v1.XmlPullParserException;
import java.util.LinkedList;
import java.util.List;
/**
* Helper class to parse Amazon AWS S3 response XML containing queue configuration.
*/
public class QueueConfiguration extends XmlEntity {
@Key("Id")
private String id;
@Key("Queue")
private String queue;
@Key("Event")
private List<String> events = new LinkedList<>();
@Key("Filter")
private Filter filter;
public QueueConfiguration() throws XmlPullParserException {
super();
super.name = "QueueConfiguration";
}
/**
* Returns id.
*/
public String id() {
return id;
}
/**
* Sets id.
*/
public void setId(String id) {
this.id = id;
}
/**
* Returns queue.
*/
public String queue() {
return queue;
}
/**
* Sets queue.
*/
public void setQueue(String queue) {
this.queue = queue;
}
/**
* Returns events.
*/
public List<EventType> events() throws InvalidArgumentException {
return EventType.fromStringList(events);
}
/**
* Sets event.
*/
public void setEvents(List<EventType> events) {
this.events = EventType.toStringList(events);
}
/**
* Sets filter.
*/
public void setFilter(Filter filter) {
this.filter = filter;
}
/**
* Returns filter.
*/
public Filter filter() {
return filter;
}
}

View File

@@ -1,45 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
/**
* Retention mode for the specified object.
*/
public enum RetentionMode {
GOVERNANCE, COMPLIANCE;
/**
* Returns ErrorCode of given code string.
*/
public static RetentionMode fromString(String modeString) {
if (modeString == null) {
return null;
}
if (modeString.equals(RetentionMode.GOVERNANCE.toString())) {
return RetentionMode.GOVERNANCE;
}
if (modeString.equals(RetentionMode.COMPLIANCE.toString())) {
return RetentionMode.COMPLIANCE;
}
// Unknown mode string.
return null;
}
}

View File

@@ -1,70 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import org.xmlpull.v1.XmlPullParserException;
/**
* Helper class to parse Amazon AWS S3 response XML containing Rule information.
*/
@SuppressWarnings("SameParameterValue")
public class Rule extends XmlEntity {
@Key("DefaultRetention")
private DefaultRetention defaultRetention;
public Rule() throws XmlPullParserException {
super();
this.name = "Rule";
}
/**
* Constructs a new Rule object with given retention.
*/
public Rule(RetentionMode mode, int duration, DurationUnit unit) throws XmlPullParserException {
this();
this.defaultRetention = new DefaultRetention(mode, duration, unit);
}
/**
* Returns mode.
*/
public RetentionMode mode() {
return defaultRetention.mode();
}
/**
* Returns days.
*/
public Integer days() {
return defaultRetention.days();
}
/**
* Returns years.
*/
public Integer years() {
return defaultRetention.years();
}
}

View File

@@ -1,83 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import it.integry.ems.object_storage.minio.sdk.errors.InvalidArgumentException;
import org.xmlpull.v1.XmlPullParserException;
import java.util.LinkedList;
import java.util.List;
/**
* Helper class to parse Amazon AWS S3 response XML containing S3Key.
*/
@SuppressWarnings("WeakerAccess")
public class S3Key extends XmlEntity {
@Key("FilterRule")
private List<FilterRule> filterRuleList = new LinkedList<>();
public S3Key() throws XmlPullParserException {
super();
super.name = "S3Key";
}
/**
* Returns filter rule list.
*/
public List<FilterRule> filterRuleList() {
return filterRuleList;
}
/**
* Sets filter rule to list.
* As per Amazon AWS S3 server behavior, its not possible to set more than one rule for "prefix" or "suffix".
* However the spec http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTnotification.html
* is not clear about this behavior.
*/
private void setRule(String name, String value) throws InvalidArgumentException, XmlPullParserException {
if (value.length() > 1024) {
throw new InvalidArgumentException("value '" + value + "' is more than 1024 long");
}
for (FilterRule rule : filterRuleList) {
// Remove rule.name is same as given name.
if (rule.name().equals(name)) {
filterRuleList.remove(rule);
}
}
FilterRule newRule = new FilterRule();
newRule.setName(name);
newRule.setValue(value);
filterRuleList.add(newRule);
}
public void setPrefixRule(String value) throws InvalidArgumentException, XmlPullParserException {
setRule("prefix", value);
}
public void setSuffixRule(String value) throws InvalidArgumentException, XmlPullParserException {
setRule("suffix", value);
}
}

View File

@@ -1,102 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import it.integry.ems.object_storage.minio.sdk.errors.InvalidArgumentException;
import org.xmlpull.v1.XmlPullParserException;
import java.util.LinkedList;
import java.util.List;
/**
* Helper class to parse Amazon AWS S3 response XML containing topic configuration.
*/
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "URF_UNREAD_FIELD")
public class TopicConfiguration extends XmlEntity {
@Key("Id")
private String id;
@Key("Topic")
private String topic;
@Key("Event")
private List<String> events = new LinkedList<>();
@Key("Filter")
private Filter filter;
public TopicConfiguration() throws XmlPullParserException {
super();
super.name = "TopicConfiguration";
}
/**
* Sets ID. This is used only in functional test.
*/
public void setId(String id) {
this.id = id;
}
/**
* Returns topic.
*/
public String topic() {
return topic;
}
/**
* Sets topic.
*/
public void setTopic(String topic) {
this.topic = topic;
}
/**
* Returns events.
*/
public List<EventType> events() throws InvalidArgumentException {
return EventType.fromStringList(events);
}
/**
* Sets event.
*/
public void setEvents(List<EventType> events) {
this.events = EventType.toStringList(events);
}
/**
* Returns filter.
*/
public Filter filter() {
return filter;
}
/**
* Sets filter.
*/
public void setFilter(Filter filter) {
this.filter = filter;
}
}

View File

@@ -1,114 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.util.Key;
import it.integry.ems.object_storage.minio.sdk.DateFormat;
import org.xmlpull.v1.XmlPullParserException;
import java.util.Date;
/**
* Helper class to parse Amazon AWS S3 response XML containing Upload information.
*/
@SuppressWarnings("unused")
public class Upload extends XmlEntity {
@Key("Key")
private String objectName;
@Key("UploadId")
private String uploadId;
@Key("Initiator")
private Initiator initiator;
@Key("Owner")
private Owner owner;
@Key("StorageClass")
private String storageClass;
@Key("Initiated")
private String initiated;
private long aggregatedPartSize;
public Upload() throws XmlPullParserException {
super();
super.name = "Upload";
}
/**
* Returns object name.
*/
public String objectName() {
return objectName;
}
/**
* Returns upload ID.
*/
public String uploadId() {
return uploadId;
}
/**
* Returns initator information.
*/
public Initiator initiator() {
return initiator;
}
/**
* Returns owner information.
*/
public Owner owner() {
return owner;
}
/**
* Returns storage class.
*/
public String storageClass() {
return storageClass;
}
/**
* Returns initated time.
*/
public Date initiated() {
return DateFormat.RESPONSE_DATE_FORMAT.parseDateTime(initiated).toDate();
}
/**
* Returns aggregated part size.
*/
public long aggregatedPartSize() {
return aggregatedPartSize;
}
/**
* Sets given aggregated part size.
*/
public void setAggregatedPartSize(long size) {
this.aggregatedPartSize = size;
}
}

View File

@@ -1,76 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.messages;
import com.google.api.client.xml.GenericXml;
import com.google.api.client.xml.Xml;
import com.google.api.client.xml.XmlNamespaceDictionary;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.Reader;
/**
* XML parser interface class extended from GenericXML.
*/
public abstract class XmlEntity extends GenericXml {
private XmlPullParser xmlPullParser;
private XmlNamespaceDictionary defaultNamespaceDictionary;
/**
* Constructs a new XmlEntity class.
*/
public XmlEntity() throws XmlPullParserException {
super.namespaceDictionary = new XmlNamespaceDictionary();
super.namespaceDictionary.set("s3", "http://s3.amazonaws.com/doc/2006-03-01/");
super.namespaceDictionary.set("", "");
this.xmlPullParser = Xml.createParser();
this.defaultNamespaceDictionary = new XmlNamespaceDictionary();
}
/**
* Constructs a new XmlEntity class by parsing content from given reader input stream.
*/
public XmlEntity(Reader reader) throws IOException, XmlPullParserException {
this();
this.parseXml(reader);
}
/**
* Parses content from given reader input stream.
*/
public void parseXml(Reader reader) throws IOException, XmlPullParserException {
this.xmlPullParser.setInput(reader);
Xml.parseElement(this.xmlPullParser, this, this.defaultNamespaceDictionary, null);
}
/**
* Parses content from given reader input stream and namespace dictionary.
*/
protected void parseXml(Reader reader, XmlNamespaceDictionary namespaceDictionary)
throws IOException, XmlPullParserException {
this.xmlPullParser.setInput(reader);
Xml.parseElement(this.xmlPullParser, this, namespaceDictionary, null);
}
}

View File

@@ -1,31 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.notification;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@SuppressFBWarnings("UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD")
@JsonIgnoreProperties(ignoreUnknown = true)
public class BucketMeta {
public String name;
public Identity ownerIdentity;
public String arn;
}

View File

@@ -1,32 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.notification;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@SuppressFBWarnings("UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD")
@JsonIgnoreProperties(ignoreUnknown = true)
public class EventMeta {
public String schemaVersion;
public String configurationId;
public BucketMeta bucket;
public ObjectMeta object;
}

View File

@@ -1,29 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.notification;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@SuppressFBWarnings("UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Identity {
public String principalId;
}

View File

@@ -1,39 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.notification;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Map;
@SuppressFBWarnings("UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD")
@JsonIgnoreProperties(ignoreUnknown = true)
public class NotificationEvent {
public String eventVersion;
public String eventSource;
public String awsRegion;
public String eventTime;
public String eventName;
public Identity userIdentity;
public Map<String, String> requestParameters;
public Map<String, String> responseElements;
public EventMeta s3;
public SourceInfo source;
}

View File

@@ -1,32 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.notification;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@SuppressFBWarnings("UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD")
@JsonIgnoreProperties(ignoreUnknown = true)
public class NotificationInfo {
@JsonProperty("Records")
public NotificationEvent[] records;
@JsonProperty("Err")
public String err;
}

View File

@@ -1,32 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.notification;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@SuppressFBWarnings("UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ObjectMeta {
public String key;
public int size;
public String etag;
public String versionId;
public String sequencer;
}

View File

@@ -1,31 +0,0 @@
/*
* MinIO Java SDK for Amazon S3 Compatible Cloud Storage,
* (C) 2018 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.notification;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@SuppressFBWarnings("UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD")
@JsonIgnoreProperties(ignoreUnknown = true)
public class SourceInfo {
public String host;
public String port;
public String userAgent;
}

View File

@@ -1,213 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.org.apache.commons.validator.routines;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* <p>
* <b>InetAddress</b> validation and conversion routines (<code>java.net.InetAddress</code>).
* </p>
*
* <p>
*
* <p>
* </p>
*
* <p>
* This class provides methods to validate a candidate IP address.
* </p>
*
* <p>
* </p>
*
* <p>
* This class is a Singleton; you can retrieve the instance via the {@link #getInstance()} method.
* </p>
*
* @version $Revision$
* @since Validator 1.4
*/
public class InetAddressValidator implements Serializable {
private static final int IPV4_MAX_OCTET_VALUE = 255;
private static final int MAX_UNSIGNED_SHORT = 0xffff;
private static final int BASE_16 = 16;
private static final long serialVersionUID = -919201640201914789L;
private static final String IPV4_REGEX =
"^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$";
// Max number of hex groups (separated by :) in an IPV6 address
private static final int IPV6_MAX_HEX_GROUPS = 8;
// Max hex digits in each IPv6 group
private static final int IPV6_MAX_HEX_DIGITS_PER_GROUP = 4;
/**
* Singleton instance of this class.
*/
private static final InetAddressValidator VALIDATOR = new InetAddressValidator();
/**
* IPv4 RegexValidator.
*/
private final RegexValidator ipv4Validator = new RegexValidator(IPV4_REGEX);
/**
* Returns the singleton instance of this validator.
*
* @return the singleton instance of this validator
*/
public static InetAddressValidator getInstance() {
return VALIDATOR;
}
/**
* Checks if the specified string is a valid IP address.
*
* @param inetAddress the string to validate
* @return true if the string validates as an IP address
*/
public boolean isValid(String inetAddress) {
return isValidInet4Address(inetAddress) || isValidInet6Address(inetAddress);
}
/**
* Validates an IPv4 address. Returns true if valid.
*
* @param inet4Address the IPv4 address to validate
* @return true if the argument contains a valid IPv4 address
*/
public boolean isValidInet4Address(String inet4Address) {
// verify that address conforms to generic IPv4 format
String[] groups = ipv4Validator.match(inet4Address);
if (groups == null) {
return false;
}
// verify that address subgroups are legal
for (String ipSegment : groups) {
if (ipSegment == null || ipSegment.length() == 0) {
return false;
}
int iIpSegment = 0;
try {
iIpSegment = Integer.parseInt(ipSegment);
} catch (NumberFormatException e) {
return false;
}
if (iIpSegment > IPV4_MAX_OCTET_VALUE) {
return false;
}
if (ipSegment.length() > 1 && ipSegment.startsWith("0")) {
return false;
}
}
return true;
}
/**
* Validates an IPv6 address. Returns true if valid.
*
* @param inet6Address the IPv6 address to validate
* @return true if the argument contains a valid IPv6 address
* @since 1.4.1
*/
public boolean isValidInet6Address(String inet6Address) {
boolean containsCompressedZeroes = inet6Address.contains("::");
if (containsCompressedZeroes && inet6Address.indexOf("::") != inet6Address.lastIndexOf("::")) {
return false;
}
if (inet6Address.startsWith(":") && !inet6Address.startsWith("::")
|| inet6Address.endsWith(":") && !inet6Address.endsWith("::")) {
return false;
}
String[] octets = inet6Address.split(":");
if (containsCompressedZeroes) {
List<String> octetList = new ArrayList<String>(Arrays.asList(octets));
if (inet6Address.endsWith("::")) {
// String.split() drops ending empty segments
octetList.add("");
} else if (inet6Address.startsWith("::") && !octetList.isEmpty()) {
octetList.remove(0);
}
octets = octetList.toArray(new String[octetList.size()]);
}
if (octets.length > IPV6_MAX_HEX_GROUPS) {
return false;
}
int validOctets = 0;
int emptyOctets = 0;
for (int index = 0; index < octets.length; index++) {
String octet = octets[index];
if (octet.length() == 0) {
emptyOctets++;
if (emptyOctets > 1) {
return false;
}
} else {
emptyOctets = 0;
if (octet.contains(".")) { // contains is Java 1.5+
if (!inet6Address.endsWith(octet)) {
return false;
}
if (index > octets.length - 1 || index > 6) { // CHECKSTYLE IGNORE MagicNumber
// IPV4 occupies last two octets
return false;
}
if (!isValidInet4Address(octet)) {
return false;
}
validOctets += 2;
continue;
}
if (octet.length() > IPV6_MAX_HEX_DIGITS_PER_GROUP) {
return false;
}
int octetInt = 0;
try {
octetInt = Integer.valueOf(octet, BASE_16).intValue();
} catch (NumberFormatException e) {
return false;
}
if (octetInt < 0 || octetInt > MAX_UNSIGNED_SHORT) {
return false;
}
}
validOctets++;
}
if (validOctets < IPV6_MAX_HEX_GROUPS && !containsCompressedZeroes) {
return false;
}
return true;
}
}

View File

@@ -1,237 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.integry.ems.object_storage.minio.sdk.org.apache.commons.validator.routines;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <b>Regular Expression</b> validation (using JDK 1.4+ regex support).
* <p>
* Construct the validator either for a single regular expression or a set (array) of
* regular expressions. By default validation is <i>case sensitive</i> but constructors
* are provided to allow <i>case in-sensitive</i> validation. For example to create
* a validator which does <i>case in-sensitive</i> validation for a set of regular
* expressions:
* </p>
* <pre>
* <code>
* String[] regexs = new String[] {...};
* RegexValidator validator = new RegexValidator(regexs, false);
* </code>
* </pre>
*
* <p>
* <ul>
* <li>Validate <code>true</code> or <code>false</code>:</li>
* <li>
* <ul>
* <li><code>boolean valid = validator.isValid(value);</code></li>
* </ul>
* </li>
* <li>Validate returning an aggregated String of the matched groups:</li>
* <li>
* <ul>
* <li><code>String result = validator.validate(value);</code></li>
* </ul>
* </li>
* <li>Validate returning the matched groups:</li>
* <li>
* <ul>
* <li><code>String[] result = validator.match(value);</code></li>
* </ul>
* </li>
* </ul>
*
* <p>
* <b>Note that patterns are matched against the entire input.</b>
*
* <p>
*
* <p>
* Cached instances pre-compile and re-use {@link Pattern}(s) - which according
* to the {@link Pattern} API are safe to use in a multi-threaded environment.
* </p>
*
* @version $Revision$
* @since Validator 1.4
*/
public class RegexValidator implements Serializable {
private static final long serialVersionUID = -8832409930574867162L;
private final Pattern[] patterns;
/**
* Construct a <i>case sensitive</i> validator for a single
* regular expression.
*
* @param regex The regular expression this validator will
* validate against
*/
public RegexValidator(String regex) {
this(regex, true);
}
/**
* Construct a validator for a single regular expression
* with the specified case sensitivity.
*
* @param regex The regular expression this validator will
* validate against
* @param caseSensitive when <code>true</code> matching is <i>case
* sensitive</i>, otherwise matching is <i>case in-sensitive</i>
*/
public RegexValidator(String regex, boolean caseSensitive) {
this(new String[]{regex}, caseSensitive);
}
/**
* Construct a <i>case sensitive</i> validator that matches any one
* of the set of regular expressions.
*
* @param regexs The set of regular expressions this validator will
* validate against
*/
public RegexValidator(String[] regexs) {
this(regexs, true);
}
/**
* Construct a validator that matches any one of the set of regular
* expressions with the specified case sensitivity.
*
* @param regexs The set of regular expressions this validator will
* validate against
* @param caseSensitive when <code>true</code> matching is <i>case
* sensitive</i>, otherwise matching is <i>case in-sensitive</i>
*/
public RegexValidator(String[] regexs, boolean caseSensitive) {
if (regexs == null || regexs.length == 0) {
throw new IllegalArgumentException("Regular expressions are missing");
}
patterns = new Pattern[regexs.length];
int flags = (caseSensitive ? 0 : Pattern.CASE_INSENSITIVE);
for (int i = 0; i < regexs.length; i++) {
if (regexs[i] == null || regexs[i].length() == 0) {
throw new IllegalArgumentException("Regular expression[" + i + "] is missing");
}
patterns[i] = Pattern.compile(regexs[i], flags);
}
}
/**
* Validate a value against the set of regular expressions.
*
* @param value The value to validate.
* @return <code>true</code> if the value is valid otherwise <code>false</code>.
*/
public boolean isValid(String value) {
if (value == null) {
return false;
}
for (int i = 0; i < patterns.length; i++) {
if (patterns[i].matcher(value).matches()) {
return true;
}
}
return false;
}
/**
* Validate a value against the set of regular expressions
* returning the array of matched groups.
*
* @param value The value to validate.
* @return String array of the <i>groups</i> matched if valid or <code>null</code> if invalid
*/
@SuppressFBWarnings(value = "PZLA", justification = "Null is checked, not empty array. API is clear as well.")
public String[] match(String value) {
if (value == null) {
return null;
}
for (int i = 0; i < patterns.length; i++) {
Matcher matcher = patterns[i].matcher(value);
if (matcher.matches()) {
int count = matcher.groupCount();
String[] groups = new String[count];
for (int j = 0; j < count; j++) {
groups[j] = matcher.group(j + 1);
}
return groups;
}
}
return null;
}
/**
* Validate a value against the set of regular expressions
* returning a String value of the aggregated groups.
*
* @param value The value to validate.
* @return Aggregated String value comprised of the
* <i>groups</i> matched if valid or <code>null</code> if invalid
*/
public String validate(String value) {
if (value == null) {
return null;
}
for (int i = 0; i < patterns.length; i++) {
Matcher matcher = patterns[i].matcher(value);
if (matcher.matches()) {
int count = matcher.groupCount();
if (count == 1) {
return matcher.group(1);
}
StringBuilder buffer = new StringBuilder();
for (int j = 0; j < count; j++) {
String component = matcher.group(j + 1);
if (component != null) {
buffer.append(component);
}
}
return buffer.toString();
}
}
return null;
}
/**
* Provide a String representation of this validator.
*
* @return A String representation of this validator
*/
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append("RegexValidator{");
for (int i = 0; i < patterns.length; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(patterns[i].pattern());
}
buffer.append("}");
return buffer.toString();
}
}

View File

@@ -11,11 +11,11 @@ import com.fasterxml.jackson.databind.annotation.JsonTypeResolver;
import com.google.common.base.Joiner;
import com.microsoft.sqlserver.jdbc.SQLServerConnection;
import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement;
import io.minio.errors.ErrorResponseException;
import it.integry.common.var.CommonConstants;
import it.integry.common.var.EmsDBConst;
import it.integry.ems.object_storage.minio.MinIONotEnabledException;
import it.integry.ems.object_storage.minio.MinIOService;
import it.integry.ems.object_storage.minio.sdk.errors.ErrorResponseException;
import it.integry.ems.object_storage.minio.sdk.errors.MinioException;
import it.integry.ems.rules.completing.CommonRules;
import it.integry.ems.rules.completing.ForeignKeyRules;
import it.integry.ems.rules.completing.UniqueKeyRules;
@@ -503,7 +503,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
return false;
}
public EntityBase selectAndMergeEntity(Connection connection, EntityBase entity) throws IllegalAccessException, IOException, FieldMissingException, SQLException, ConverterNotConfiguredException, MergeEntityDBToObjectException, MinioException, XmlPullParserException, NoSuchAlgorithmException, InvalidKeyException {
public EntityBase selectAndMergeEntity(Connection connection, EntityBase entity) throws IllegalAccessException, IOException, FieldMissingException, SQLException, ConverterNotConfiguredException, MergeEntityDBToObjectException, XmlPullParserException, NoSuchAlgorithmException, InvalidKeyException, MinIONotEnabledException {
String where;
if (!entity.getOnlyPkMaster() && entity.getOperation() == OperationType.SELECT_OBJECT) {
@@ -574,7 +574,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
} else throw new Exception("Impossibile confrontare le entity");
}
private EntityBase mergeEntityDBToObject(Connection connection, HashMap<String, Object> datiDb, EntityBase entity) throws IllegalAccessException, ConverterNotConfiguredException, SQLException, MinioException, XmlPullParserException, NoSuchAlgorithmException, IOException, InvalidKeyException, MergeEntityDBToObjectException {
private EntityBase mergeEntityDBToObject(Connection connection, HashMap<String, Object> datiDb, EntityBase entity) throws IllegalAccessException, ConverterNotConfiguredException, SQLException, XmlPullParserException, NoSuchAlgorithmException, IOException, InvalidKeyException, MergeEntityDBToObjectException, MinIONotEnabledException {
if (UtilityHashMap.isPresent(datiDb)) {
WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
MinIOService minIOService = context.getBean(MinIOService.class);
@@ -648,11 +648,13 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
}
field.set(entity, columnValue);
} catch (SQLException | MinioException | XmlPullParserException | NoSuchAlgorithmException |
} catch (SQLException | MinIONotEnabledException | XmlPullParserException | NoSuchAlgorithmException |
IOException | InvalidKeyException e) {
if (!UtilityDebug.isDebugExecution() && !UtilityDebug.isIntegryServer()) {
throw e;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -1290,7 +1292,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
}
public void completeEntityChild(Connection connection, EntityBase child, Boolean copyPk) throws InvocationTargetException, IllegalAccessException, RulesNotCompiledException, MergeEntityDBToObjectException, SQLException, MinioException, XmlPullParserException, IOException, NoSuchAlgorithmException, InvalidKeyException, FieldMissingException, ConverterNotConfiguredException {
public void completeEntityChild(Connection connection, EntityBase child, Boolean copyPk) throws InvocationTargetException, IllegalAccessException, RulesNotCompiledException, MergeEntityDBToObjectException, SQLException, XmlPullParserException, IOException, NoSuchAlgorithmException, InvalidKeyException, FieldMissingException, ConverterNotConfiguredException, MinIONotEnabledException {
child.setParent(this);
if (copyPk) {
child.setParentPKAndImportFromParent(this, true);

View File

@@ -30,6 +30,8 @@ import java.sql.Connection;
import java.util.*;
import java.util.stream.Collectors;
import static org.reflections.scanners.Scanners.SubTypes;
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class EntityPropertyHolder {
@@ -77,12 +79,15 @@ public class EntityPropertyHolder {
}
public List<EntityHierarchyDTO> scanEntityMapping() {
Reflections reflections = new Reflections("it.integry.ems_model.entity");
List<EntityHierarchyDTO> mapping = new ArrayList<>();
Set<Class<? extends EntityBase>> classes = reflections.getSubTypesOf(EntityBase.class);
Reflections reflections = new Reflections("it.integry.ems_model.entity");
Set<Class<? extends EntityBase>> classes = reflections.get(SubTypes.of(EntityBase.class).asClass())
.stream().map(x -> (Class<? extends EntityBase>) x)
.collect(Collectors.toSet());
for (Class<? extends EntityBase> entity : classes) {
if(!entity.isAnnotationPresent(Table.class)) continue;
if (!entity.isAnnotationPresent(Table.class)) continue;
EntityHierarchyDTO dto = new EntityHierarchyDTO();
dto.setClazz(entity);
@@ -99,15 +104,13 @@ public class EntityPropertyHolder {
private void scanEntityFields() {
Reflections reflections = new Reflections("it.integry.ems_model.entity");
List<Class<?>> clssList = new ArrayList<>(Stream.of(reflections.getSubTypesOf(EntityBase.class))
.toList());
List<Class<?>> clssList = new ArrayList<>(reflections.get(SubTypes.of(EntityBase.class).asClass()));
for (int i = 0; i < clssList.size(); i++) {
Class<?> clazz = clssList.get(i);
if (Modifier.isAbstract(clazz.getModifiers())) {
List<Class<?>> childClssList = new ArrayList<>(Stream.of(reflections.getSubTypesOf(clazz)).toList());
List<Class<?>> childClssList = new ArrayList<>(reflections.get(SubTypes.of(clazz).asClass()));
clssList.addAll(childClssList);
clssList.remove(i);

View File

@@ -89,7 +89,8 @@ public class UtilityReflection {
}
}
}
} catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
} catch (SecurityException | NoSuchFieldException | IllegalArgumentException |
IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

View File

@@ -1,13 +1,4 @@
import it.integry.ems_model.annotation.SqlField;
import it.integry.ems_model.base.EntityBase;
import it.integry.ems_model.base.EntityPropertyHolder;
import org.apache.commons.io.IOUtils;
import org.reflections.Reflections;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.util.Set;
public class EntityTestDefaultVal {
@@ -21,32 +12,32 @@ public class EntityTestDefaultVal {
EntityPropertyHolder holder = new EntityPropertyHolder();
holder.init();
Reflections reflections = new Reflections("it.integry.ems_model.entity");
Set<Class<? extends EntityBase>> clssList = reflections.getSubTypesOf(EntityBase.class);
for (Class<?> clazz : clssList) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
SqlField sf = field.getAnnotation(SqlField.class);
if (sf != null && !sf.defaultObjectValue().equals("")) {
String search = clazz.getSimpleName() + "(" + field.getName() + " == null";
for (String drl : dlrs) {
if (clazz.getResource("/rules/" + drl) != null) {
File fileDRL = new File(clazz.getResource("/rules/" + drl).toURI());
if (fileDRL.exists()) {
String fileString = IOUtils.toString(new FileInputStream(fileDRL));
if (fileString.contains(search)) {
System.out.println(search + " on " + drl);
}
}
}
}
}
}
}
// Reflections reflections = new Reflections("it.integry.ems_model.entity");
// Set<Class<? extends EntityBase>> clssList = reflections.getSubTypesOf(EntityBase.class);
//
// for (Class<?> clazz : clssList) {
//
// Field[] fields = clazz.getDeclaredFields();
// for (Field field : fields) {
//
// SqlField sf = field.getAnnotation(SqlField.class);
// if (sf != null && !sf.defaultObjectValue().equals("")) {
// String search = clazz.getSimpleName() + "(" + field.getName() + " == null";
// for (String drl : dlrs) {
// if (clazz.getResource("/rules/" + drl) != null) {
// File fileDRL = new File(clazz.getResource("/rules/" + drl).toURI());
// if (fileDRL.exists()) {
// String fileString = IOUtils.toString(new FileInputStream(fileDRL));
// if (fileString.contains(search)) {
// System.out.println(search + " on " + drl);
// }
//
// }
// }
// }
// }
// }
// }
}
}

View File

@@ -178,13 +178,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.10</version>
<version>3.14.0</version>
</dependency>
<dependency>

View File

@@ -789,8 +789,6 @@ public class CrmService {
public List<EntityBase> buildEntityDest(String tipoAnag, String codAnag, String codVdes, CrmDestinazione crmDestinazione) throws Exception {
List<EntityBase> entityList = new ArrayList<EntityBase>();
EntityBase entity = new EntityBase() {
};
if ("C".equals(tipoAnag)) {
List<VtbDest> vtbDestList = new ArrayList<VtbDest>();

Some files were not shown because too many files have changed in this diff Show More