Class ODClient

  • All Implemented Interfaces:
    OdilonClient

    public class ODClient
    extends Object
    implements OdilonClient

    This class implements a simple Odilon Object Storage client.

    Service

    • Creating a bucket
    • Listing buckets

    Bucket

    • Creating an object, including automatic multipart for large objects.
    • Listing objects in a bucket
    • Listing active multipart uploads

    Object

    • Removing an active multipart upload for a specific object and uploadId
    • Read object metadata
    • Reading an object
    • Reading a range of bytes of an object
    • Deleting an object

    For examples on using this library, please see

    • Field Detail

      • DEFAULT_CONNECTION_TIMEOUT

        public static final int DEFAULT_CONNECTION_TIMEOUT
        See Also:
        Constant Field Values
      • DEFAULT_USER_AGENT

        public static final String DEFAULT_USER_AGENT
    • Constructor Detail

      • ODClient

        public ODClient​(String endpoint,
                        int port,
                        String accessKey,
                        String secretKey)

        By default the server has the following settings in file odilon.properties

        • endpoint. "http://localhost"
        • port. 9234
        • accessKey. "odilon"
        • secretKey. "odilon"
      • ODClient

        public ODClient​(String endpoint,
                        int port,
                        String accessKey,
                        String secretKey,
                        boolean secure)
    • Method Detail

      • getUrl

        public String getUrl()
        Specified by:
        getUrl in interface OdilonClient
        Returns:
        server url (without the port)
      • putObject

        public io.odilon.model.ObjectMetadata putObject​(String bucketName,
                                                        String objectName,
                                                        File file)
                                                 throws ODClientException

        Uploads the File file to the server

        Example:
        
         String endpoint = "http://localhost"; 
         // default port 
          int port = 9234; 
        	
         // default credentials 
         String accessKey = "odilon";
         String secretKey = "odilon";
        			
         String bucketName  = "demo_bucket";
         String objectName1 = "demo_object1";
         String objectName2 = "demo_object2";
        			
         File file1 = new File("test1.pdf");
         File file2 = new File("test2.pdf");
        			
         // put two objects in the bucket
         // the bucket must exist before sending the object,
         // and object names must be unique for that bucket  
        			
         OdilonClient client = new ODClient(endpoint, port, accessKey, secretKey);
        
         client.putObject(bucketName, objectName1, file1);
         client.putObject(bucketName, objectName2, file2);
        
        
        Specified by:
        putObject in interface OdilonClient
        Parameters:
        bucketName - Bucket name
        objectName - Object name
        Returns:
        ObjectMetadata of the Object created or updated
        Throws:
        ODClientException
      • putObject

        public io.odilon.model.ObjectMetadata putObject​(String bucketName,
                                                        String objectName,
                                                        InputStream stream,
                                                        String fileName,
                                                        String contentType)
                                                 throws ODClientException
        Description copied from interface: OdilonClient

        Odilon stores objects using a flat structure of containers called Buckets. A bucket is like a folder, it just contains binary objects, potentially a very large number. Every object contained by a bucket has a unique ObjectName in that bucket; therefore, the pair BucketName + ObjectName is a Unique ID for each object in Odilon.

        Uploading a File requires the Bucket to exist and the ObjectName to be unique for that bucket.

        The Odilon client closes the InputStream after sending the data to the server. However, if an Exception other than ODClientException is thrown by this method, the InputStream may not have been closed.

        Therefore callers must always attempt to close the Inputstream

        Example:
        
         File file = new File("test.pdf");
        	String bucketName = "bucket-demo";
        	String objectName = file.getName();
        
         try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))){	
        		client.putObjectStream(bucketName,objectName,inputStream,Optional.of(file.getName()),Optional.empty());
        	} catch (ODClientException e) {
        		System.out.println(String.valueOf(e.getHttpStatus())+" " + e.getMessage() +" " + String.valueOf(e.getErrorCode()));
        	} catch (FileNotFoundException | IOException e1) {
        		System.out.println(e1.getMessage());
        	}
         
        Specified by:
        putObject in interface OdilonClient
        Parameters:
        bucketName - Bucket name
        objectName - Object name
        Returns:
        ObjectMetadata of the Object created or updated
        Throws:
        ODClientException
      • listObjects

        public io.odilon.model.list.ResultSet<io.odilon.model.list.Item<io.odilon.model.ObjectMetadata>> listObjects​(String bucketName)
                                                                                                              throws ODClientException

        Item is a wrapper for Lists and other Iterable structures of T where some elements may not be a T but an error.
        T must be Serializable

        Example list all bucket's objects:
         
         try {
        	ResultSet<Item <ObjectMetadata>> resultSet = client.listObjects(bucket.getName());
        		while (resultSet.hasNext()) {
        			Item item = resultSet.next();
        			if (item.isOk())
        				System.out.println("ObjectName:" +  item.getObject().objectName + " | file: " + item.getObject().fileName);
        			else
        				System.out.println(item.getErrorString());
        		}
        	} catch (ODClientException e) {
        	   	System.out.println(String.valueOf( e.getHttpStatus())+ " " + e.getMessage() + " " + String.valueOf(e.getErrorCode()) );
        	}
        
         
        Specified by:
        listObjects in interface OdilonClient
        Parameters:
        bucketName - Bucket name
        Returns:
        Throws:
        ODClientException
      • listObjects

        public io.odilon.model.list.ResultSet<io.odilon.model.list.Item<io.odilon.model.ObjectMetadata>> listObjects​(String bucketName,
                                                                                                                     Optional<String> prefix,
                                                                                                                     Optional<Integer> pageSize)
                                                                                                              throws ODClientException
        Description copied from interface: OdilonClient

        Item <T> is a wrapper for Lists and other iterable structures of T where some elements may not be a T but an error.
        T must be Serializable

        Example list all bucket's objects:
         
         try {
        	ResultSet<Item <ObjectMetadata>> resultSet = client.listObjects(bucket.getName());
        		while (resultSet.hasNext()) {
        			Item item = resultSet.next();
        			if (item.isOk())
        				System.out.println("ObjectName:" +  item.getObject().objectName + " | file: " + item.getObject().fileName);
        			else
        				System.out.println(item.getErrorString());
        		}
        	} catch (ODClientException e) {
        	   	System.out.println(String.valueOf( e.getHttpStatus())+ " " + e.getMessage() + " " + String.valueOf(e.getErrorCode()) );
        	}
        
         
        Specified by:
        listObjects in interface OdilonClient
        Throws:
        ODClientException
      • listBuckets

        public List<io.odilon.model.Bucket> listBuckets()
                                                 throws ODClientException

        Returns all buckets, sorted alphabetically

        Example:

        List<Bucket> bucketList = odilonClient.listBuckets();
         for (Bucket bucket : bucketList) {
           	System.out.println(bucket.creationDate() + ", " + bucket.name());
         } 
         

        Specified by:
        listBuckets in interface OdilonClient
        Returns:
        List of buckets
        Throws:
        ODClientException
      • getBucket

        public io.odilon.model.Bucket getBucket​(String bucketName)
                                         throws ODClientException
        Description copied from interface: OdilonClient

        Returns the Bucket

        Specified by:
        getBucket in interface OdilonClient
        Parameters:
        bucketName - Bucket name
        Returns:
        Bucket
        Throws:
        ODClientException - if the Bucket does not exist the error code getErrorCode() returns ErrorCode.BUCKET_NOT_EXISTS
      • createBucket

        public void createBucket​(String bucketName)
                          throws ODClientException
        Description copied from interface: OdilonClient

        bucketName length must be lower or equal to SharedConstant.MAX_BUCKET_CHARS and match the regular expression SharedConstant.bucket_valid_regex (see OdilonClient.isValidBucketName(java.lang.String))

        Example:
        
         try {
           String bucketName = "bucket-demo";
           // check if the bucket exists, if not create it
           if (client.existsBucket(bucketName))
               System.out.println("bucket already exists ->" + bucketName );
           else 
               client.createBucket(bucketName);
         } catch (ODClientException e) {
               System.out.println( String.valueOf(e.getHttpStatus())+ " " + e.getMessage() + " " + String.valueOf(e.getErrorCode()) );
         }
         
        Specified by:
        createBucket in interface OdilonClient
        Parameters:
        bucketName - Bucket name
        Throws:
        ODClientException - if the bucket already exists (error code ErrorCode.OBJECT_ALREADY_EXIST)
      • deleteBucket

        public void deleteBucket​(String bucketName)
                          throws ODClientException
        Description copied from interface: OdilonClient

        Deletes a bucket. The bucket must be empty to be deleted

        Specified by:
        deleteBucket in interface OdilonClient
        Parameters:
        bucketName - Bucket name
        Throws:
        ODClientException -
        Bucket does not exist -> ODHttpStatus.NOT_FOUND with error code ErrorCode.BUCKET_NOT_EXISTS
        Bucket is not empty -> with error code {@link ErrorCode.BUCKET_NOT_EMPTY}
      • deleteObject

        public void deleteObject​(String bucketName,
                                 String objectName)
                          throws ODClientException

        Removes an object from a bucket.

        Example:

        odilonClient.deleteObject("my-bucketname", "my-objectname"); 

        Specified by:
        deleteObject in interface OdilonClient
        Parameters:
        bucketName - Bucket name
        objectName - Object name in the bucket
        Throws:
        ODClientException
      • deleteAllBucketVersions

        public void deleteAllBucketVersions​(String bucketName)
                                     throws ODClientException
        Description copied from interface: OdilonClient

        Deletes all Objects' previous versions. It does not delete the current version (called head version).
        This method is sometimes used to free disk in the server

        The method returns immediately after sending the command to the server. The command is processed asynchronously in the server.

        Specified by:
        deleteAllBucketVersions in interface OdilonClient
        Parameters:
        bucketName - Bucket name
        Throws:
        ODClientException -
        Bucket does not exist -> ODHttpStatus.NOT_FOUND with error code ErrorCode.BUCKET_NOT_EXISTS
        Server does not have Version Control enabled -> ODHttpStatus.METHOD_NOT_ALLOWED with error code ErrorCode.API_NOT_ENABLED Version Control not enabled
      • ping

        public String ping()

        Returns the String "ok" or a String with the error reported by the Server. If the client can not connect to the Server, the method returns a message "can not connect"

        Example:
        {@code String pingResult = odilonClient.ping();
         
         if (!pingResult.equals("ok")) {
           System.out.println( "Server error -> " + pingResult));
         }
        Specified by:
        ping in interface OdilonClient
        Returns:
        String "ok" or the error reported by the Server.
      • getPresignedObjectUrl

        public String getPresignedObjectUrl​(String bucketName,
                                            String objectName,
                                            Optional<Integer> expires)
                                     throws ODClientException

        A presigned URL is a way to grant temporary access to an Object, for example in an HTML webpage. It remains valid for a limited period of time which is specified when the URL is generated.

        Specified by:
        getPresignedObjectUrl in interface OdilonClient
        Parameters:
        bucketName - Bucket name
        objectName - Object name
        expires - duration in seconds for the url to be valid
        Returns:
        temporary url to download the file without authentication
        Throws:
        ODClientException
      • getObjectMetadata

        public io.odilon.model.ObjectMetadata getObjectMetadata​(String bucketName,
                                                                String objectName)
                                                         throws ODClientException

        Returns ObjectMetadata of given object in given bucket.

        Example:

        ObjectMetadata meta = odilonClient.getObjectMetadata("my-bucketname", "my-objectname");
           			System.out.println(meta.toString()));
        Specified by:
        getObjectMetadata in interface OdilonClient
        Parameters:
        bucketName - Bucket name
        objectName - Object name in the bucket
        Returns:
        Throws:
        ODClientException
      • getObjectMetadataPreviousVersion

        public io.odilon.model.ObjectMetadata getObjectMetadataPreviousVersion​(String bucketName,
                                                                               String objectName)
                                                                        throws ODClientException

        Returns ObjectMetadata of previous version

        Example:

        ObjectMetadata meta = odilonClient.getObjectMetadata("my-bucketname", "my-objectname");
           			System.out.println(meta.toString()));
        Specified by:
        getObjectMetadataPreviousVersion in interface OdilonClient
        Parameters:
        bucketName - Bucket name.
        objectName - Object name in the bucket.
        Throws:
        ODClientException
      • getObject

        public InputStream getObject​(String bucketName,
                                     String objectName)
                              throws ODClientException

        Gets entire object's data as InputStream in given bucket. The InputStream must be closed after use else the connection will remain open.

        Example:
        InputStream stream = OdilonClient.getObject("my-bucketname", "my-objectname");
         byte[] buf = new byte[16384];
         int bytesRead;
         while ((bytesRead = stream.read(buf, 0, buf.length)) >= 0) {
           System.out.println(new String(buf, 0, bytesRead));
         }
         stream.close(); 
        Specified by:
        getObject in interface OdilonClient
        Parameters:
        bucketName - Bucket name
        objectName - Object name in the bucket
        Returns:
        InputStream containing the object data.
        Throws:
        ODClientException
      • setTimeout

        public void setTimeout​(long connectTimeout,
                               long writeTimeout,
                               long readTimeout)

        Sets HTTP connect, write and read timeouts. A value of 0 means no timeout, otherwise values must be between 1 and Integer.MAX_VALUE when converted to milliseconds.

        Example:
        odilonClient.setTimeout(TimeUnit.SECONDS.toMillis(10), TimeUnit.SECONDS.toMillis(10),
                                    TimeUnit.SECONDS.toMillis(30)); 
        Specified by:
        setTimeout in interface OdilonClient
        Parameters:
        connectTimeout - HTTP connect timeout in milliseconds.
        writeTimeout - HTTP write timeout in milliseconds.
        readTimeout - HTTP read timeout in milliseconds.
      • isValidBucketName

        public boolean isValidBucketName​(String name)
        Description copied from interface: OdilonClient

        • Max length: SharedConstant.MAX_BUCKET_CHARS
        • Regular expression that must match: SharedConstant.bucket_valid_regex
        Specified by:
        isValidBucketName in interface OdilonClient
        Parameters:
        name - Bucket name
        Returns:
        whether the bucketName is a valid Odilon bucket name
      • traceOn

        public void traceOn​(OutputStream traceStream)
        Description copied from interface: OdilonClient
        ======================================= DEBUG ==========================================
        Specified by:
        traceOn in interface OdilonClient
      • toJSON

        public String toJSON()
      • setChunk

        public void setChunk​(int chunkSize)
      • getChunk

        public int getChunk()
      • getObjectMapper

        protected com.fasterxml.jackson.databind.ObjectMapper getObjectMapper()