Giter Club home page Giter Club logo

digitalocean-api-java's Introduction

DigitalOcean API Client for Java

Build Status Version Javadoc License

Simple & Lightweight API client library for Enterprise Application or Utilities Integration around DigitalOcean RESTful APIs. You can use this library with project based (JVM hosted languages) on Java, Groovy, Scala, Clojure, etc.

Give your support by clicking Hearts on DigitalOcean Developers Community.

News

  • v2.17 released and tagged on Feb 03, 2019
  • v2.16 released and tagged on Sep 03, 2018
  • v2.15 released and tagged on May 5, 2018
  • v2.14 released and tagged on Mar 6, 2018
  • v2.13 eleased and tagged on Nov 18, 2017

Getting Started

For handy use, DigitalOcean API Client library project dependency definition provided below or you wanna jar Download it from Maven central repo.

Note: master branch maps to v2 APIs and digitalocean turned off v1 APIs as on Nov 9, 2015 .

Maven dependency

<dependency>
    <groupId>com.myjeeva.digitalocean</groupId>
    <artifactId>digitalocean-api-client</artifactId>
    <version>2.17</version>
</dependency>

Gradle/Grails dependency

compile 'com.myjeeva.digitalocean:digitalocean-api-client:2.17'

Groovy Grape

@Grapes(
@Grab(group='com.myjeeva.digitalocean', module='digitalocean-api-client', version='2.17')
)

Scala SBT

libraryDependencies += "com.myjeeva.digitalocean" % "digitalocean-api-client" % "2.17"

Note:

  • For Android projects, kindly include the httpclient-android library explicitly in your project dependencies.
  • Library vx.x-SNAPSHOT is available between the release version. Snapshot is update to with master branch.

Getting Help

For API documentation see:

For Example usage see:

Samples

Creating a DigitalOcean Client in three simple ways!

// Way one, just pass on authToken
DigitalOcean apiClient = new DigitalOceanClient(authToken);

// Way two, pass on version number & authToken
DigitalOcean apiClient = new DigitalOceanClient("v2", authToken);

// Way three, pass on version number, authToken & httpClient
// Go ahead and customize httpClient attributes for requirements
CloseableHttpClient httpClient = HttpClients.createDefault();
DigitalOcean apiClient = new DigitalOceanClient("v2", authToken, httpClient);

Let's invoke the method(s) as per need via apiClient

// Fetching all the available droplets from control panel
Droplets droplets = apiClient.getAvailableDroplets(pageNo, perPage);

// Fetching all the available kernels for droplet
Kernels kernels = apiClient.getAvailableKernels(dropletId, pageNo, perPage);

// Create a new droplet
Droplet newDroplet = new Droplet();
newDroplet.setName("api-client-test-host");
newDroplet.setSize(new Size("512mb")); // setting size by slug value
newDroplet.setRegion(new Region("sgp1")); // setting region by slug value; sgp1 => Singapore 1 Data center
newDroplet.setImage(new Image(1601)); // setting by Image Id 1601 => centos-5-8-x64 also available in image slug value
newDroplet.setEnableBackup(Boolean.TRUE);
newDroplet.setEnableIpv6(Boolean.TRUE);
newDroplet.setEnablePrivateNetworking(Boolean.TRUE);

// Adding SSH key info
List<Key> keys = new ArrayList<Key>();
keys.add(new Key(6536653));
keys.add(new Key(6536654));
newDroplet.setKeys(keys);

// Adding Metadata API - User Data
newDroplet.setUserData(" < YAML Content > "); // Follow DigitalOcean documentation to prepare user_data value
Droplet droplet = apiClient.createDroplet(newDroplet);


// Creating multiple droplets
Droplet droplet = new Droplet();
droplet.setNames(Arrays.asList("sub-01.example.com", "sub-02.example.com"));
droplet.setSize("512mb");
droplet.setImage(new Image("ubuntu-14-04-x64"));
droplet.setRegion(new Region("nyc1"));
Droplets droplets = apiClient.createDroplets(droplet);

// Fetch droplet information
Droplet droplet = apiClient.getDropletInfo(dropletId);

// Fetch Available Plans/Sizes supported by DigitalOcean
Sizes sizes = apiClient.getAvailableSizes(pageNo);

// Fetch Available Regions supported by DigitalOcean
Regions regions = apiClient.getAvailableRegions(pageNo);

Accessing RateLimit header values from return object. This is applicable for all requests.

Droplets droplets = getAvailableDroplets(1, 20);
RateLimit rateLimit = droplets.getRateLimit();

Actions actions = getAvailableActions(2, 40);
RateLimit rateLimit = actions.getRateLimit();

Domain domain = getDomainInfo("myjeeva.com");
RateLimit rateLimit = domain.getRateLimit();

Droplet droplet = getDropletInfo(10000001);
RateLimit rateLimit = droplet.getRateLimit();

Reporting Issues

DigitalOcean API Client uses GitHub’s integrated issue tracking system to record bugs and feature requests. If you want to raise an issue, please follow the recommendations bellow:

  • Before you log a bug, please search the issue tracker to see if someone has already reported the problem. If the issue doesn’t already exist, create a new issue.
  • Please provide as much information as possible with the issue report, we like to know the version of DigitalOcean API Client that you are using.
  • If you need to paste code, or include a stack trace use Markdown ``` escapes before and after your text.

Supported API's and Changelogs

Refer to CHANGELOG.md

Author

Jeevanandam M. - [email protected]

Contributors

Please refer to https://github.com/jeevatkm/digitalocean-api-java/graphs/contributors

Contributing

  1. Fork it
  2. Create your feature branch - git checkout -b my-new-feature
  3. Implement your changes
  4. Format your code with ./mvnw com.coveo:fmt-maven-plugin:format
  5. Check tests passig with ./mvnw verify
  6. Commit your changes - git commit -am 'Added feature'
  7. Push to the branch - git push origin my-new-feature
  8. Create new Pull Request

License

DigitalOcean API Client - MIT License.

digitalocean-api-java's People

Contributors

andreybleme avatar bahrinka avatar behrica avatar benesch avatar beolnix avatar emanuell avatar hsitter avatar isopov avatar jeevatkm avatar majidalfifi avatar mashurex avatar pulse00 avatar rpardini avatar samuelfac avatar strokine avatar tlehoux avatar tmoreira2020 avatar zacorich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

digitalocean-api-java's Issues

Missing dependency?

I was trying to use the latest version of the library in my Android app, and ran into

java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/impl/client/HttpClients

from Android, I think it's missing a dependency. I got around it by adding HttpComponents to my app's build.gradle file

    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'

Update snapshots

Could you be so kind to update the 1.5-SNAPSHOT on the sonatype mvn repo, so that the latest changes are available?

thanks!

Android app compatiable

Hi, I'm trying to write an Android app with your api, but I just encounter a bug like this, would you please help me to fix it? Below is the detail of the exception,Thanks so much.

java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:300)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:841)
 Caused by: java.lang.NoSuchMethodError: org.apache.http.entity.StringEntity.<init>
        at com.myjeeva.digitalocean.impl.DigitalOceanClient.createRequestData(DigitalOceanClient.java:1021)
        at com.myjeeva.digitalocean.impl.DigitalOceanClient.perform(DigitalOceanClient.java:837)
        at com.myjeeva.digitalocean.impl.DigitalOceanClient.createDroplet(DigitalOceanClient.java:278)
        at space.haiyf.app.grabword.DisplayMessageActivity$createCmd.doInBackground(DisplayMessageActivity.java:137)
        at space.haiyf.app.grabword.DisplayMessageActivity$createCmd.doInBackground(DisplayMessageActivity.java:127)
        at android.os.AsyncTask$2.call(AsyncTask.java:288)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)

            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)

getSlug() method in Image class started to return null values.

Not a big deal but I suppose that something like {"images": [ { "id" : 3123213, "slug" : null }]} didn't happen in json response not so long ago. This is just for everyone to note as in my case I had to debug the json response to understand why library stopped working for me.

Add volume snapshot api support

  • Creating volume snapshot: /v2/volumes/$VOLUME_ID/snapshots
  • Get all volume snapshot by volume Id: /v2/volumes/$VOLUME_ID/snapshots

Gson Unparseable Date Exception

I'm getting the following exception when retrieving/deserializing droplets:

Caused by: java.text.ParseException: Unparseable date: "2014-07-07T03:03:14.000Z"

I believe changing DATE_FORMAT = "yyyy-mm-dd'T'HH:mm:ss'Z'" to "yyyy-mm-dd'T'HH:mm:ss.SSS'Z'" should fix it.

Missing IP Address field

There's no IP Address property in the Droplet class while there should be one since the API returns an 'ip_address' field.

method "takeDropletSnapshot" ignores specified snapshot name

Calling it like this:

digitalOcean.takeDropletSnapshot(924997,"snap-1");

still creates it with a default snapshot name, so it ignores the provided name.
I debugged the code and found the reason in line 225 of DigitalOceanClient.java:

response = process(Action.TAKE_DROPLET_SNAPSHOT, dropletId, qp);

This line calls the "wrong" overloaded "process" method. It calls

process(Action action, Object... id)

instead of

process(Action action, Object[] id,Map<String, String> queryParams)

This results in ignoring all extra query params in "qp"

Consider deleting resource by tag

Hi @jeevatkm ,

Thanks a lot for this digital ocean API client.
The REST API provides the ability to delete by tag. Unfortunately the client does not provide that feature.
Would you consider supporting it ?

Thank you for your work

NullPointerException when deleting droplet in version 2.5

java.lang.NullPointerException
at com.myjeeva.digitalocean.impl.DigitalOceanClient.perform(DigitalOceanClient.java:1088)
at com.myjeeva.digitalocean.impl.DigitalOceanClient.deleteDroplet(DigitalOceanClient.java:326)

This doesn't happen in version 2.4, so the bug is in changesets between 2.4 and 2.5. I dropped there with debugger and it looks like 2.5 assumes different REST response than the one actually received.

Possibility to create volumes within creation of the droplet

I see on the Digital Ocean API that it is possible to specify volumes to be attached at the creation of the droplet. Can that be added? I am trying to add to a Jenkins plugin that uses this wrapper and hit myself on this issue because we cannot fire two events simultaneously, we must wait for the droplet to be created before attaching the volume.

ssh key access for droplets not working

I managed to launch, get status, terminate droplet via Java API v.2. But I couldn't set SSH keys to Droplet for getting access via ssh. I tried all approaches of API: create from open key and fingerprint, get all available keys in account and set to droplet, set id of account ssh keys.

Also I successfully launch droplets with ssh keys via REST API and web interface. And connected to them via Putty. But when I try connect to Droplet started with Java API I got message "private key refused
List keys = new ArrayList()
keys.add(new Key(364008))
        keys.add(new Key(368425))
        keys.add(new Key(452642))

    newDroplet.setKeys(keys)
also i tried
newDroplet.setKeys(apiClient.getAvailableKeys(1).keys)
Via REST API it work right

DigitalOceanClient hangs on retry

I wrote an in-house web application based on Spring Framework, and one of the component is a @Scheduled job that runs periodically to update the droplet statuses.

It hanged after a retry, so I added some debug logs into the code. Normally it would be like this:

11:38:34,341 INFO  [stdout] (myScheduler-3) Got DO client
11:38:35,574 INFO  [stdout] (myScheduler-3) Got droplet info.
11:38:35,575 INFO  [stdout] (myScheduler-3) Got droplet status.
11:38:35,575 INFO  [stdout] (myScheduler-3) Setting droplet status: Active
11:38:35,576 INFO  [stdout] (myScheduler-3) Updating droplet info to database.
11:38:35,576 INFO  [stdout] (myScheduler-3) Updating info for droplet: 8249784

It's a for loop that loops all droplets I've recorded in the local database.

But before it hangs, it would show logs like this:

11:38:35,579 INFO  [stdout] (myScheduler-3) Got DO client
11:42:26,054 INFO  [org.apache.http.impl.execchain.RetryExec] (myScheduler-3) I/O exception (java.net.SocketException) caught when processing request to {s}->https://api.digitalocean.com:443: Connection reset
11:42:26,054 INFO  [org.apache.http.impl.execchain.RetryExec] (myScheduler-3) Retrying request to {s}->https://api.digitalocean.com:443

And nothing else happens.

Since I set the scheduler to fixedDelay = duration, the scheduler won't be executed again unless the last execution is completed. The problem above prevents the scheduler to work properly.

Is there any workaround for this problem?

Support API versioning introduced (v1)

Digital Ocean development team have introduced the Versioning concept into Cloud APIs. Since API v2.0 beta is out for try.

v1 URI will look like below:

https://api.digitalocean.com/v1/droplets/?client_id=[client_id]&api_key=[api_key]¶ms.......

"Item may not be null"

new DigitalOceanClient("v2", token); return error with "Item may not be null".
I've tried with httpClient but nothing...

Make RateLimit values available at all return object level

Make RateLimit header values available in all the return object (Not at nested level).

Droplets droplets = getAvailableDroplets(1);
RateLimit rateLimit = droplets.getRateLimit();
Actions actions = getAvailableActions(2);
RateLimit rateLimit = actions.getRateLimit();
Domain domain = getDomainInfo("myjeeva.com");
RateLimit rateLimit = domain.getRateLimit();
Droplet droplet = getDropletInfo(10000001);
RateLimit rateLimit = droplet.getRateLimit();

getAvailableImages returns Ubuntu 24 x64 images

Running 2.6 version of the plugin, I get two Ubuntu 24 x64 images that different only by ids. Both of the images are not mine, i.e. I don't have them in either Snapshots or Backups.

24 = {Image@9528} "com.myjeeva.digitalocean.pojo.Image@158a57d6[id=17824874,name=24 x64,distribution=Ubuntu,slug=<null>,availablePublic=true,regions=[nyc3],createdDate=Fri Jun 10 00:54:21 EDT 2016,minDiskSize=20,size=29.68,type=snapshot,rateLimit=<null>]"
23 = {Image@9527} "com.myjeeva.digitalocean.pojo.Image@11b8b745[id=17824847,name=24 x64,distribution=Ubuntu,slug=<null>,availablePublic=true,regions=[nyc3],createdDate=Fri Jun 10 00:54:21 EDT 2016,minDiskSize=20,size=29.68,type=snapshot,rateLimit=<null>]"

It would make sense for this to be Fedora 24 x64, be there is already Fedora 24 x64.

com.myjeeva.digitalocean.pojo.Image@4ed7e4cf[id=18027532,name=24 x64,distribution=Fedora,slug=fedora-24-x64,availablePublic=true,regions=[nyc1, sfo1, nyc2, ams2, sgp1, lon1, nyc3, ams3, fra1, tor1, sfo2, blr1],createdDate=Tue Jun 21 18:36:10 EDT 2016,minDiskSize=20,size=3.0,type=snapshot,rateLimit=<null>]

It also doesn't seem like there is any Ubuntu 24 x64 when creating a droplet in Digital Ocean's Web UI...

Not sure what to make out of this Ubuntu 24 x64. Perhaps it is upstream, i.e. Digital Ocean's, issue?

Enhancements to the library

  • Update logger bridge library slf4j-jdk14 ==> slf4j-api
  • Decide and apply appropriate Java code formatter: Google
  • Create date attribute to native data type in Droplet class

Bring DigitalOcean OAUTH API's support

OAuth 2 is an open standard for authorization that enables third-party applications to obtain limited access to DigitalOcean user accounts, by delegating user authentication to DigitalOcean.

Developers must register their application to use OAuth. A registered application is assigned a client ID and client secret. The client secret should be kept confidential, and only used between the application and the DigitalOcean authorization server (https://cloud.digitalocean.com/v1/oauth/).

More Info, click here

Error on apiClient.shutdownDroplet

Exception in thread "main" com.myjeeva.digitalocean.exception.DigitalOceanException:
HTTP Status Code: 403
Error Id: translation missing: en.status_code.forbidden.id
Error Message: You do not have access for the attempted action.
at com.myjeeva.digitalocean.impl.DigitalOceanClient.evaluateResponse(DigitalOceanClient.java:870)
at com.myjeeva.digitalocean.impl.DigitalOceanClient.executeHttpRequest(DigitalOceanClient.java:835)
at com.myjeeva.digitalocean.impl.DigitalOceanClient.doPost(DigitalOceanClient.java:806)
at com.myjeeva.digitalocean.impl.DigitalOceanClient.perform(DigitalOceanClient.java:763)
at com.myjeeva.digitalocean.impl.DigitalOceanClient.shutdownDroplet(DigitalOceanClient.java:311)

Incorrect time zone returned from getActionInfo

For both Image and Droplet actions, getCompletedAt should returns a string of 2014-11-14T16:32:24Z as per DigitalOcean API doc.

But I got from Java output is Thu Mar 31 12:53:19 HKT 2016. The date seems to be converted to my local time format with HKT, but the numbers are still in UTC. It needs to add +08:00 for HKT. The actual local time is Thu Mar 31 20:53:19 HKT 2016.

It seems HKT is added incorrectly. It should be UTC regardless of the local time zone.

The workaround is to replaced HKT with UTC in the date string.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy");
Date myDate = simpleDateFormat.parse(apiClient.getActionInfo(actionID).getCompletedAt().toString().replace("HKT", "UTC"));

System.out.println("Reboot finished at: " + myDate);
System.out.println("Reboot finished at: " + apiClient.getActionInfo(actionID).getCompletedAt());

So the first line of output is correct for HKT.

Reboot finished at: Thu Mar 31 22:39:49 HKT 2016
Reboot finished at: Thu Mar 31 14:39:49 HKT 2016

PS: This affects getCompletedAt for both DropletAction and ImageAction. And I believe the same problem to getStartedAt

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.