Skip to content

Repository files navigation

algorithmia-java

Java client for accessing Algorithmia's algorithm marketplace and data APIs.

Algorithmia Client Java Docs

Latest Release

Getting started

The Algorithmia java client is published to Maven central and can be added as a dependency via:

<dependency>
<groupId>com.algorithmia</groupId>
<artifactId>algorithmia-client</artifactId>
<version>[,1.1.0)</version>
</dependency>

Instantiate a client using your API Key:

AlgorithmiaClientclient = Algorithmia.client(apiKey);

Notes:

  • API key may be omitted only when making calls from algorithms running on the Algorithmia cluster
  • Using version range [,1.1.0) is recommended as it implies using the latest backward-compatible bugfixes.

Now you are ready to call algorithms.

Calling Algorithms

The following examples of calling algorithms are organized by type of input/output which vary between algorithms.

Note: a single algorithm may have different input and output types, or accept multiple types of input, so consult the algorithm's description for usage examples specific to that algorithm.

Text input/output

Call an algorithm with text input by simply passing a string into its pipe method. If the algorithm output is text, call the asString method on the response.

Algorithmalgo = client.algo("algo://demo/Hello/0.1.1");
AlgoResponseresult = algo.pipe("HAL 9000");
System.out.println(result.asString());
// -> Hello HAL 9000

JSON input/output

Call an algorithm with JSON input by simply passing in a type that can be serialized to JSON, including most plain old java objects and collection types. If the algorithm output is JSON, call the as method on the response with a TypeToken containing the type that it should be deserialized into:

Algorithmalgo = client.algo("algo://WebPredict/ListAnagrams/0.1.0");
List<String> words = Arrays.asList(("transformer", "terraforms", "retransform");
AlgoResponseresult = algo.pipe(words);
// WebPredict/ListAnagrams returns an array of strings, so cast the result:List<String> anagrams = result.as(newTypeToken<List<String>>(){});
// -> List("transformer", "retransform")

Alternatively, you may work with raw JSON input by calling pipeJson, and raw JSON output by calling asJsonString on the response:

StringjsonWords = "[\"transformer\", \"terraforms\", \"retransform\"]";
AlgoResponseresult2 = algo.pipeJson(jsonWords);
Stringanagrams = result2.asJsonString();
// -> "[\"transformer\", \"retransform\"]"DoubledurationInSeconds = response.getMetadata().duration;

Binary input/output

Call an algorithm with binary input by passing a byte[] into the pipe method. If the algorithm response is binary data, then call the as method on the response with a byte[]TypeToken to obtain the raw byte array.

byte[] input = Files.readAllBytes(newFile("/path/to/bender.jpg").toPath());
AlgoResponseresult = client.algo("opencv/SmartThumbnail/0.1").pipe(input);
byte[] buffer = result.as(newTypeToken<byte[]>(){});
// -> [byte array]

Error handling

API errors will result in the call to pipe throwing APIException. Errors that occur durring algorithm execution will result in AlgorithmException when attempting to read the response.

Algorithmalgo = client.algo('util/whoopsWrongAlgo')
try {
AlgoResponseresult = algo.pipe('Hello, world!');
Stringoutput = result.asString();
} catch (APIExceptionex) {
System.out.println("API Exception: "ex.getMessage());
} catch (AlgorithmExceptionex) {
System.out.println("Algorithm Exception: "ex.getMessage());
System.out.println(ex.stacktrace);
}

Request options

The client exposes options that can configure algorithm requests. This includes support for changing the timeout or indicating that the API should include stdout in the response.:

Algorithmalgo = client.algo("algo://demo/Hello/0.1.1")
.setTimeout(1, TimeUnit.MINUTES)
.setStdout(true);
AlgoResponseresult = algo.pipe("HAL 9000");
Doublestdout = response.getMetadata().stdout;

Note: setStdout(true) is ignored if you do not have access to the algorithm source.

Working with Data

The Algorithmia Java client also provides a way to manage both Algorithmia hosted data and data from Dropbox or S3 accounts that you've connected to you Algorithmia account.

This client provides a DataFile type (generally created by client.file(uri)) and a DataDir type (generally created by client.dir(uri)) that provide methods for managing your data.

Create directories

Create directories by instantiating a DataDirectory object and calling create():

DataDirectoryrobots = client.dir("data://.my/robots");
robots.create();
DataDirectorydbxRobots = client.dir("dropbox://robots");
dbxRobots.create();

Upload files to a directory

Upload files by calling put on a DataFile object, or by calling putFile on a DataDirectory object.

DataDirectoryrobots = client.dir("data://.my/robots");
// Upload local filerobots.putFile(newFile("/path/to/Optimus_Prime.png"));
// Write a text filerobots.file("Optimus_Prime.txt").put("Leader of the Autobots");
// Write a binary filerobots.file("Optimus_Prime.key").put(newbyte[] { (byte)0xe0, 0x4f, (byte)0xd0, 0x20 });

Download contents of file

Download files by calling getString, getBytes, or getFile on a DataFile object:

DataDirectoryrobots = client.dir("data://.my/robots");
// Download file and get the file handleFilet800File = robots.file("T-800.png").getFile();
// Get the file's contents as a stringStringt800Text = robots.file("T-800.txt").getString();
// Get the file's contents as a byte arraybyte[] t800Bytes = robots.file("T-800.png").getBytes();

Delete files and directories

Delete files and directories by calling delete on their respective DataFile or DataDirectory object. DataDirectories take an optional force parameter that indicates whether the directory should be deleted if it contains files or other directories.

client.file("data://.my/robots/C-3PO.txt").delete();
client.dir("data://.my/robots").delete(false);

List directory contents

Iterate over the contents of a directory using the iterator returned by calling files, or dirs on a DataDirectory object:

// List top level directoriesDataDirectorymyRoot = client.dir("data://.my");
for(DataDirectorydir : myRoot.dirs()) {
System.out.println("Directory " + dir + " at URL " + dir.url());
}
// List files in the 'robots' directoryDataDirectoryrobots = client.dir("data://.my/robots");
for(DataFilefile : robots.files()) {
System.out.println("File " + file + " at URL: " + file.url());
}

Manage directory permissions

Directory permissions may be set when creating a directory, or may be updated on already existing directories.

DataDirectoryfooLimited = client.dir("data://.my/fooLimited");
// Create the directory as privatefooLimited.create(DataAcl.PRIVATE);
// Update a directory to be publicfooLimited.updatePermissions(DataAcl.PUBLIC);
// Check a directory's permissionsif (fooLimited.getPermissions().getReadPermissions() == DataAclType.PRIVATE) {
System.out.println("fooLimited is private");
}

Java Algo development category API's

NameParametersExample
Create AlgorithmString userName - Your Algorithmia user name.
String requestString - JSON payload for the Algorithm you wish to create.
Algorithm newAlgorithm = Algorithmia.client(key).createAlgo(userName, requestString);
Get AlgorithmString userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
Algorithm algorithm = Algorithmia.client(key).getAlgo(userName, algoName);
Compile AlgorithmString userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
Algorithm algorithm = Algorithmia.client(key).compileAlgo(userName, algoName);
Publish AlgorithmString userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
String requestString - JSON payload for the Algorithm you wish to publish.
Algorithm newAlgorithm = Algorithmia.client(key).publishAlgo(userName, algoName, requestString);
List Algorithm VersionsString userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
Boolean callable - Whether to return only public or private algorithm versions.
Integer limit - Items per page.
Boolean published - Whether to return only versions that have been published.
String marker - Marker for pagination.
AlgorithmVersionsList algoList = Algorithmia.client(key).listAlgoVersions(userName, algoName, callable, limit, published, marker)
Update AlgorithmString userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
String requestString - JSON payload for the Algorithm you wish to create.
Algorithm newAlgorithm = Algorithmia.client(key).updateAlgo(userName, algoName, requestString);
Execute AlgorithmString algoName - The name address of the algorithm.Algorithm algo = client.algo("algo://demo/Hello/0.1.1");
AlgoResponse result = algo.pipe("HAL 9000");
Get Algorithm Build LogsString userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
String buildId - The id of the build to retrieve logs.
BuildLogs buildLogs = Algorithmia.client(key).getAlgoBuildLogs(userName, algoName, buildId)
Create DirectoryString path - Path to a data directory.DataDirectory robots = client.dir("data://.my/robots");
robots.create();
List Directory ContentsString path - Path to a data directory.DataDirectory myRoot = client.dir("data://.my");
for(DataDirectory dir : myRoot.dirs()) { System.out.println("Directory " + dir + " at URL " + dir.url()); }
Update DirectoryFile file - A file to put into this data directory.DataDirectory robots = client.dir("data://.my/robots");
robots.putFile(new File("/path/to/Optimus_Prime.png"));
Delete Directoryboolean forceDelete - Forces deletion of the directory if it contains files.client.dir("data://.my/robots").delete(false);
Upload FileFile file - file the file to upload data from.robots.putFile(new File("/path/to/Optimus_Prime.png"));
Verify File Existence-if(file.exists()) { file.delete(); }
Download File-File t800File = robots.file("T-800.png").getFile();
Report InsightsString input - JSON payload key-value pairsAlgorithmiaInsights insightsResponse = Algorithmia.client(defaultKey).reportInsights(input);

Java CICD Automation and Admin Automation category API's

NameParametersExample
List Algorithm BuildsString userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
Integer limit - Items per page.
String marker - Marker for pagination.
AlgorithmBuildsList algoList = Algorithmia.client(defaultKey).listAlgoBuilds(userName, algoName, ?, ?);
Get Algorithm BuildString userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
String buildId - The id of the build to retrieve.
Algorithm.Build returnedBuild = Algorithmia.client(defaultKey).getAlgoBuild(userName, algoName, buildId);
Delete AlgorithmString userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
HttpResponse response = Algorithmia.client(defaultKey).deleteAlgo(userName, algoName);
Get Algorithm SCM statusString userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
AlgorithmSCMStatus scmStatus = Algorithmia.client(defaultKey).getAlgoSCMStatus(userName, algoName);
Get SCMString scmId - The id of scm to retriveAlgorithm.SCM scm = Algorithmia.client(defaultKey).getSCM(scmId);
List Cluster SCM’s-AlgorithmSCMsList algorithmSCMsList = Algorithmia.client(defaultKey).listSCMs();
Query SCM Authorization StatusString scmId - The id of scm status to retrive AlgorithmSCMAuthorizationStatus algorithmSCMAuthorizationStatus = Algorithmia.client(defaultKey).querySCMStatus("github");
Create UserString requestString - JSON payload for the user to be created.User newUser = Algorithmia.client(adminKey, testAddress).createUser(json);
Create OrganizationString requestString - JSON payload for the organization to be created.Organization newOrganization = Algorithmia.client(adminKey, testAddress).createOrganization(json);
Add Organization MemberString orgName - The organization name.
String userName - the users algorithmia user name.
HttpResponse response = Algorithmia.client(adminKey, testAddress).addOrganizationMember(orgName, userName);

About

Java Client for Algorithmia Algorithms and Data API

Resources

Stars

15 stars

Watchers

22 watching

Forks

Releases

Packages

Used by

Contributors

Languages