Transloadit's official Android SDK, maintained by the community
Java
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
TransloaditLib
TransloaditLibTest
bin
doc
LICENSE
README.md

README.md

Important

The Transloadit Android SDK works with Android 2.2 Froyo (API level 8) or with any newer version.

It uses the Apache HttpComponents library. (Description in: Transloadit Android SDK -> 1. Dependencies)

Purpose

This is the official Android SDK for the transloadit.com API.

It allows you to easily use Transloadit services in your Android applications.

Directory structure

  • "TransloaditLib" - Contains the SDK source (Android project)
  • "TransloaditLibTest" - Contains unit tests (Android test project)
  • "bin" - compiled jar file
  • "doc" - javadoc

Examples

The SDK is easy to configure, use and extend. Please see the details below.

Sample application

The sample application below is part of a simple Android application.

1. Upload a file, use pre-created template with all required settings

package hu.szabot.transloaditTest;

import hu.szabot.transloadit.ITransloadit;
import hu.szabot.transloadit.Transloadit;
import hu.szabot.transloadit.TransloaditResponse;
import hu.szabot.transloadit.assembly.AssemblyBuilder;
import hu.szabot.transloadit.assembly.IAssemblyBuilder;
import hu.szabot.transloadit.exceptions.FileNotOpenableException;
import hu.szabot.transloadit.log.TransloaditLogger;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class TransloaditActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Create Transloadit instance
        ITransloadit transloadit = new Transloadit("YOUR-API-KEY-HERE");

        //Create assembly builder to build up the assembly
        IAssemblyBuilder assembly = new AssemblyBuilder();

        //Set template ID
        assembly.setTemplateID("YOUR-PRECREATED-TEMPLATE-ID");

        try {

            //Add a file to be uploaded with autogenerated key
            assembly.addFile(new File(Environment.getExternalStorageDirectory().getPath()+"/YOUR-FILE"));

        } catch (FileNotOpenableException e)
        {
            TransloaditLogger.logError(getClass(), e);
        }

        try
        {
            //Invoke assembly, and wait for the result
            TransloaditResponse response = transloadit.invokeAssembly(assembly);

            if (response.isSuccess())
            {
                TransloaditLogger.logInfo(getClass(), "Assembly %s result", (String)response.getData().get("assembly_id"));
            }
            else
            {
                TransloaditLogger.logError(getClass(), "Error has occured while completing assembly");
            }
        }catch (IOException e)
        {
            TransloaditLogger.logError(getClass(),e, "Error has occured while completing assembly");
        }

    }
}

2. Upload a file, with custom assembly with all required and optional settings

package hu.szabot.transloaditTest;

import hu.szabot.transloadit.ITransloadit;
import hu.szabot.transloadit.Transloadit;
import hu.szabot.transloadit.TransloaditResponse;
import hu.szabot.transloadit.assembly.AssemblyBuilder;
import hu.szabot.transloadit.assembly.IAssemblyBuilder;
import hu.szabot.transloadit.assembly.IStep;
import hu.szabot.transloadit.assembly.Step;
import hu.szabot.transloadit.assembly.exceptions.InvalidFieldKeyException;
import hu.szabot.transloadit.exceptions.FileNotOpenableException;
import hu.szabot.transloadit.log.TransloaditLogger;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class TransloaditActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Create Transloadit instance
        ITransloadit transloadit = new Transloadit("YOUR-API-KEY-HERE");

        //Create assembly builder to build up the assembly
        IAssemblyBuilder assembly = new AssemblyBuilder();

        try
        {
            //Add a file to be uploaded with autogenerated key
            assembly.addFile(new File(Environment.getExternalStorageDirectory().getPath()+"/YOUR-FILE"));
        }
        catch (FileNotOpenableException e)
        {
            TransloaditLogger.logError(getClass(), e);
        }

        try
        {
            //Add a file to be uploaded with custom key
            assembly.addFile("custom_file",new File(Environment.getExternalStorageDirectory().getPath()+"/YOUR-FILE"));
        }
        catch (FileNotOpenableException e)
        {
            TransloaditLogger.logError(getClass(), e);
        }
        catch (InvalidFieldKeyException e)
        {
            TransloaditLogger.logError(getClass(), e);
        }

        //Define the step, you can define more in the same assembly
        IStep step = new Step();
        step.setOption("robot", "/image/resize");
        step.setOption("width", 75);
        step.setOption("height", 75);
        step.setOption("resize_strategy", "pad");
        step.setOption("background", "#000000");

        //Add the step to the assembly
        assembly.addStep("thumb", step);

        //Set notification URL
        assembly.setNotifyURL("http://your-service.net/ready");

        //Set the expiration date time of the request for the assembly
        //Assembly will be expired in 120 minutes from now
        assembly.setAuthExpires(new Date(new Date().getTime() + 120 * 60000));

        try
        {
            //Invoke assembly, and wait for the result
            TransloaditResponse response = transloadit.invokeAssembly(assembly);

            if (response.isSuccess())
            {
                TransloaditLogger.logInfo(getClass(), "Assembly %s result", (String)response.getData().get("assembly_id"));
            }
            else
            {
                TransloaditLogger.logError(getClass(), "Error has occured while completing assembly");
            }

        }catch (IOException e)
        {
            TransloaditLogger.logError(getClass(),e, "Error has occured while completing assembly");
        }
    }
}

Transloadit Android SDK

You need to download the necessary jar file and integrate it to your application. Also you can pull the source code and compile it with your application.

1. Dependencies

The SDK uses the Apache HttpComponents library. You can download it from: http://hc.apache.org/downloads.cgi

Required libraries:

  • Httpcore-x.y.jar
  • Httpmime-x.y.jar

2. Use of the SDK

If you would like to use the Android SDK for Transloadit in your application, you need to add it as a jar library, or you need to pull the latest commit, and use the source directly.

Transloadit services work with assemblies. An assembly must contain each information which will be used for authentication and processing. Each assembly must contain authentication information, steps or template ID. You can set custom, and optional values like custom fields and files too.

Note: template ID is the ID of a Transloadit template that can be created in your Transloadit account.

2.1. Use of Transloadit class

With that class you are able to create a Transloadit instance, which will process all the assemblies sent by your application.

ITransloadit transloadit = new Transloadit(YOUR-API-KEY);

Note: You can use Transloadit instances as singleton instances.

2.2. Build an assembly

To build up an assembly you need to use assembly.AssemblyBuilder.

IAssemblyBuilder builder = new AssemblyBuilder();

As described above, to define steps for your assembly you can use assembly.Step class. Each step must have option(s), which can be set with the setOption(String key, Object value) method. That step will be proceeded on your uploaded, or predefined resources.

// Step below will resize the uploaded image to 75x75 size
// with the pad resize strategy and with a black background color

IStep step = new Step();
step.setOption("robot", "/image/resize");
step.setOption("width", 75);
step.setOption("height", 75);
step.setOption("resize_strategy", "pad");
step.setOption("background", "#000000");

To add that step to your assembly you need to call the addStep(String name, IStep step) method, where the name parameter is the key of the step. You can refer to that in further steps in the same assembly, even if you add more.

builder.addStep("resize", step);

2.2.1. Add custom field to the assembly

Custom fields can be set for each assembly as a parameter of a pre-created template. You can set custom fields with setField(String key, Object value) method, where the key parameter is the unique key of the field and value parameter is the value of the field.

If a valid key is not defined in the custom field collection, then it will be created, also the related value will be set. If a valid key is already defined then it will be overriden with the passed value.

There are some field keys which are used by the SDK. You are not able to use these keys as custom field keys such as "notify_url", "params", "signature", "template_id". If you try to use one of those keys, then a assembly.exceptions.InvalidKeyFieldKeyException will be thrown.

assembly.exceptions.AlreadyDefinedFieldKeyException will be thrown, if you try to use a custom field key, which is already defined as a key of a file (read about files in the next section below).

builder.setField("field_key", "field_value")

2.2.2. Adding a file to an assembly

You can call addFile(File file) or addFile(String key, File file) method, where the key parameter is the unique key of the file and the file parameter is the File class of the file, on the created builder object to add a file to your assembly.

If you call the method with only the file parameter, then the key of the file will be an autogenerated key. If you call the method with both parameters, then the file will be added with the specified key. If the key is already defined as a custom field key or a file key, then an autogenerated key will be set for the file.

builder.addFile(new File("/yourFile.png")) or builder.addFile("custom_file", File("/yourFile.png"))

2.2.3. Setting authentication information

You can set authentication information as per the examples below.

The Transloadit constructor sets the API key.

The following methods can be called on the builder object:

builder.setAuthExpires(new Date(new Date().getTime() + 120 * 60000)); //Request will be expired after the current date time + 120 minutes
builder.setAuthMaxSize(1024);

Note: These methods are optional

2.2.4. Set notify URL

You can define a notify URL for your assembly by calling setNotifyURL(String notifyURL) on the builder object, which will be requested after the assembly is done on Transloadit server.

builder.setNotifyURL("http://your-service.net/ready");

If your assembly is done, then a POST request will be sent to the specified notify URL. That request will contain information about the status of the created assembly and it will also contain all information about the result files. If Transloadit has sent assembly_url as a GET parameter, then that URL will be called by a TransloaditRequest.

For example: You have a mobile application, which invokes assemblies via that Android SDK, and you have a REST API service written in PHP, which can handle the request which will be sent after the assembly is done. What you need to do is to integrate the PHP Transloadit SDK to your PHP REST API service and call Transloadit::response() method, then you will be able to use the result of the assembly in your service (like creating database records for example).

2.2.5. Set template ID

You can define a template ID which will be used to process your assembly on the Transloadit servers. You can use setTemplateID(String templateID) for that, where the templateID parameter is the ID of the precreated template.

builder.setTemplateID("ID-OF-PRECEREATED-TEMPLATE");

2.2.6. Creating an assembly

Once your assembly is built up you can send it to the Transloadit servers with the invokeAssembly(IAssmeblyBuilder builder) method, where the builder parameter is the built up instance of AssemblyBuilder class, that can be called on the transloadit object. The result of the assembly will be represented in an ITransloaditResponse instance.

ITransloaditResponse response = transloadit.invokeAssembly(builder);

Once the request is done and the response object was created, you are able to examine its properties:

  • response.getData() - returns the response as a dictionary (Map<String, Object>)
  • response.getResponseString() - returns the response string
  • response.isSuccess() - returns the success of the request

Note: response.getData() main Map can store sub Maps as the value of the main Map

2.2.7. Deleting an assembly

Transloadit Android SDK gives you the possibility to delete an assembly on the server. You can call the deleteAssembly(String assemblyID) method, where assemblyID parameter is the ID of an exisiting assembly, on the created transloadit object. That call can be useful when you would like to cancel an assembly.

´ITransloaditResponse response = transloadit.deleteAssembly("YOUR-CREATED-ASSEMBLY-ID");´

You can handle the response like in case of invoke an assembly.

2.3. Usage of the logger class

The SDK provides you the possibility to log information and errors. You can use the default TransloaditLogger.

  • logInfo(Class<?> type, String message, Object... parameters) - logs information, where type is the type of the sender object, message is the custom log message with parameters and parameters are the parameters of the custom log message
  • logError(Class<?> type, Exception exception, String message, Object... parameters) - logs an error (recommended to use in case of an exception thrown), where the type is the type of the sender object, exception is the thrown exception, message is the custom log message with parameters and parameters are the parameters of the custom log message

*Note: * logError(...) method has more parameter definition

3. Extend Transloadit Android API

The SDK is able to be extended. You can use the interfaces to create your own implementations and you can extend the pre-created classes.

4. Run unit tests

To pass all unit tests you need JUnit 3. Run the test project as an Android JUnit Test.

4.1 Constants Class

To run the tests you need to fill out the Constants.java file.

  • API_KEY Your Transloadit API key
  • TEST_IMAGE_ON_SD_CARD test image file path on the SD card
  • TEMPLATE_ID template ID
  • SECRET_KEY Your secret key.
  • SIGNATURE_AUTHENTICATION Using server authentication or not. Same as the server settings.