diff --git a/.gitignore b/.gitignore
index 86139491..8f1fdc77 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,3 +19,6 @@ target
# Ignore all log files
*.log
+
+#Ignore Test Output
+test-output
\ No newline at end of file
diff --git a/README.md b/README.md
index 406f3ca1..a51128f7 100644
--- a/README.md
+++ b/README.md
@@ -1,114 +1,3 @@
-# docker-java
-
-Java API client for [Docker](http://docs.docker.io/ "Docker")
-
-Supports a subset of the Docker Client API v1.8, Docker Server version 0.7.6
-
-## Build with Maven
-
-###### Prerequisites:
-
-* Java 1.6+
-* Maven 3.0.5
-* Docker daemon running
-
-Maven will run tests during build process. Tests are using localhost instance of Docker, make sure that
-you have Docker running for tests to work or just turn off tests.
-
-If you don't have Docker running locally, you can skip tests with -DskipTests flag set to true:
-
- $ mvn clean install -DskipTests=true
-
-
-By default Docker server is using UNIX sockets for communication with the Docker client, however docker-java
-client uses TCP/IP to connect to the Docker server, so you will need to make sure that your Docker server is
-listening on TCP port. To allow Docker server to use TCP add the following line to /etc/default/docker
-
- DOCKER_OPTS="-H tcp://127.0.0.1:4243 -H unix:///var/run/docker.sock"
-
-More details setting up docket server can be found in official documentation: http://docs.docker.io/en/latest/use/basics/
-
-Now make sure that docker is up:
-
- $ docker -H tcp://127.0.0.1:4243 version
-
- Client version: 0.7.6
- Go version (client): go1.2
- Git commit (client): bc3b2ec
- Server version: 0.7.6
- Git commit (server): bc3b2ec
- Go version (server): go1.2
- Last stable version: 0.7.6
-
-Run build with tests:
-
- $ mvn clean install
-
-## Docker-Java maven dependency:
-
-
- com.kpelykh
- docker-java
- 0.7.6-SNAPSHOT
-
-
-
-## Example code snippets:
-
- DockerClient dockerClient = new DockerClient("http://localhost:4243");
-
-###### Get Docker info:
-
- Info info = dockerClient.info();
- System.out.print(info);
-
-###### Search Docker repository:
-
- List dockerSearch = dockerClient.search("busybox");
- System.out.println("Search returned" + dockerSearch.toString());
-
-###### Create new Docker container, wait for its start and stop it:
-
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[] {"touch", "/test"});
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
-
- dockerClient.startContainer(container.id);
-
- dockerClient.waitContainer(container.id);
-
- dockerClient.stopContainer(container.id);
-
-
-##### Support for UNIX sockets:
-
- Support for UNIX socket should appear in docker-java pretty soon. I'm working on its integration.
-
-##### Docker Builder:
-
-To use Docker Builder, as described on page http://docs.docker.io/en/latest/use/builder/,
-user dockerClient.build(baseDir), where baseDir is a path to folder containing Dockerfile.
-
-
- File baseDir = new File("~/kpelykh/docker/netcat");
-
- ClientResponse response = dockerClient.build(baseDir);
-
- StringWriter logwriter = new StringWriter();
-
- try {
- LineIterator itr = IOUtils.lineIterator(response.getEntityInputStream(), "UTF-8");
- while (itr.hasNext()) {
- String line = itr.next();
- logwriter.write(line);
- LOG.info(line);
- }
- } finally {
- IOUtils.closeQuietly(response.getEntityInputStream());
- }
-
-
-
-For additional examples, please look at [DockerClientTest.java](https://github.com/kpelykh/docker-java/blob/master/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java "DockerClientTest.java")
+This project has moved to https://github.com/docker-java/docker-java
+--------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index be72410e..3de239d1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -11,7 +11,7 @@
com.kpelykh
docker-java
jar
- 0.7.6-SNAPSHOT
+ 0.8.2-SNAPSHOT
docker-java
https://github.com/kpelykh/docker-java
@@ -27,9 +27,9 @@
scm:git:git@github.com:kpelykh/docker-java.git
- scm:git:git@github.com:kpelykh/docker-java.git
+ git@github.com:kpelykh/docker-java.git
scm:git:git@github.com:kpelykh/docker-java.git
-
+
@@ -40,6 +40,8 @@
+ true
+
UTF-8
true
false
@@ -51,6 +53,8 @@
1.18
1.9
+ 2.3.3
+
4.2.5
1.5
2.3
@@ -77,20 +81,21 @@
- com.sun.jersey
- jersey-core
- ${jersey.version}
+ com.fasterxml.jackson.jaxrs
+ jackson-jaxrs-json-provider
+ ${jackson-jaxrs.version}
com.sun.jersey
- jersey-client
+ jersey-core
${jersey.version}
com.sun.jersey
- jersey-json
+ jersey-client
${jersey.version}
+
com.sun.jersey.contribs
jersey-multipart
@@ -136,6 +141,12 @@
${slf4j-api.version}
+
+ org.slf4j
+ jul-to-slf4j
+ ${slf4j-api.version}
+
+
ch.qos.logback
@@ -185,93 +196,110 @@
test
+
+
+
+ com.github.jnr
+ jffi
+ 1.2.7
+
+
+ com.github.jnr
+ jffi
+ native
+ 1.2.7
+
+
+
-
-
-
-
- org.apache.maven.plugins
- maven-release-plugin
- ${maven-release-plugin.version}
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- ${jdk.source}
- ${jdk.target}
- ISO-8859-1
- ${jdk.debug}
- ${jdk.optimize}
-
-
-
-
- org.apache.maven.plugins
- maven-jar-plugin
- ${maven-jar-plugin.version}
-
-
-
- test-jar
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
-
-
- org.codehaus.mojo
- cobertura-maven-plugin
- ${cobertura-maven-plugin.version}
-
-
-
- org.apache.maven.plugins
- maven-antrun-plugin
- ${maven-antrun-plugin.version}
-
-
- validate
-
- run
-
-
-
- *******************************************************************
- *******************************************************************
- [project.name] : ${project.name}
- [project.basedir] : ${project.basedir}
- [project.version] : ${project.version}
- [project.artifactId] ${project.artifactId}
- [project.build.directory] ${project.build.directory}
- [jdk.source] : ${jdk.source}
- [jdk.target] : ${jdk.target}
- [jdk.debug] : ${jdk.debug}
- [jdk.optimize] : ${jdk.optimize}
- [source encoding]: ${project.build.sourceEncoding}
- [M2_HOME] : ${env.M2_HOME}
- [LocalRepository] : ${settings.localRepository}
- *******************************************************************
- *******************************************************************
-
-
-
-
-
-
-
-
+
+
+
+
+ org.apache.maven.plugins
+ maven-release-plugin
+ ${maven-release-plugin.version}
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${jdk.source}
+ ${jdk.target}
+ ISO-8859-1
+ ${jdk.debug}
+ ${jdk.optimize}
+
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+ ${maven-jar-plugin.version}
+
+
+
+ test-jar
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+ ${skipTests}
+
+
+
+
+
+ org.codehaus.mojo
+ cobertura-maven-plugin
+ ${cobertura-maven-plugin.version}
+
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+ ${maven-antrun-plugin.version}
+
+
+ validate
+
+ run
+
+
+
+ *******************************************************************
+ *******************************************************************
+ [project.name] : ${project.name}
+ [project.basedir] : ${project.basedir}
+ [project.version] : ${project.version}
+ [project.artifactId] ${project.artifactId}
+ [project.build.directory] ${project.build.directory}
+ [jdk.source] : ${jdk.source}
+ [jdk.target] : ${jdk.target}
+ [jdk.debug] : ${jdk.debug}
+ [jdk.optimize] : ${jdk.optimize}
+ [source encoding]: ${project.build.sourceEncoding}
+ [LocalRepository] : ${settings.localRepository}
+ *******************************************************************
+ *******************************************************************
+
+
+
+
+
+
+
+
diff --git a/src/main/java/com/kpelykh/docker/client/Config.java b/src/main/java/com/kpelykh/docker/client/Config.java
new file mode 100644
index 00000000..f6e59d76
--- /dev/null
+++ b/src/main/java/com/kpelykh/docker/client/Config.java
@@ -0,0 +1,57 @@
+package com.kpelykh.docker.client;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.URI;
+import java.util.Properties;
+
+class Config {
+ URI url;
+ String version, username, password, email;
+
+ private Config() {
+ }
+
+ static Config createConfig() throws DockerException {
+ final Properties p = new Properties();
+
+ try {
+ p.load(Config.class.getResourceAsStream("/docker.io.properties"));
+ } catch (IOException e) {
+ throw new DockerException(e);
+ }
+
+ final File file = new File(System.getProperty("user.home"), ".docker.io.properties");
+
+ if (file.isFile()) {
+ try {
+ final FileInputStream in = new FileInputStream(file);
+ try {
+ p.load(in);
+ } finally {
+ in.close();
+ }
+ } catch (IOException e) {
+ throw new DockerException(e);
+ }
+ }
+
+ for (String s : new String[]{"url", "version", "username", "password", "email"}) {
+ final String key = "docker.io." + s;
+ if (System.getProperties().keySet().contains(key)) {
+ p.setProperty(key, System.getProperty(key));
+ }
+ }
+
+ final Config c = new Config();
+
+ c.url = URI.create(p.getProperty("docker.io.url"));
+ c.version = p.getProperty("docker.io.version");
+ c.username = p.getProperty("docker.io.username");
+ c.password = p.getProperty("docker.io.password");
+ c.email = p.getProperty("docker.io.email");
+
+ return c;
+ }
+}
diff --git a/src/main/java/com/kpelykh/docker/client/DockerClient.java b/src/main/java/com/kpelykh/docker/client/DockerClient.java
index 4981893f..101d7209 100644
--- a/src/main/java/com/kpelykh/docker/client/DockerClient.java
+++ b/src/main/java/com/kpelykh/docker/client/DockerClient.java
@@ -1,5 +1,7 @@
package com.kpelykh.docker.client;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Preconditions;
import com.kpelykh.docker.client.model.*;
import com.kpelykh.docker.client.utils.CompressArchiveUtil;
@@ -9,691 +11,944 @@
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;
-import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
import com.sun.jersey.client.apache4.ApacheHttpClient4Handler;
import com.sun.jersey.core.util.MultivaluedMapImpl;
+
+import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.LineIterator;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
+import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
-import org.codehaus.jettison.json.JSONException;
-import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
+
import java.io.File;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
+import static org.apache.commons.io.IOUtils.closeQuietly;
+
/**
- *
* @author Konstantin Pelykh (kpelykh@gmail.com)
- *
*/
-public class DockerClient
-{
+public class DockerClient {
- private static final Logger LOGGER = LoggerFactory.getLogger(DockerClient.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(DockerClient.class);
- private static DockerClient instance;
private Client client;
- private String restEndpointUrl;
-
- public DockerClient(String serverUrl) {
- restEndpointUrl = serverUrl + "/v1.8";
- ClientConfig clientConfig = new DefaultClientConfig();
- clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
-
- SchemeRegistry schemeRegistry = new SchemeRegistry();
- schemeRegistry.register(new Scheme("http", 4243, PlainSocketFactory.getSocketFactory()));
-
- PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
- // Increase max total connection
- cm.setMaxTotal(1000);
- // Increase default max connection per route
- cm.setDefaultMaxPerRoute(1000);
-
- HttpClient httpClient = new DefaultHttpClient(cm);
- client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, null, false), clientConfig);
-
- //Experimental support for unix sockets:
- //client = new UnixSocketClient(clientConfig);
-
- client.addFilter(new JsonClientFilter());
- client.addFilter(new LoggingFilter());
- }
-
- /**
- ** MISC API
- **
- **/
-
- public Info info() throws DockerException {
- WebResource webResource = client.resource(restEndpointUrl + "/info");
-
- try {
- LOGGER.trace("GET: {}", webResource);
- return webResource.accept(MediaType.APPLICATION_JSON).get(Info.class);
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error.", exception);
- } else {
- throw new DockerException(exception);
- }
- }
- }
-
-
- public Version version() throws DockerException {
- WebResource webResource = client.resource(restEndpointUrl + "/version");
-
- try {
- LOGGER.trace("GET: {}", webResource);
- return webResource.accept(MediaType.APPLICATION_JSON).get(Version.class);
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error.", exception);
- } else {
- throw new DockerException(exception);
- }
- }
+ private String restEndpointUrl;
+ private AuthConfig authConfig;
+
+ public DockerClient() throws DockerException {
+ this(Config.createConfig());
+ }
+
+ public DockerClient(String serverUrl) throws DockerException {
+ this(configWithServerUrl(serverUrl));
+ }
+
+ private static Config configWithServerUrl(String serverUrl) throws DockerException {
+ final Config c = Config.createConfig();
+ c.url = URI.create(serverUrl);
+ return c;
+ }
+
+ private DockerClient(Config config) {
+ restEndpointUrl = config.url + "/v" + config.version;
+ ClientConfig clientConfig = new DefaultClientConfig();
+ //clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
+
+ SchemeRegistry schemeRegistry = new SchemeRegistry();
+ schemeRegistry.register(new Scheme("http", config.url.getPort(), PlainSocketFactory.getSocketFactory()));
+ schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
+
+ PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
+ // Increase max total connection
+ cm.setMaxTotal(1000);
+ // Increase default max connection per route
+ cm.setDefaultMaxPerRoute(1000);
+
+ HttpClient httpClient = new DefaultHttpClient(cm);
+ client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, null, false), clientConfig);
+
+ client.setReadTimeout(10000);
+ //Experimental support for unix sockets:
+ //client = new UnixSocketClient(clientConfig);
+
+ client.addFilter(new JsonClientFilter());
+ client.addFilter(new LoggingFilter());
+ }
+
+ public void setCredentials(String username, String password, String email) {
+ if (username == null) {
+ throw new IllegalArgumentException("username is null");
+ }
+ if (password == null) {
+ throw new IllegalArgumentException("password is null");
+ }
+ if (email == null) {
+ throw new IllegalArgumentException("email is null");
+ }
+ authConfig = new AuthConfig();
+ authConfig.setUsername(username);
+ authConfig.setPassword(password);
+ authConfig.setEmail(email);
+ }
+
+ /**
+ * Authenticate with the server, useful for checking authentication.
+ */
+ public void auth() throws DockerException {
+ try {
+ client.resource(restEndpointUrl + "/auth")
+ .header("Content-Type", MediaType.APPLICATION_JSON)
+ .accept(MediaType.APPLICATION_JSON)
+ .post(authConfig());
+ } catch (UniformInterfaceException e) {
+ throw new DockerException(e);
+ }
+ }
+
+ private String registryAuth() throws DockerException {
+ try {
+ return Base64.encodeBase64String(new ObjectMapper().writeValueAsString(authConfig()).getBytes());
+ } catch (IOException e) {
+ throw new DockerException(e);
+ }
+ }
+
+ public AuthConfig authConfig() throws DockerException {
+ return authConfig != null
+ ? authConfig
+ : authConfigFromProperties();
+ }
+
+ private static AuthConfig authConfigFromProperties() throws DockerException {
+ final AuthConfig a = new AuthConfig();
+
+ a.setUsername(Config.createConfig().username);
+ a.setPassword(Config.createConfig().password);
+ a.setEmail(Config.createConfig().email);
+
+ if (a.getUsername() == null) {throw new IllegalStateException("username is null");}
+ if (a.getPassword() == null) {throw new IllegalStateException("password is null");}
+ if (a.getEmail() == null) {throw new IllegalStateException("email is null");}
+
+ return a;
}
/**
- ** IMAGE API
- **
- **/
-
- public ClientResponse pull(String repository) throws DockerException {
- return this.pull(repository, null, null);
- }
-
- public ClientResponse pull(String repository, String tag) throws DockerException {
- return this.pull(repository, tag, null);
- }
-
- public ClientResponse pull(String repository, String tag, String registry) throws DockerException {
- Preconditions.checkNotNull(repository, "Repository was not specified");
-
- if (StringUtils.countMatches(repository, ":") == 1) {
- String repositoryTag[] = StringUtils.split(repository);
- repository = repositoryTag[0];
- tag = repositoryTag[1];
-
- }
-
- MultivaluedMap params = new MultivaluedMapImpl();
- params.add("tag", tag);
- params.add("fromImage", repository);
- params.add("registry", registry);
-
- WebResource webResource = client.resource(restEndpointUrl + "/images/create").queryParams(params);
-
- try {
- LOGGER.trace("POST: {}", webResource);
- return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ClientResponse.class);
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error.", exception);
- } else {
- throw new DockerException(exception);
- }
- }
- }
-
- public List search(String search) throws DockerException {
- WebResource webResource = client.resource(restEndpointUrl + "/images/search").queryParam("term", search);
- try {
- return webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() {});
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error.", exception);
- } else {
- throw new DockerException(exception);
- }
- }
-
- }
-
- public void removeImage(String imageId) throws DockerException {
- Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty");
-
- try {
- WebResource webResource = client.resource(restEndpointUrl + "/images/" + imageId);
- LOGGER.trace("DELETE: {}", webResource);
- webResource.delete();
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 204) {
- //no error
- LOGGER.trace("Successfully removed image " + imageId);
- } else if (exception.getResponse().getStatus() == 404) {
- LOGGER.warn("{} no such image", imageId);
- } else if (exception.getResponse().getStatus() == 409) {
- throw new DockerException("Conflict");
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error.", exception);
- } else {
- throw new DockerException(exception);
- }
- }
-
- }
-
- public void removeImages(List images) throws DockerException {
- Preconditions.checkNotNull(images, "List of images can't be null");
-
- for (String imageId : images) {
- removeImage(imageId);
- }
- }
-
- public String getVizImages() throws DockerException {
- WebResource webResource = client.resource(restEndpointUrl + "/images/viz");
-
- try {
- LOGGER.trace("GET: {}", webResource);
- String response = webResource.get(String.class);
- LOGGER.trace("Response: {}", response);
-
- return response;
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 400) {
- throw new DockerException("bad parameter");
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- }
- }
-
-
- public List getImages() throws DockerException {
- return this.getImages(null, false);
- }
-
- public List getImages(boolean allContainers) throws DockerException {
- return this.getImages(null, allContainers);
- }
-
- public List getImages(String name) throws DockerException {
- return this.getImages(name, false);
- }
-
- public List getImages(String name, boolean allImages) throws DockerException {
-
- MultivaluedMap params = new MultivaluedMapImpl();
- params.add("filter", name);
- params.add("all", allImages ? "1" : "0");
-
- WebResource webResource = client.resource(restEndpointUrl + "/images/json").queryParams(params);
-
- try {
- LOGGER.trace("GET: {}", webResource);
- List images = webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() {});
- LOGGER.trace("Response: {}", images);
- return images;
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 400) {
- throw new DockerException("bad parameter");
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException();
- }
- }
-
- }
-
- public ImageInspectResponse inspectImage(String imageId) throws DockerException {
-
- WebResource webResource = client.resource(restEndpointUrl + String.format("/images/%s/json", imageId));
-
- try {
- LOGGER.trace("GET: {}", webResource);
- return webResource.accept(MediaType.APPLICATION_JSON).get(ImageInspectResponse.class);
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 404) {
- throw new DockerException(String.format("No such image %s", imageId));
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- }
- }
-
- /**
- ** CONTAINER API
- **
- **/
-
- public List listContainers(boolean allContainers) {
- return this.listContainers(allContainers, false, -1, false, null, null);
- }
-
- public List listContainers(boolean allContainers, boolean latest) {
- return this.listContainers(allContainers, latest, -1, false, null, null);
- }
-
- public List listContainers(boolean allContainers, boolean latest, int limit) {
- return this.listContainers(allContainers, latest, limit, false, null, null);
- }
-
- public List listContainers(boolean allContainers, boolean latest, int limit, boolean showSize) {
- return this.listContainers(allContainers, latest, limit, showSize, null, null);
- }
-
- public List listContainers(boolean allContainers, boolean latest, int limit, boolean showSize, String since) {
- return this.listContainers(allContainers, latest, limit, false, since, null);
- }
-
- public List listContainers(boolean allContainers, boolean latest, int limit, boolean showSize, String since, String before) {
-
- MultivaluedMap params = new MultivaluedMapImpl();
- params.add("limit", latest ? "1" : String.valueOf(limit));
- params.add("all", allContainers ? "1" : "0");
- params.add("since", since);
- params.add("before", before);
- params.add("size", showSize ? "1" : "0");
-
- WebResource webResource = client.resource(restEndpointUrl + "/containers/json").queryParams(params);
- LOGGER.trace("GET: {}", webResource);
- List containers = webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() {});
- LOGGER.trace("Response: {}", containers);
-
- return containers;
- }
-
- public ContainerCreateResponse createContainer(ContainerConfig config) throws DockerException{
- return createContainer(config, null);
- }
-
- public ContainerCreateResponse createContainer(ContainerConfig config,String name) throws DockerException {
-
- MultivaluedMap params = new MultivaluedMapImpl();
- if(name != null){
- params.add("name", name);
- }
- WebResource webResource = client.resource(restEndpointUrl + "/containers/create").queryParams(params);
-
- try {
- LOGGER.trace("POST: {} ", webResource);
- return webResource.accept(MediaType.APPLICATION_JSON)
- .type(MediaType.APPLICATION_JSON)
- .post(ContainerCreateResponse.class, config);
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 404) {
- throw new DockerException(String.format("%s is an unrecognized image. Please pull the image first.", config.getImage()));
- } else if (exception.getResponse().getStatus() == 406) {
- throw new DockerException("impossible to attach (container not running)");
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- }
-
- }
-
- public void startContainer(String containerId) throws DockerException {
- this.startContainer(containerId, null);
- }
-
- public void startContainer(String containerId, HostConfig hostConfig) throws DockerException {
-
- WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/start", containerId));
-
- try {
- LOGGER.trace("POST: {}", webResource);
- Builder builder = webResource.accept(MediaType.TEXT_PLAIN);
- if (hostConfig != null) {
- builder.type(MediaType.APPLICATION_JSON).post(hostConfig);
- } else {
- builder.post((HostConfig) null);
- }
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 404) {
- throw new DockerException(String.format("No such container %s", containerId));
- } else if (exception.getResponse().getStatus() == 204) {
- //no error
- LOGGER.trace("Successfully started container {}", containerId);
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- }
- }
-
- public ContainerInspectResponse inspectContainer(String containerId) throws DockerException {
-
- WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/json", containerId));
-
- try {
- LOGGER.trace("GET: {}", webResource);
- return webResource.accept(MediaType.APPLICATION_JSON).get(ContainerInspectResponse.class);
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 404) {
- throw new DockerException(String.format("No such container %s", containerId));
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- }
- }
-
-
- public void removeContainer(String container) throws DockerException {
- this.removeContainer(container, false);
- }
-
- public void removeContainer(String containerId, boolean removeVolumes) throws DockerException {
- Preconditions.checkState(!StringUtils.isEmpty(containerId), "Container ID can't be empty");
-
- WebResource webResource = client.resource(restEndpointUrl + "/containers/" + containerId).queryParam("v", removeVolumes ? "1" : "0");
-
- try {
- LOGGER.trace("DELETE: {}", webResource);
- String response = webResource.accept(MediaType.APPLICATION_JSON).delete(String.class);
- LOGGER.trace("Response: {}", response);
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 204) {
- //no error
- LOGGER.trace("Successfully removed container " + containerId);
- } else if (exception.getResponse().getStatus() == 400) {
- throw new DockerException("bad parameter");
- } else if (exception.getResponse().getStatus() == 404) {
- LOGGER.warn(String.format("%s is an unrecognized container.", containerId));
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- }
- }
-
-
- public void removeContainers(List containers, boolean removeVolumes) throws DockerException {
- Preconditions.checkNotNull(containers, "List of containers can't be null");
-
- for (String containerId : containers) {
- removeContainer(containerId, removeVolumes);
- }
- }
-
- public int waitContainer(String containerId) throws DockerException {
- WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/wait", containerId));
-
- try {
- LOGGER.trace("POST: {}", webResource);
- JSONObject jsonObject = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(JSONObject.class);
- return jsonObject.getInt("StatusCode");
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 404) {
- throw new DockerException(String.format("No such container %s", containerId));
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- } catch (JSONException e) {
- throw new DockerException(e);
- }
- }
-
-
- public ClientResponse logContainer(String containerId) throws DockerException {
- return logContainer(containerId, false);
- }
-
- public ClientResponse logContainerStream(String containerId) throws DockerException {
- return logContainer(containerId, true);
- }
-
- private ClientResponse logContainer(String containerId, boolean stream) throws DockerException {
- MultivaluedMap params = new MultivaluedMapImpl();
- params.add("logs", "1");
- params.add("stdout", "1");
- params.add("stderr", "1");
- if (stream) {
- params.add("stream", "1"); // this parameter keeps stream open indefinitely
- }
-
- WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/attach", containerId))
- .queryParams(params);
-
- try {
- LOGGER.trace("POST: {}", webResource);
- return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ClientResponse.class, params);
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 400) {
- throw new DockerException("bad parameter");
- } else if (exception.getResponse().getStatus() == 404) {
- throw new DockerException(String.format("No such container %s", containerId));
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- }
- }
-
- public List containterDiff(String containerId) throws DockerException {
-
- WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/changes", containerId));
-
- try {
- LOGGER.trace("GET: {}", webResource);
- return webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() {});
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 404) {
- throw new DockerException(String.format("No such container %s", containerId));
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- }
- }
-
-
-
-
- public void stopContainer(String containerId) throws DockerException {
- this.stopContainer(containerId, 10);
- }
-
- public void stopContainer(String containerId, int timeout) throws DockerException {
-
- WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/stop", containerId))
- .queryParam("t", String.valueOf(timeout));
-
-
- try {
- LOGGER.trace("POST: {}", webResource);
- webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post();
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 404) {
- LOGGER.warn("No such container {}", containerId);
- } else if (exception.getResponse().getStatus() == 204) {
- //no error
- LOGGER.trace("Successfully stopped container {}", containerId);
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- }
- }
-
- public void kill(String containerId) throws DockerException {
- WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/kill", containerId));
-
- try {
- LOGGER.trace("POST: {}", webResource);
- webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post();
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 404) {
- LOGGER.warn("No such container {}", containerId);
- } else if (exception.getResponse().getStatus() == 204) {
- //no error
- LOGGER.trace("Successfully killed container {}", containerId);
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- }
- }
-
- public void restart(String containerId, int timeout) throws DockerException {
- WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/restart", containerId));
-
- try {
- LOGGER.trace("POST: {}", webResource);
- webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post();
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 404) {
- throw new DockerException(String.format("No such container %s", containerId));
- } else if (exception.getResponse().getStatus() == 204) {
- //no error
- LOGGER.trace("Successfully restarted container {}", containerId);
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- }
- }
-
- public String commit(CommitConfig commitConfig) throws DockerException {
- Preconditions.checkNotNull(commitConfig.getContainer(), "Container ID was not specified");
-
- MultivaluedMap params = new MultivaluedMapImpl();
- params.add("container", commitConfig.getContainer());
- params.add("repo", commitConfig.getRepo());
- params.add("tag", commitConfig.getTag());
- params.add("m", commitConfig.getMessage());
- params.add("author", commitConfig.getAuthor());
- params.add("run", commitConfig.getRun());
-
- WebResource webResource = client.resource(restEndpointUrl + "/commit").queryParams(params);
-
- try {
- LOGGER.trace("POST: {}", webResource);
- JSONObject jsonObject = webResource.accept("application/vnd.docker.raw-stream").post(JSONObject.class, params);
- return jsonObject.getString("Id");
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 404) {
- throw new DockerException(String.format("No such container %s", commitConfig.getContainer()));
- } else if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- } catch (JSONException e) {
- throw new DockerException(e);
- }
- }
-
-
- public ClientResponse build(File dockerFolder) throws DockerException {
- return this.build(dockerFolder, null);
- }
-
- public ClientResponse build(File dockerFolder, String tag) throws DockerException {
- Preconditions.checkNotNull(dockerFolder, "Folder is null");
- Preconditions.checkArgument(dockerFolder.exists(), "Folder %s doesn't exist", dockerFolder);
- Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(), "Dockerfile doesn't exist in " + dockerFolder);
-
- //We need to use Jersey HttpClient here, since ApacheHttpClient4 will not add boundary filed to
- //Content-Type: multipart/form-data; boundary=Boundary_1_372491238_1372806136625
-
- MultivaluedMap params = new MultivaluedMapImpl();
- params.add("t", tag);
-
- // ARCHIVE TAR
- String archiveNameWithOutExtension = UUID.randomUUID().toString();
-
- File dockerFolderTar = null;
- File tmpDockerContextFolder = null;
-
- try {
- File dockerFile = new File(dockerFolder, "Dockerfile");
- List dockerFileContent = FileUtils.readLines(dockerFile);
-
- if (dockerFileContent.size() <= 0) {
- throw new DockerException(String.format("Dockerfile %s is empty", dockerFile));
- }
-
- //Create tmp docker context folder
- tmpDockerContextFolder = new File(FileUtils.getTempDirectoryPath(), "docker-java-build" + archiveNameWithOutExtension);
-
- FileUtils.copyFileToDirectory(dockerFile, tmpDockerContextFolder);
-
- for (String cmd : dockerFileContent) {
- if (StringUtils.startsWithIgnoreCase(cmd.trim(), "ADD ")) {
- String addArgs[] = StringUtils.split(cmd, " \t");
- if (addArgs.length != 3) {
- throw new DockerException(String.format("Wrong format on line [%s]", cmd));
- }
-
- File src = new File(addArgs[1]);
- if (!src.isAbsolute()) {
- src = new File(dockerFolder, addArgs[1]).getCanonicalFile();
- }
-
- if (!src.exists()) {
- throw new DockerException(String.format("Source file %s doesnt' exist", src));
- }
- if (src.isDirectory()) {
- FileUtils.copyDirectory(src, tmpDockerContextFolder);
- } else {
- FileUtils.copyFileToDirectory(src, tmpDockerContextFolder);
- }
- }
- }
-
- dockerFolderTar = CompressArchiveUtil.archiveTARFiles(tmpDockerContextFolder, archiveNameWithOutExtension);
-
- } catch (IOException ex) {
- FileUtils.deleteQuietly(dockerFolderTar);
- FileUtils.deleteQuietly(tmpDockerContextFolder);
- throw new DockerException("Error occurred while preparing Docker context folder.", ex);
- }
-
- WebResource webResource = client.resource(restEndpointUrl + "/build").queryParams(params);
-
- try {
- LOGGER.trace("POST: {}", webResource);
- return webResource
- .type("application/tar")
- .accept(MediaType.TEXT_PLAIN)
- .post(ClientResponse.class, FileUtils.openInputStream(dockerFolderTar));
- } catch (UniformInterfaceException exception) {
- if (exception.getResponse().getStatus() == 500) {
- throw new DockerException("Server error", exception);
- } else {
- throw new DockerException(exception);
- }
- } catch (IOException e) {
- throw new DockerException(e);
- } finally {
- FileUtils.deleteQuietly(dockerFolderTar);
- FileUtils.deleteQuietly(tmpDockerContextFolder);
- }
-
- }
-
+ * * MISC API
+ * *
+ */
+
+ public Info info() throws DockerException {
+ WebResource webResource = client.resource(restEndpointUrl + "/info");
+
+ try {
+ LOGGER.trace("GET: {}", webResource);
+ return webResource.accept(MediaType.APPLICATION_JSON).get(Info.class);
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error.", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+
+ public Version version() throws DockerException {
+ WebResource webResource = client.resource(restEndpointUrl + "/version");
+
+ try {
+ LOGGER.trace("GET: {}", webResource);
+ return webResource.accept(MediaType.APPLICATION_JSON).get(Version.class);
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error.", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+
+ public int ping() throws DockerException {
+ WebResource webResource = client.resource(restEndpointUrl + "/_ping");
+
+ try {
+ LOGGER.trace("GET: {}", webResource);
+ ClientResponse resp = webResource.get(ClientResponse.class);
+ return resp.getStatus();
+ } catch (UniformInterfaceException exception) {
+ throw new DockerException(exception);
+ }
+ }
+
+
+ /**
+ * * IMAGE API
+ * *
+ */
+
+ public ClientResponse pull(String repository) throws DockerException {
+ return this.pull(repository, null, null);
+ }
+
+ public ClientResponse pull(String repository, String tag) throws DockerException {
+ return this.pull(repository, tag, null);
+ }
+
+ public ClientResponse pull(String repository, String tag, String registry) throws DockerException {
+ Preconditions.checkNotNull(repository, "Repository was not specified");
+
+ if (StringUtils.countMatches(repository, ":") == 1) {
+ String repositoryTag[] = StringUtils.split(repository, ':');
+ repository = repositoryTag[0];
+ tag = repositoryTag[1];
+
+ }
+
+ MultivaluedMap params = new MultivaluedMapImpl();
+ params.add("tag", tag);
+ params.add("fromImage", repository);
+ params.add("registry", registry);
+
+ WebResource webResource = client.resource(restEndpointUrl + "/images/create").queryParams(params);
+
+ try {
+ LOGGER.trace("POST: {}", webResource);
+ return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ClientResponse.class);
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error.", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+
+
+
+ /**
+ * @return The output slurped into a string.
+ */
+ public static String asString(ClientResponse response) throws IOException {
+
+ StringWriter out = new StringWriter();
+ try {
+ LineIterator itr = IOUtils.lineIterator(
+ response.getEntityInputStream(), "UTF-8");
+ while (itr.hasNext()) {
+ String line = itr.next();
+ out.write(line + (itr.hasNext() ? "\n" : ""));
+ }
+ } finally {
+ closeQuietly(response.getEntityInputStream());
+ }
+ return out.toString();
+ }
+
+ /**
+ * Push the latest image to the repository.
+ *
+ * @param name The name, e.g. "alexec/busybox" or just "busybox" if you want to default. Not null.
+ */
+ public ClientResponse push(final String name) throws DockerException {
+ if (name == null) {
+ throw new IllegalArgumentException("name is null");
+ }
+ try {
+ final String registryAuth = registryAuth();
+ return client.resource(restEndpointUrl + "/images/" + name(name) + "/push")
+ .header("X-Registry-Auth", registryAuth)
+ .accept(MediaType.APPLICATION_JSON)
+ .post(ClientResponse.class);
+ } catch (UniformInterfaceException e) {
+ throw new DockerException(e);
+ }
+ }
+
+ private String name(String name) {
+ return name.contains("/") ? name : authConfig.getUsername();
+ }
+
+ /**
+ * Tag an image into a repository
+ *
+ * @param image the local image to tag (either a name or an id)
+ * @param repository the repository to tag in
+ * @param tag any tag for this image
+ * @param force (not documented)
+ * @return the HTTP status code (201 for success)
+ */
+ public int tag(String image, String repository, String tag, boolean force) throws DockerException {
+ Preconditions.checkNotNull(image, "image was not specified");
+ Preconditions.checkNotNull(repository, "repository was not specified");
+ Preconditions.checkNotNull(tag, " tag was not provided");
+
+ MultivaluedMap params = new MultivaluedMapImpl();
+ params.add("repo", repository);
+ params.add("tag", tag);
+ params.add("force", String.valueOf(force));
+
+ WebResource webResource = client.resource(restEndpointUrl + "/images/" + image + "/tag").queryParams(params);
+
+ try {
+ LOGGER.trace("POST: {}", webResource);
+ ClientResponse resp = webResource.post(ClientResponse.class);
+ return resp.getStatus();
+ } catch (UniformInterfaceException exception) {
+ throw new DockerException(exception);
+ }
+ }
+
+ /**
+ * Create an image by importing the given stream of a tar file.
+ *
+ * @param repository the repository to import to
+ * @param tag any tag for this image
+ * @param imageStream the InputStream of the tar file
+ * @return an {@link ImageCreateResponse} containing the id of the imported image
+ * @throws DockerException if the import fails for some reason.
+ */
+ public ImageCreateResponse importImage(String repository, String tag, InputStream imageStream) throws DockerException {
+ Preconditions.checkNotNull(repository, "Repository was not specified");
+ Preconditions.checkNotNull(imageStream, "imageStream was not provided");
+
+ MultivaluedMap params = new MultivaluedMapImpl();
+ params.add("repo", repository);
+ params.add("tag", tag);
+ params.add("fromSrc", "-");
+
+ WebResource webResource = client.resource(restEndpointUrl + "/images/create").queryParams(params);
+
+ try {
+ LOGGER.trace("POST: {}", webResource);
+ return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ImageCreateResponse.class, imageStream);
+
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error.", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+ public List search(String search) throws DockerException {
+ WebResource webResource = client.resource(restEndpointUrl + "/images/search").queryParam("term", search);
+ try {
+ return webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() {
+ });
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error.", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+
+ }
+
+ /**
+ * Remove an image, deleting any tags it might have.
+ */
+ public void removeImage(String imageId) throws DockerException {
+ Preconditions.checkState(!StringUtils.isEmpty(imageId), "Image ID can't be empty");
+
+ try {
+ WebResource webResource = client.resource(restEndpointUrl + "/images/" + imageId)
+ .queryParam("force", "true");
+ LOGGER.trace("DELETE: {}", webResource);
+ webResource.delete();
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 204) {
+ //no error
+ LOGGER.trace("Successfully removed image " + imageId);
+ } else if (exception.getResponse().getStatus() == 404) {
+ LOGGER.warn("{} no such image", imageId);
+ } else if (exception.getResponse().getStatus() == 409) {
+ throw new DockerException("Conflict");
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error.", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+
+ }
+
+ public void removeImages(List images) throws DockerException {
+ Preconditions.checkNotNull(images, "List of images can't be null");
+
+ for (String imageId : images) {
+ removeImage(imageId);
+ }
+ }
+
+ public String getVizImages() throws DockerException {
+ WebResource webResource = client.resource(restEndpointUrl + "/images/viz");
+
+ try {
+ LOGGER.trace("GET: {}", webResource);
+ String response = webResource.get(String.class);
+ LOGGER.trace("Response: {}", response);
+
+ return response;
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 400) {
+ throw new DockerException("bad parameter");
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+
+ public List getImages() throws DockerException {
+ return this.getImages(null, false);
+ }
+
+ public List getImages(boolean allContainers) throws DockerException {
+ return this.getImages(null, allContainers);
+ }
+
+ public List getImages(String name) throws DockerException {
+ return this.getImages(name, false);
+ }
+
+ public List getImages(String name, boolean allImages) throws DockerException {
+
+ MultivaluedMap params = new MultivaluedMapImpl();
+ params.add("filter", name);
+ params.add("all", allImages ? "1" : "0");
+
+ WebResource webResource = client.resource(restEndpointUrl + "/images/json").queryParams(params);
+
+ try {
+ LOGGER.trace("GET: {}", webResource);
+ List images = webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() {
+ });
+ LOGGER.trace("Response: {}", images);
+ return images;
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 400) {
+ throw new DockerException("bad parameter");
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException();
+ }
+ }
+
+ }
+
+ public ImageInspectResponse inspectImage(String imageId) throws DockerException, NotFoundException {
+
+ WebResource webResource = client.resource(restEndpointUrl + String.format("/images/%s/json", imageId));
+
+ try {
+ LOGGER.trace("GET: {}", webResource);
+ return webResource.accept(MediaType.APPLICATION_JSON).get(ImageInspectResponse.class);
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 404) {
+ throw new NotFoundException(String.format("No such image %s", imageId));
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+ /**
+ * * CONTAINER API
+ * *
+ */
+
+ public List listContainers(boolean allContainers) {
+ return this.listContainers(allContainers, false, -1, false, null, null);
+ }
+
+ public List listContainers(boolean allContainers, boolean latest) {
+ return this.listContainers(allContainers, latest, -1, false, null, null);
+ }
+
+ public List listContainers(boolean allContainers, boolean latest, int limit) {
+ return this.listContainers(allContainers, latest, limit, false, null, null);
+ }
+
+ public List listContainers(boolean allContainers, boolean latest, int limit, boolean showSize) {
+ return this.listContainers(allContainers, latest, limit, showSize, null, null);
+ }
+
+ public List listContainers(boolean allContainers, boolean latest, int limit, boolean showSize, String since) {
+ return this.listContainers(allContainers, latest, limit, false, since, null);
+ }
+
+ public List listContainers(boolean allContainers, boolean latest, int limit, boolean showSize, String since, String before) {
+
+ MultivaluedMap params = new MultivaluedMapImpl();
+ params.add("limit", latest ? "1" : String.valueOf(limit));
+ params.add("all", allContainers ? "1" : "0");
+ params.add("since", since);
+ params.add("before", before);
+ params.add("size", showSize ? "1" : "0");
+
+ WebResource webResource = client.resource(restEndpointUrl + "/containers/json").queryParams(params);
+ LOGGER.trace("GET: {}", webResource);
+ List containers = webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() {
+ });
+ LOGGER.trace("Response: {}", containers);
+
+ return containers;
+ }
+
+ public ContainerCreateResponse createContainer(ContainerConfig config) throws DockerException {
+ return createContainer(config, null);
+ }
+
+ public ContainerCreateResponse createContainer(ContainerConfig config, String name) throws DockerException, NotFoundException {
+
+ MultivaluedMap params = new MultivaluedMapImpl();
+ if (name != null) {
+ params.add("name", name);
+ }
+ WebResource webResource = client.resource(restEndpointUrl + "/containers/create").queryParams(params);
+
+ try {
+ LOGGER.trace("POST: {} ", webResource);
+ return webResource.accept(MediaType.APPLICATION_JSON)
+ .type(MediaType.APPLICATION_JSON)
+ .post(ContainerCreateResponse.class, config);
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 404) {
+ throw new NotFoundException(String.format("%s is an unrecognized image. Please pull the image first.", config.getImage()));
+ } else if (exception.getResponse().getStatus() == 406) {
+ throw new DockerException("impossible to attach (container not running)");
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+
+ }
+
+ public void startContainer(String containerId) throws DockerException {
+ this.startContainer(containerId, null);
+ }
+
+ public void startContainer(String containerId, HostConfig hostConfig) throws DockerException, NotFoundException {
+
+ WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/start", containerId));
+
+ try {
+ LOGGER.trace("POST: {}", webResource);
+ Builder builder = webResource.accept(MediaType.TEXT_PLAIN);
+ if (hostConfig != null) {
+ builder.type(MediaType.APPLICATION_JSON).post(hostConfig);
+ } else {
+ builder.post((HostConfig) null);
+ }
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 404) {
+ throw new NotFoundException(String.format("No such container %s", containerId));
+ } else if (exception.getResponse().getStatus() == 204) {
+ //no error
+ LOGGER.trace("Successfully started container {}", containerId);
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+ public ContainerInspectResponse inspectContainer(String containerId) throws DockerException, NotFoundException {
+
+ WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/json", containerId));
+
+ try {
+ LOGGER.trace("GET: {}", webResource);
+ return webResource.accept(MediaType.APPLICATION_JSON).get(ContainerInspectResponse.class);
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 404) {
+ throw new NotFoundException(String.format("No such container %s", containerId));
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+
+ public void removeContainer(String container) throws DockerException {
+ this.removeContainer(container, false);
+ }
+
+ public void removeContainer(String containerId, boolean removeVolumes) throws DockerException {
+ Preconditions.checkState(!StringUtils.isEmpty(containerId), "Container ID can't be empty");
+
+ WebResource webResource = client.resource(restEndpointUrl + "/containers/" + containerId).queryParam("v", removeVolumes ? "1" : "0");
+
+ try {
+ LOGGER.trace("DELETE: {}", webResource);
+ String response = webResource.accept(MediaType.APPLICATION_JSON).delete(String.class);
+ LOGGER.trace("Response: {}", response);
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 204) {
+ //no error
+ LOGGER.trace("Successfully removed container " + containerId);
+ } else if (exception.getResponse().getStatus() == 400) {
+ throw new DockerException("bad parameter");
+ } else if (exception.getResponse().getStatus() == 404) {
+ // should really throw a NotFoundException instead of silently ignoring the problem
+ LOGGER.warn(String.format("%s is an unrecognized container.", containerId));
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+
+ public void removeContainers(List containers, boolean removeVolumes) throws DockerException {
+ Preconditions.checkNotNull(containers, "List of containers can't be null");
+
+ for (String containerId : containers) {
+ removeContainer(containerId, removeVolumes);
+ }
+ }
+
+ public int waitContainer(String containerId) throws DockerException, NotFoundException {
+ WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/wait", containerId));
+
+ try {
+ LOGGER.trace("POST: {}", webResource);
+ ObjectNode ObjectNode = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ObjectNode.class);
+ return ObjectNode.get("StatusCode").asInt();
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 404) {
+ throw new NotFoundException(String.format("No such container %s", containerId));
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ } catch (Exception e) {
+ throw new DockerException(e);
+ }
+ }
+
+
+ public ClientResponse logContainer(String containerId) throws DockerException {
+ return logContainer(containerId, false);
+ }
+
+ public ClientResponse logContainerStream(String containerId) throws DockerException {
+ return logContainer(containerId, true);
+ }
+
+ private ClientResponse logContainer(String containerId, boolean stream) throws DockerException, NotFoundException {
+ MultivaluedMap params = new MultivaluedMapImpl();
+ params.add("logs", "1");
+ params.add("stdout", "1");
+ params.add("stderr", "1");
+ if (stream) {
+ params.add("stream", "1"); // this parameter keeps stream open indefinitely
+ }
+
+ WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/attach", containerId))
+ .queryParams(params);
+
+ try {
+ LOGGER.trace("POST: {}", webResource);
+ return webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).post(ClientResponse.class, params);
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 400) {
+ throw new DockerException("bad parameter");
+ } else if (exception.getResponse().getStatus() == 404) {
+ throw new NotFoundException(String.format("No such container %s", containerId));
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+ public ClientResponse copyFile(String containerId, String resource) throws DockerException {
+ CopyConfig copyConfig = new CopyConfig();
+ copyConfig.setResource(resource);
+
+ WebResource webResource =
+ client.resource(restEndpointUrl + String.format("/containers/%s/copy", containerId));
+
+ try {
+ LOGGER.trace("POST: " + webResource.toString());
+ WebResource.Builder builder =
+ webResource.accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).type("application/json");
+
+ return builder.post(ClientResponse.class, copyConfig.toString());
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 400) {
+ throw new DockerException("bad parameter");
+ } else if (exception.getResponse().getStatus() == 404) {
+ throw new DockerException(String.format("No such container %s", containerId));
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+ public List containerDiff(String containerId) throws DockerException, NotFoundException {
+
+ WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/changes", containerId));
+
+ try {
+ LOGGER.trace("GET: {}", webResource);
+ return webResource.accept(MediaType.APPLICATION_JSON).get(new GenericType>() {
+ });
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 404) {
+ throw new NotFoundException(String.format("No such container %s", containerId));
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+
+ public void stopContainer(String containerId) throws DockerException {
+ this.stopContainer(containerId, 10);
+ }
+
+ public void stopContainer(String containerId, int timeout) throws DockerException {
+
+ WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/stop", containerId))
+ .queryParam("t", String.valueOf(timeout));
+
+
+ try {
+ LOGGER.trace("POST: {}", webResource);
+ webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post();
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 404) {
+ LOGGER.warn("No such container {}", containerId);
+ } else if (exception.getResponse().getStatus() == 204) {
+ //no error
+ LOGGER.trace("Successfully stopped container {}", containerId);
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+ public void kill(String containerId) throws DockerException {
+ WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/kill", containerId));
+
+ try {
+ LOGGER.trace("POST: {}", webResource);
+ webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post();
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 404) {
+ LOGGER.warn("No such container {}", containerId);
+ } else if (exception.getResponse().getStatus() == 204) {
+ //no error
+ LOGGER.trace("Successfully killed container {}", containerId);
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+ public void restart(String containerId, int timeout) throws DockerException, NotFoundException {
+ WebResource webResource = client.resource(restEndpointUrl + String.format("/containers/%s/restart", containerId));
+
+ try {
+ LOGGER.trace("POST: {}", webResource);
+ webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post();
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 404) {
+ throw new NotFoundException(String.format("No such container %s", containerId));
+ } else if (exception.getResponse().getStatus() == 204) {
+ //no error
+ LOGGER.trace("Successfully restarted container {}", containerId);
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ }
+ }
+
+ public String commit(CommitConfig commitConfig) throws DockerException, NotFoundException {
+ Preconditions.checkNotNull(commitConfig.getContainer(), "Container ID was not specified");
+
+ MultivaluedMap params = new MultivaluedMapImpl();
+ params.add("container", commitConfig.getContainer());
+ params.add("repo", commitConfig.getRepo());
+ params.add("tag", commitConfig.getTag());
+ params.add("m", commitConfig.getMessage());
+ params.add("author", commitConfig.getAuthor());
+ params.add("run", commitConfig.getRun());
+
+ WebResource webResource = client.resource(restEndpointUrl + "/commit").queryParams(params);
+
+ try {
+ LOGGER.trace("POST: {}", webResource);
+ ObjectNode ObjectNode = webResource.accept("application/vnd.docker.raw-stream").post(ObjectNode.class, params);
+ return ObjectNode.get("Id").asText();
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 404) {
+ throw new NotFoundException(String.format("No such container %s", commitConfig.getContainer()));
+ } else if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ } catch (Exception e) {
+ throw new DockerException(e);
+ }
+ }
+
+
+ public ClientResponse build(File dockerFolder) throws DockerException {
+ return this.build(dockerFolder, null);
+ }
+
+ public ClientResponse build(File dockerFolder, String tag) throws DockerException {
+ return this.build(dockerFolder, tag, false);
+ }
+
+ private static boolean isFileResource(String resource) {
+ URI uri;
+ try {
+ uri = new URI(resource);
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(e);
+ }
+ return uri.getScheme() == null || "file".equals(uri.getScheme());
+ }
+
+ public ClientResponse build(File dockerFolder, String tag, boolean noCache) throws DockerException {
+ Preconditions.checkNotNull(dockerFolder, "Folder is null");
+ Preconditions.checkArgument(dockerFolder.exists(), "Folder %s doesn't exist", dockerFolder);
+ Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(), "Dockerfile doesn't exist in " + dockerFolder);
+
+ //We need to use Jersey HttpClient here, since ApacheHttpClient4 will not add boundary filed to
+ //Content-Type: multipart/form-data; boundary=Boundary_1_372491238_1372806136625
+
+ MultivaluedMap params = new MultivaluedMapImpl();
+ params.add("t", tag);
+ if (noCache) {
+ params.add("nocache", "true");
+ }
+
+ // ARCHIVE TAR
+ String archiveNameWithOutExtension = UUID.randomUUID().toString();
+
+ File dockerFolderTar = null;
+
+ try {
+ File dockerFile = new File(dockerFolder, "Dockerfile");
+ List dockerFileContent = FileUtils.readLines(dockerFile);
+
+ if (dockerFileContent.size() <= 0) {
+ throw new DockerException(String.format("Dockerfile %s is empty", dockerFile));
+ }
+
+ List filesToAdd = new ArrayList();
+ filesToAdd.add(dockerFile);
+
+ for (String cmd : dockerFileContent) {
+ if (StringUtils.startsWithIgnoreCase(cmd.trim(), "ADD")) {
+ String addArgs[] = StringUtils.split(cmd, " \t");
+ if (addArgs.length != 3) {
+ throw new DockerException(String.format("Wrong format on line [%s]", cmd));
+ }
+
+ String resource = addArgs[1];
+
+ if(isFileResource(resource)) {
+ File src = new File(resource);
+ if (!src.isAbsolute()) {
+ src = new File(dockerFolder, resource).getCanonicalFile();
+ } else {
+ throw new DockerException(String.format("Source file %s must be relative to %s", src, dockerFolder));
+ }
+
+ if (!src.exists()) {
+ throw new DockerException(String.format("Source file %s doesn't exist", src));
+ }
+ if (src.isDirectory()) {
+ filesToAdd.addAll(FileUtils.listFiles(src, null, true));
+ } else {
+ filesToAdd.add(src);
+ }
+ }
+ }
+ }
+
+ dockerFolderTar = CompressArchiveUtil.archiveTARFiles(dockerFolder, filesToAdd, archiveNameWithOutExtension);
+
+ } catch (IOException ex) {
+ FileUtils.deleteQuietly(dockerFolderTar);
+ throw new DockerException("Error occurred while preparing Docker context folder.", ex);
+ }
+
+ WebResource webResource = client.resource(restEndpointUrl + "/build").queryParams(params);
+
+ try {
+ LOGGER.trace("POST: {}", webResource);
+ return webResource
+ .type("application/tar")
+ .accept(MediaType.TEXT_PLAIN)
+ .post(ClientResponse.class, FileUtils.openInputStream(dockerFolderTar));
+ } catch (UniformInterfaceException exception) {
+ if (exception.getResponse().getStatus() == 500) {
+ throw new DockerException("Server error", exception);
+ } else {
+ throw new DockerException(exception);
+ }
+ } catch (IOException e) {
+ throw new DockerException(e);
+ } finally {
+ FileUtils.deleteQuietly(dockerFolderTar);
+ }
+ }
}
diff --git a/src/main/java/com/kpelykh/docker/client/NotFoundException.java b/src/main/java/com/kpelykh/docker/client/NotFoundException.java
new file mode 100644
index 00000000..76569f7b
--- /dev/null
+++ b/src/main/java/com/kpelykh/docker/client/NotFoundException.java
@@ -0,0 +1,14 @@
+package com.kpelykh.docker.client;
+
+/**
+ * Indicates that the given entity does not exist.
+ *
+ * @author Ryan Campbell ryan.campbell@gmail.com
+ */
+public class NotFoundException extends DockerException {
+
+ public NotFoundException(String message) {
+ super(message);
+ }
+
+}
diff --git a/src/main/java/com/kpelykh/docker/client/UnixSocketClient.java b/src/main/java/com/kpelykh/docker/client/UnixSocketClient.java
deleted file mode 100644
index 75582037..00000000
--- a/src/main/java/com/kpelykh/docker/client/UnixSocketClient.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package com.kpelykh.docker.client;
-
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.config.ClientConfig;
-
-
-public class UnixSocketClient extends Client {
-
- public UnixSocketClient(ClientConfig clientConfig) {
- super(new UnixSocketClientHandler(), clientConfig);
- }
-}
diff --git a/src/main/java/com/kpelykh/docker/client/UnixSocketClientHandler.java b/src/main/java/com/kpelykh/docker/client/UnixSocketClientHandler.java
deleted file mode 100644
index 6ce3f1ce..00000000
--- a/src/main/java/com/kpelykh/docker/client/UnixSocketClientHandler.java
+++ /dev/null
@@ -1,213 +0,0 @@
-package com.kpelykh.docker.client;
-
-import com.sun.jersey.api.client.*;
-import com.sun.jersey.api.client.config.ClientConfig;
-import com.sun.jersey.core.header.InBoundHeaders;
-import com.sun.jersey.core.util.ReaderWriter;
-import jnr.unixsocket.UnixSocketAddress;
-import jnr.unixsocket.UnixSocketChannel;
-import org.apache.http.Header;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpException;
-import org.apache.http.HttpResponse;
-import org.apache.http.annotation.NotThreadSafe;
-import org.apache.http.client.methods.*;
-import org.apache.http.entity.AbstractHttpEntity;
-import org.apache.http.entity.BufferedHttpEntity;
-import org.apache.http.impl.DefaultHttpResponseFactory;
-import org.apache.http.impl.io.DefaultHttpResponseParser;
-import org.apache.http.impl.io.HttpRequestWriter;
-import org.apache.http.message.BasicLineFormatter;
-import org.apache.http.message.BasicLineParser;
-import org.apache.http.params.BasicHttpParams;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.*;
-import java.net.URI;
-import java.nio.channels.Channels;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * TODO: Make thread-safe.
- */
-@NotThreadSafe
-public class UnixSocketClientHandler extends RequestWriter implements ClientHandler {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(UnixSocketClientHandler.class);
-
- public static final int BUFFERSIZE = 1024;
- public static final String DOCKER_SOCKET_PATH = "/var/run/docker.sock";
-
- @Override
- public ClientResponse handle(ClientRequest cr) throws ClientHandlerException {
- try {
- File path = new File(DOCKER_SOCKET_PATH);
- UnixSocketAddress address = new UnixSocketAddress(path);
- UnixSocketChannel channel = UnixSocketChannel.open(address);
- OutputStream unixSocketChannelOutputStream = Channels.newOutputStream(channel);
-
- final HttpUriRequest request = getUriHttpRequest(cr);
- BasicHttpParams params = new BasicHttpParams();
-
- UnixSocketSessionOutputBuffer outputBuffer = new UnixSocketSessionOutputBuffer();
- outputBuffer.init(unixSocketChannelOutputStream, BUFFERSIZE, params);
- HttpRequestWriter writer = new HttpRequestWriter(outputBuffer, new BasicLineFormatter(), params);
- writer.write(request);
- outputBuffer.flush();
-
- UnixSocketSessionInputBuffer inputBuffer = new UnixSocketSessionInputBuffer();
- inputBuffer.init(Channels.newInputStream(channel), BUFFERSIZE, params);
-
- HttpResponse response = new DefaultHttpResponseParser(inputBuffer, new BasicLineParser(), new DefaultHttpResponseFactory(), params).parse();
- LOGGER.trace(response.toString());
-
- ClientResponse clientResponse = new ClientResponse(response.getStatusLine().getStatusCode(),
- getInBoundHeaders(response),
- new HttpClientResponseInputStream(response),
- getMessageBodyWorkers());
-
- clientResponse.bufferEntity();
- clientResponse.close();
-
- return clientResponse;
-
- } catch (IOException e) {
- e.printStackTrace();
- } catch (HttpException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- private HttpUriRequest getUriHttpRequest(final ClientRequest cr) {
- final String strMethod = cr.getMethod();
- final URI uri = cr.getURI();
-
- final HttpEntity entity = getHttpEntity(cr);
- final HttpUriRequest request;
-
- if (strMethod.equals("GET")) {
- request = new HttpGet(uri);
- } else if (strMethod.equals("POST")) {
- request = new HttpPost(uri);
- } else if (strMethod.equals("PUT")) {
- request = new HttpPut(uri);
- } else if (strMethod.equals("DELETE")) {
- request = new HttpDelete(uri);
- } else if (strMethod.equals("HEAD")) {
- request = new HttpHead(uri);
- } else if (strMethod.equals("OPTIONS")) {
- request = new HttpOptions(uri);
- } else {
- request = new HttpEntityEnclosingRequestBase() {
- @Override
- public String getMethod() {
- return strMethod;
- }
-
- @Override
- public URI getURI() {
- return uri;
- }
- };
- }
-
- if (entity != null && request instanceof HttpEntityEnclosingRequestBase) {
- ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
- } else if (entity != null) {
- throw new ClientHandlerException("Adding entity to http method " + cr.getMethod() + " is not supported.");
- }
-
- return request;
- }
-
- private HttpEntity getHttpEntity(final ClientRequest cr) {
- final Object entity = cr.getEntity();
-
- if (entity == null)
- return null;
-
- final RequestEntityWriter requestEntityWriter = getRequestEntityWriter(cr);
-
- try {
- HttpEntity httpEntity = new AbstractHttpEntity() {
- @Override
- public boolean isRepeatable() {
- return false;
- }
-
- @Override
- public long getContentLength() {
- return requestEntityWriter.getSize();
- }
-
- @Override
- public InputStream getContent() throws IOException, IllegalStateException {
- return null;
- }
-
- @Override
- public void writeTo(OutputStream outputStream) throws IOException {
- requestEntityWriter.writeRequestEntity(outputStream);
- }
-
- @Override
- public boolean isStreaming() {
- return false;
- }
- };
-
- if (cr.getProperties().get(ClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE) != null) {
- // TODO return InputStreamEntity
- return httpEntity;
- } else {
- return new BufferedHttpEntity(httpEntity);
- }
- } catch (Exception ex) {
- // TODO warning/error?
- }
-
- return null;
- }
-
- private InBoundHeaders getInBoundHeaders(final HttpResponse response) {
- final InBoundHeaders headers = new InBoundHeaders();
- final Header[] respHeaders = response.getAllHeaders();
- for (Header header : respHeaders) {
- List list = headers.get(header.getName());
- if (list == null) {
- list = new ArrayList();
- }
- list.add(header.getValue());
- headers.put(header.getName(), list);
- }
- return headers;
- }
-
- private static final class HttpClientResponseInputStream extends FilterInputStream {
-
- HttpClientResponseInputStream(final HttpResponse response) throws IOException {
- super(getInputStream(response));
- }
-
- @Override
- public void close()
- throws IOException {
- super.close();
- }
- }
-
- private static InputStream getInputStream(final HttpResponse response) throws IOException {
-
- if (response.getEntity() == null) {
- return new ByteArrayInputStream(new byte[0]);
- } else {
- final InputStream i = response.getEntity().getContent();
- if (i.markSupported())
- return i;
- return new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE);
- }
- }
-}
diff --git a/src/main/java/com/kpelykh/docker/client/UnixSocketSessionInputBuffer.java b/src/main/java/com/kpelykh/docker/client/UnixSocketSessionInputBuffer.java
deleted file mode 100644
index 9c7f150c..00000000
--- a/src/main/java/com/kpelykh/docker/client/UnixSocketSessionInputBuffer.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.kpelykh.docker.client;
-
-import org.apache.http.impl.io.AbstractSessionInputBuffer;
-import org.apache.http.params.HttpParams;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- *
- */
-public class UnixSocketSessionInputBuffer extends AbstractSessionInputBuffer {
-
- @Override
- protected void init(InputStream instream, int buffersize, HttpParams params) {
- super.init(instream, buffersize, params);
- }
-
- @Override
- public boolean isDataAvailable(int timeout) throws IOException {
- return true;
- }
-}
diff --git a/src/main/java/com/kpelykh/docker/client/UnixSocketSessionOutputBuffer.java b/src/main/java/com/kpelykh/docker/client/UnixSocketSessionOutputBuffer.java
deleted file mode 100644
index 411096ff..00000000
--- a/src/main/java/com/kpelykh/docker/client/UnixSocketSessionOutputBuffer.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.kpelykh.docker.client;
-
-import org.apache.http.impl.io.AbstractSessionOutputBuffer;
-import org.apache.http.params.HttpParams;
-
-import java.io.OutputStream;
-
-/**
- * {@link org.apache.http.impl.io.AbstractSessionOutputBuffer} implementation for UNIX sockets.
- */
-public class UnixSocketSessionOutputBuffer extends AbstractSessionOutputBuffer {
-
- @Override
- protected void init(OutputStream outstream, int buffersize, HttpParams params) {
- super.init(outstream, buffersize, params);
- }
-}
diff --git a/src/main/java/com/kpelykh/docker/client/model/AuthConfig.java b/src/main/java/com/kpelykh/docker/client/model/AuthConfig.java
new file mode 100644
index 00000000..514e79be
--- /dev/null
+++ b/src/main/java/com/kpelykh/docker/client/model/AuthConfig.java
@@ -0,0 +1,58 @@
+package com.kpelykh.docker.client.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class AuthConfig {
+ @JsonProperty
+ private String username;
+ @JsonProperty
+ private String password;
+ @JsonProperty
+ private String email;
+ @JsonProperty("serveraddress")
+ private String serverAddress = "https://index.docker.io/v1/";
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getServerAddress() {
+ return serverAddress;
+ }
+
+ public void setServerAddress(String serverAddress) {
+ this.serverAddress = serverAddress;
+ }
+
+ @Override
+ public String toString() {
+ return "AuthConfig{" +
+ "username='" + username + '\'' +
+ ", password='" + password + '\'' +
+ ", email='" + email + '\'' +
+ ", serverAddress='" + serverAddress + '\'' +
+ '}';
+ }
+}
diff --git a/src/main/java/com/kpelykh/docker/client/model/BoundHostVolumes.java b/src/main/java/com/kpelykh/docker/client/model/BoundHostVolumes.java
new file mode 100644
index 00000000..9a912439
--- /dev/null
+++ b/src/main/java/com/kpelykh/docker/client/model/BoundHostVolumes.java
@@ -0,0 +1,92 @@
+/**
+ * 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 com.kpelykh.docker.client.model;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Kevin A. Archie
+ *
+ */
+@JsonSerialize(using=BoundHostVolumes.Serializer.class)
+public class BoundHostVolumes {
+ private static final String[] STRING_ARRAY = new String[0];
+ private final String[] dests, binds;
+
+ /**
+ *
+ * @param specs Iterable of String binding specs, each of form "{host-path}:{container-patch}:[rw|ro]"
+ * @throws MalformedVolumeSpecException if any specs are null or empty
+ */
+ public BoundHostVolumes(final Iterable specs) {
+ final List dests = new ArrayList(), binds = new ArrayList();
+ for (final String spec : specs) {
+ if (null == spec || "".equals(spec)) {
+ // skip empty spec lines
+ } else {
+ final String[] sspec = spec.split(":");
+ dests.add(sspec.length > 1 ? sspec[1] : sspec[0]);
+ binds.add(spec);
+ }
+ }
+ this.dests = dests.toArray(STRING_ARRAY);
+ this.binds = binds.toArray(STRING_ARRAY);
+ }
+
+ public String[] asBinds() {
+ return binds;
+ }
+
+ private BoundHostVolumes writeVolumes(final JsonGenerator jg) throws IOException {
+ jg.writeStartObject();
+ for (final String dest : dests) {
+ jg.writeObjectFieldStart(dest);
+ jg.writeEndObject();
+ }
+ jg.writeEndObject();
+ return this;
+ }
+
+ /**
+ * This is an ugly hack. We assume that the serializer only gets called when
+ * a containing ContainerConfig gets serialized, when POSTing to
+ * /containers/create . In that context, we pass only the container-path
+ * part (the key in the volumes map).
+ *
+ * @author Kevin A. Archie
+ *
+ */
+ public static class Serializer extends JsonSerializer {
+ /* (non-Javadoc)
+ * @see org.codehaus.jackson.map.JsonSerializer#serialize(java.lang.Object, org.codehaus.jackson.JsonGenerator, org.codehaus.jackson.map.SerializerProvider)
+ */
+ @Override
+ public void serialize(final BoundHostVolumes volumes, final JsonGenerator jg, final SerializerProvider sp)
+ throws IOException {
+ volumes.writeVolumes(jg);
+ }
+ }
+}
diff --git a/src/main/java/com/kpelykh/docker/client/model/ChangeLog.java b/src/main/java/com/kpelykh/docker/client/model/ChangeLog.java
index be6df3a4..50fdab4a 100644
--- a/src/main/java/com/kpelykh/docker/client/model/ChangeLog.java
+++ b/src/main/java/com/kpelykh/docker/client/model/ChangeLog.java
@@ -1,12 +1,14 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
/**
*
* @author Konstantin Pelykh (kpelykh@gmail.com)
*
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public class ChangeLog {
@JsonProperty("Path")
diff --git a/src/main/java/com/kpelykh/docker/client/model/CommitConfig.java b/src/main/java/com/kpelykh/docker/client/model/CommitConfig.java
index 69af9959..4023deb7 100644
--- a/src/main/java/com/kpelykh/docker/client/model/CommitConfig.java
+++ b/src/main/java/com/kpelykh/docker/client/model/CommitConfig.java
@@ -1,12 +1,14 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
/**
*
* @author Konstantin Pelykh (kpelykh@gmail.com)
*
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public class CommitConfig {
@JsonProperty("container")
diff --git a/src/main/java/com/kpelykh/docker/client/model/Container.java b/src/main/java/com/kpelykh/docker/client/model/Container.java
index c9de7434..3e6554cb 100644
--- a/src/main/java/com/kpelykh/docker/client/model/Container.java
+++ b/src/main/java/com/kpelykh/docker/client/model/Container.java
@@ -1,7 +1,7 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.annotate.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Arrays;
@@ -48,6 +48,9 @@ public class Container {
@JsonProperty("SizeRootFs")
private int sizeRootFs;
+ @JsonProperty("Names")
+ private String[] names;
+
public String getId() {
return id;
}
@@ -84,6 +87,42 @@ public int getSizeRootFs() {
return sizeRootFs;
}
+ public String[] getNames() {
+ return names;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public void setCommand(String command) {
+ this.command = command;
+ }
+
+ public void setImage(String image) {
+ this.image = image;
+ }
+
+ public void setCreated(long created) {
+ this.created = created;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public void setSize(int size) {
+ this.size = size;
+ }
+
+ public void setSizeRootFs(int sizeRootFs) {
+ this.sizeRootFs = sizeRootFs;
+ }
+
+ public void setNames(String[] names) {
+ this.names = names;
+ }
+
@Override
public String toString() {
return "Container{" +
@@ -95,6 +134,7 @@ public String toString() {
", ports=" + ports +
", size=" + size +
", sizeRootFs=" + sizeRootFs +
+ ", names=" + Arrays.toString(names) +
'}';
}
}
diff --git a/src/main/java/com/kpelykh/docker/client/model/ContainerConfig.java b/src/main/java/com/kpelykh/docker/client/model/ContainerConfig.java
index 52bf2da5..27a1d7e3 100644
--- a/src/main/java/com/kpelykh/docker/client/model/ContainerConfig.java
+++ b/src/main/java/com/kpelykh/docker/client/model/ContainerConfig.java
@@ -1,6 +1,7 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Arrays;
import java.util.Map;
@@ -10,6 +11,7 @@
* @author Konstantin Pelykh (kpelykh@gmail.com)
*
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public class ContainerConfig {
@JsonProperty("Hostname") private String hostName = "";
@@ -28,7 +30,7 @@ public class ContainerConfig {
@JsonProperty("Cmd") private String[] cmd;
@JsonProperty("Dns") private String[] dns;
@JsonProperty("Image") private String image;
- @JsonProperty("Volumes") private Object volumes;
+ @JsonProperty("Volumes") private BoundHostVolumes volumes;
@JsonProperty("VolumesFrom") private String volumesFrom = "";
@JsonProperty("Entrypoint") private String[] entrypoint = new String[]{};
@JsonProperty("NetworkDisabled") private boolean networkDisabled = false;
@@ -37,7 +39,8 @@ public class ContainerConfig {
@JsonProperty("Domainname") private String domainName = "";
// FIXME Is this the right type? -BJE
@JsonProperty("ExposedPorts") private Map exposedPorts;
- @JsonProperty("OnBuild") private String[] onBuild;
+
+ @JsonProperty("OnBuild") private int[] onBuild;
public Map getExposedPorts() {
return exposedPorts;
@@ -216,11 +219,11 @@ public ContainerConfig setImage(String image) {
return this;
}
- public Object getVolumes() {
+ public BoundHostVolumes getVolumes() {
return volumes;
}
- public ContainerConfig setVolumes(Object volumes) {
+ public ContainerConfig setVolumes(BoundHostVolumes volumes) {
this.volumes = volumes;
return this;
}
@@ -242,14 +245,19 @@ public ContainerConfig setEntrypoint(String[] entrypoint) {
this.entrypoint = entrypoint;
return this;
}
-
- public String[] getOnBuild() {
- return onBuild;
- }
-
- public void setOnBuild(String[] onBuild) {
- this.onBuild=onBuild;
- }
+
+ public void setOnBuild(int[] onBuild) {
+ this.onBuild = onBuild;
+ }
+
+ public int[] getOnBuild() {
+ return onBuild;
+ }
+
+ public void setDomainName(String domainName) {
+ this.domainName = domainName;
+ }
+
@Override
public String toString() {
@@ -277,6 +285,7 @@ public String toString() {
", privileged=" + privileged +
", workingDir='" + workingDir + '\'' +
", domainName='" + domainName + '\'' +
+ ", onBuild='" + Arrays.toString(onBuild) + '\'' +
'}';
}
}
diff --git a/src/main/java/com/kpelykh/docker/client/model/ContainerCreateResponse.java b/src/main/java/com/kpelykh/docker/client/model/ContainerCreateResponse.java
index c0ef5bdc..8f60ce15 100644
--- a/src/main/java/com/kpelykh/docker/client/model/ContainerCreateResponse.java
+++ b/src/main/java/com/kpelykh/docker/client/model/ContainerCreateResponse.java
@@ -1,6 +1,7 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Arrays;
@@ -9,6 +10,7 @@
* @author Konstantin Pelykh (kpelykh@gmail.com)
*
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public class ContainerCreateResponse {
@JsonProperty("Id")
@@ -25,6 +27,14 @@ public String[] getWarnings() {
return warnings;
}
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public void setWarnings(String[] warnings) {
+ this.warnings = warnings;
+ }
+
@Override
public String toString() {
return "ContainerCreateResponse{" +
diff --git a/src/main/java/com/kpelykh/docker/client/model/ContainerInspectResponse.java b/src/main/java/com/kpelykh/docker/client/model/ContainerInspectResponse.java
index 04d2f8c9..d686f9eb 100644
--- a/src/main/java/com/kpelykh/docker/client/model/ContainerInspectResponse.java
+++ b/src/main/java/com/kpelykh/docker/client/model/ContainerInspectResponse.java
@@ -1,16 +1,17 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
-
-import java.util.Arrays;
import java.util.Map;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
/**
*
* @author Konstantin Pelykh (kpelykh@gmail.com)
*
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public class ContainerInspectResponse {
@JsonProperty("ID")
@@ -32,7 +33,7 @@ public class ContainerInspectResponse {
private ContainerState state;
@JsonProperty("Image")
- private String image;
+ private String imageId;
@JsonProperty("NetworkSettings")
private NetworkSettings networkSettings;
@@ -64,6 +65,12 @@ public class ContainerInspectResponse {
@JsonProperty("HostConfig")
private HostConfig hostConfig;
+ @JsonProperty("ExecDriver")
+ private String execDriver;
+
+ @JsonProperty("MountLabel")
+ private String mountLabel;
+
public String getId() {
return id;
}
@@ -112,12 +119,12 @@ public void setState(ContainerState state) {
this.state = state;
}
- public String getImage() {
- return image;
+ public String getImageId() {
+ return imageId;
}
- public void setImage(String image) {
- this.image = image;
+ public void setImageId(String image) {
+ this.imageId = image;
}
public NetworkSettings getNetworkSettings() {
@@ -199,6 +206,22 @@ public HostConfig getHostConfig() {
public void setHostConfig(HostConfig hostConfig) {
this.hostConfig = hostConfig;
}
+
+ public void setExecDriver(String execDriver) {
+ this.execDriver = execDriver;
+ }
+
+ public String getExecDriver() {
+ return execDriver;
+ }
+
+ public String getMountLabel() {
+ return mountLabel;
+ }
+
+ public void setMountLabel(String mountLabel) {
+ this.mountLabel = mountLabel;
+ }
public class NetworkSettings {
diff --git a/src/main/java/com/kpelykh/docker/client/model/CopyConfig.java b/src/main/java/com/kpelykh/docker/client/model/CopyConfig.java
new file mode 100755
index 00000000..696778a2
--- /dev/null
+++ b/src/main/java/com/kpelykh/docker/client/model/CopyConfig.java
@@ -0,0 +1,63 @@
+package com.kpelykh.docker.client.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ * Configuration object for copy command.
+ * @author Victor Lyuboslavsky
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class CopyConfig {
+
+ @JsonProperty("HostPath")
+ private String hostPath;
+
+ @JsonProperty("Resource")
+ private String resource;
+
+ /**
+ * Constructor.
+ */
+ public CopyConfig() {
+ hostPath = ".";
+ }
+
+ /**
+ * Retrieves the 'resource' variable.
+ * @return the 'resource' variable value
+ */
+ public String getResource() {
+ return resource;
+ }
+
+ /**
+ * Sets the 'resource' variable.
+ * @param resource the new 'resource' variable value to set
+ */
+ public void setResource(String resource) {
+ this.resource = resource;
+ }
+
+ /**
+ * Retrieves the 'hostPath' variable.
+ * @return the 'hostPath' variable value
+ */
+ public String getHostPath() {
+ return hostPath;
+ }
+
+ /**
+ * Sets the 'hostPath' variable.
+ * @param hostPath the new 'hostPath' variable value to set
+ */
+ public void setHostPath(String hostPath) {
+ this.hostPath = hostPath;
+ }
+
+ @Override
+ public String toString() {
+ return "{\"HostPath\":\"" + hostPath + "\", \"Resource\":\"" + resource + "\"}";
+ }
+
+}
diff --git a/src/main/java/com/kpelykh/docker/client/model/DriverStatus.java b/src/main/java/com/kpelykh/docker/client/model/DriverStatus.java
index 2ed1922c..5421bc44 100644
--- a/src/main/java/com/kpelykh/docker/client/model/DriverStatus.java
+++ b/src/main/java/com/kpelykh/docker/client/model/DriverStatus.java
@@ -1,10 +1,12 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by ben on 12/12/13.
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public class DriverStatus {
@JsonProperty("Root Dir")
diff --git a/src/main/java/com/kpelykh/docker/client/model/HostConfig.java b/src/main/java/com/kpelykh/docker/client/model/HostConfig.java
index e124cf0d..dc7d4258 100644
--- a/src/main/java/com/kpelykh/docker/client/model/HostConfig.java
+++ b/src/main/java/com/kpelykh/docker/client/model/HostConfig.java
@@ -1,6 +1,7 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Arrays;
@@ -9,6 +10,7 @@
* @author Konstantin Pelykh (kpelykh@gmail.com)
*
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public class HostConfig {
@JsonProperty("Binds")
@@ -33,6 +35,15 @@ public class HostConfig {
@JsonProperty("PublishAllPorts")
private boolean publishAllPorts;
+ @JsonProperty("Dns")
+ private String dns;
+
+ @JsonProperty("DnsSearch")
+ private String dnsSearch;
+
+ @JsonProperty("VolumesFrom")
+ private String volumesFrom;
+
public HostConfig() {
this.binds = null;
}
@@ -93,7 +104,31 @@ public boolean isPublishAllPorts() {
public void setPublishAllPorts(boolean publishAllPorts) {
this.publishAllPorts = publishAllPorts;
}
-
+
+ public String getDns() {
+ return dns;
+ }
+
+ public void setDns(String dns) {
+ this.dns = dns;
+ }
+
+ public void setDnsSearch(String dnsSearch) {
+ this.dnsSearch = dnsSearch;
+ }
+
+ public String getDnsSearch() {
+ return dnsSearch;
+ }
+
+ public void setVolumesFrom(String volumesFrom) {
+ this.volumesFrom = volumesFrom;
+ }
+
+ public String getVolumesFrom() {
+ return volumesFrom;
+ }
+
@Override
public String toString() {
return "HostConfig{" +
@@ -104,6 +139,7 @@ public String toString() {
", portBindings=" + portBindings +
", privileged=" + privileged +
", publishAllPorts=" + publishAllPorts +
+ ", dns='" + dns + '\'' +
'}';
}
diff --git a/src/main/java/com/kpelykh/docker/client/model/Image.java b/src/main/java/com/kpelykh/docker/client/model/Image.java
index 4b68590c..cfc578ce 100644
--- a/src/main/java/com/kpelykh/docker/client/model/Image.java
+++ b/src/main/java/com/kpelykh/docker/client/model/Image.java
@@ -1,6 +1,7 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Arrays;
@@ -9,6 +10,7 @@
* @author Konstantin Pelykh (kpelykh@gmail.com)
*
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public class Image {
@JsonProperty("Id")
diff --git a/src/main/java/com/kpelykh/docker/client/model/ImageCreateResponse.java b/src/main/java/com/kpelykh/docker/client/model/ImageCreateResponse.java
new file mode 100644
index 00000000..21545a2d
--- /dev/null
+++ b/src/main/java/com/kpelykh/docker/client/model/ImageCreateResponse.java
@@ -0,0 +1,30 @@
+package com.kpelykh.docker.client.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ * Parse reponses from /images/create
+ *
+ * @author Ryan Campbell (ryan.campbell@gmail.com)
+ *
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class ImageCreateResponse {
+
+ @JsonProperty("status")
+ private String id;
+
+
+ public String getId() {
+ return id;
+ }
+
+
+ @Override
+ public String toString() {
+ return "ContainerCreateResponse{" +
+ "id='" + id + '\'' +
+ '}';
+ }
+}
diff --git a/src/main/java/com/kpelykh/docker/client/model/ImageInspectResponse.java b/src/main/java/com/kpelykh/docker/client/model/ImageInspectResponse.java
index 4b714f4f..3514670c 100644
--- a/src/main/java/com/kpelykh/docker/client/model/ImageInspectResponse.java
+++ b/src/main/java/com/kpelykh/docker/client/model/ImageInspectResponse.java
@@ -1,12 +1,14 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
/**
*
* @author Konstantin Pelykh (kpelykh@gmail.com)
*
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public class ImageInspectResponse {
@JsonProperty("id")
@@ -20,7 +22,7 @@ public class ImageInspectResponse {
@JsonProperty("container_config") private ContainerConfig containerConfig;
- @JsonProperty("Size") private int size;
+ @JsonProperty("Size") private long size;
@JsonProperty("docker_version") private String dockerVersion;
@@ -74,11 +76,11 @@ public void setContainerConfig(ContainerConfig containerConfig) {
this.containerConfig = containerConfig;
}
- public int getSize() {
+ public long getSize() {
return size;
}
- public void setSize(int size) {
+ public void setSize(long size) {
this.size = size;
}
diff --git a/src/main/java/com/kpelykh/docker/client/model/Info.java b/src/main/java/com/kpelykh/docker/client/model/Info.java
index f340dc81..72f2f360 100644
--- a/src/main/java/com/kpelykh/docker/client/model/Info.java
+++ b/src/main/java/com/kpelykh/docker/client/model/Info.java
@@ -1,7 +1,8 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.List;
@@ -11,6 +12,7 @@
*
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
+@JsonIgnoreProperties(ignoreUnknown = true)
public class Info {
@JsonProperty("Debug")
@@ -200,7 +202,7 @@ public String getExecutionDriver() {
public void setExecutionDriver(String executionDriver) {
this.executionDriver=executionDriver;
}
-
+
@Override
public String toString() {
return "Info{" +
diff --git a/src/main/java/com/kpelykh/docker/client/model/Port.java b/src/main/java/com/kpelykh/docker/client/model/Port.java
index b4fa913a..538213ec 100644
--- a/src/main/java/com/kpelykh/docker/client/model/Port.java
+++ b/src/main/java/com/kpelykh/docker/client/model/Port.java
@@ -1,11 +1,12 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author Nicolas De Loof
*/
-
+@JsonIgnoreProperties(ignoreUnknown = true)
public class Port {
@JsonProperty("PrivatePort")
diff --git a/src/main/java/com/kpelykh/docker/client/model/Ports.java b/src/main/java/com/kpelykh/docker/client/model/Ports.java
index d9fdab60..fc590289 100644
--- a/src/main/java/com/kpelykh/docker/client/model/Ports.java
+++ b/src/main/java/com/kpelykh/docker/client/model/Ports.java
@@ -1,13 +1,14 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.*;
-import org.codehaus.jackson.map.DeserializationContext;
-import org.codehaus.jackson.map.JsonDeserializer;
-import org.codehaus.jackson.map.JsonSerializer;
-import org.codehaus.jackson.map.SerializerProvider;
-import org.codehaus.jackson.map.annotate.JsonDeserialize;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-import org.codehaus.jackson.node.NullNode;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.ObjectCodec;
+import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.node.NullNode;
import java.io.IOException;
import java.util.HashMap;
@@ -93,12 +94,12 @@ public Ports deserialize(JsonParser jsonParser, DeserializationContext deseriali
Ports out = new Ports();
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
- for (Iterator> it = node.getFields(); it.hasNext();) {
+ for (Iterator> it = node.fields(); it.hasNext();) {
Map.Entry field = it.next();
if (!field.getValue().equals(NullNode.getInstance())) {
- String hostIp = field.getValue().get(0).get("HostIp").getTextValue();
- String hostPort = field.getValue().get(0).get("HostPort").getTextValue();
+ String hostIp = field.getValue().get(0).get("HostIp").textValue();
+ String hostPort = field.getValue().get(0).get("HostPort").textValue();
out.addPort(Port.makePort(field.getKey(), hostIp, hostPort));
}
}
diff --git a/src/main/java/com/kpelykh/docker/client/model/SearchItem.java b/src/main/java/com/kpelykh/docker/client/model/SearchItem.java
index 9c0942ea..d7f6eb4f 100644
--- a/src/main/java/com/kpelykh/docker/client/model/SearchItem.java
+++ b/src/main/java/com/kpelykh/docker/client/model/SearchItem.java
@@ -1,12 +1,14 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
/**
*
* @author Konstantin Pelykh (kpelykh@gmail.com)
*
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public class SearchItem {
@JsonProperty("star_count")
diff --git a/src/main/java/com/kpelykh/docker/client/model/Version.java b/src/main/java/com/kpelykh/docker/client/model/Version.java
index 915ae67e..a427aafb 100644
--- a/src/main/java/com/kpelykh/docker/client/model/Version.java
+++ b/src/main/java/com/kpelykh/docker/client/model/Version.java
@@ -1,15 +1,16 @@
package com.kpelykh.docker.client.model;
-import org.codehaus.jackson.annotate.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
/**
*
* @author Konstantin Pelykh (kpelykh@gmail.com)
*
*/
+@JsonIgnoreProperties(ignoreUnknown = true)
public class Version {
-
@JsonProperty("Version")
private String version;
@@ -28,6 +29,8 @@ public class Version {
@JsonProperty("Os")
private String operatingSystem;
+ @JsonProperty("ApiVersion")
+ private String apiVersion;
public String getVersion() {
return version;
@@ -76,6 +79,14 @@ public String getOperatingSystem() {
public void setOperatingSystem(String operatingSystem) {
this.operatingSystem = operatingSystem;
}
+
+ public void setApiVersion(String apiVersion) {
+ this.apiVersion = apiVersion;
+ }
+
+ public String getApiVersion() {
+ return apiVersion;
+ }
@Override
public String toString() {
@@ -86,6 +97,7 @@ public String toString() {
", kernelVersion='" + kernelVersion + '\'' +
", arch='" + arch + '\'' +
", operatingSystem='" + operatingSystem + '\'' +
+ ", apiVersion='" + apiVersion + '\'' +
'}';
}
}
diff --git a/src/main/java/com/kpelykh/docker/client/utils/CompressArchiveUtil.java b/src/main/java/com/kpelykh/docker/client/utils/CompressArchiveUtil.java
index 502ad0b7..aabf4cbb 100644
--- a/src/main/java/com/kpelykh/docker/client/utils/CompressArchiveUtil.java
+++ b/src/main/java/com/kpelykh/docker/client/utils/CompressArchiveUtil.java
@@ -3,57 +3,36 @@
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.filefilter.RegexFileFilter;
-import org.apache.commons.lang.StringUtils;
import java.io.*;
-import java.util.Collection;
-
-import static org.apache.commons.io.filefilter.FileFilterUtils.*;
public class CompressArchiveUtil {
- public static File archiveTARFiles(File baseDir, String archiveNameWithOutExtension) throws IOException {
-
- File tarFile = null;
-
- tarFile = new File(FileUtils.getTempDirectoryPath(), archiveNameWithOutExtension + ".tar");
-
- Collection files =
- FileUtils.listFiles(
- baseDir,
- new RegexFileFilter("^(.*?)"),
- and(directoryFileFilter(), notFileFilter(nameFileFilter(baseDir.getName()))));
-
- byte[] buf = new byte[1024];
- int len;
-
- {
- TarArchiveOutputStream tos = new TarArchiveOutputStream(new FileOutputStream(tarFile));
+ public static File archiveTARFiles(File base, Iterable files, String archiveNameWithOutExtension) throws IOException {
+ File tarFile = new File(FileUtils.getTempDirectoryPath(), archiveNameWithOutExtension + ".tar");
+ TarArchiveOutputStream tos = new TarArchiveOutputStream(new FileOutputStream(tarFile));
+ try {
tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
for (File file : files) {
TarArchiveEntry tarEntry = new TarArchiveEntry(file);
- tarEntry.setName(StringUtils.substringAfter(file.toString(), baseDir.getPath()));
+ tarEntry.setName(relativize(base, file));
tos.putArchiveEntry(tarEntry);
if (!file.isDirectory()) {
- FileInputStream fin = new FileInputStream(file);
- BufferedInputStream in = new BufferedInputStream(fin);
-
- while ((len = in.read(buf)) != -1) {
- tos.write(buf, 0, len);
- }
-
- in.close();
+ FileUtils.copyFile(file, tos);
}
tos.closeArchiveEntry();
-
}
+ } finally {
tos.close();
}
-
- return tarFile;
- }
+ return tarFile;
+ }
+
+ private static String relativize(File base, File absolute) {
+ String relative = base.toURI().relativize(absolute.toURI()).getPath();
+ return relative;
+ }
}
diff --git a/src/main/java/com/kpelykh/docker/client/utils/JsonClientFilter.java b/src/main/java/com/kpelykh/docker/client/utils/JsonClientFilter.java
index eae8d089..55b8b287 100644
--- a/src/main/java/com/kpelykh/docker/client/utils/JsonClientFilter.java
+++ b/src/main/java/com/kpelykh/docker/client/utils/JsonClientFilter.java
@@ -5,10 +5,6 @@
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;
-import javax.ws.rs.core.MediaType;
-import java.util.HashMap;
-import java.util.Map;
-
/**
*
* @author Konstantin Pelykh (kpelykh@gmail.com)
@@ -17,12 +13,6 @@
public class JsonClientFilter extends ClientFilter {
public ClientResponse handle(ClientRequest cr) {
- MediaType contentType = (MediaType) cr.getHeaders().getFirst("Content-Type");
- if (contentType != null && !contentType.getParameters().containsKey("charset")) {
- Map contentParams = new HashMap();
- contentParams.put("charset", "UTF-8");
- cr.getHeaders().putSingle("Content-Type", new MediaType(contentType.getType(), contentType.getSubtype(), contentParams));
- }
// Call the next filter
ClientResponse resp = getNext().handle(cr);
String respContentType = resp.getHeaders().getFirst("Content-Type");
@@ -33,4 +23,4 @@ public ClientResponse handle(ClientRequest cr) {
return resp;
}
-}
\ No newline at end of file
+}
diff --git a/src/main/resources/docker.io.properties b/src/main/resources/docker.io.properties
new file mode 100644
index 00000000..0ce162bd
--- /dev/null
+++ b/src/main/resources/docker.io.properties
@@ -0,0 +1,2 @@
+docker.io.url=http://localhost:4243
+docker.io.version=1.11
\ No newline at end of file
diff --git a/src/test/java/com/kpelykh/docker/client/test/AbstractDockerClientTest.java b/src/test/java/com/kpelykh/docker/client/test/AbstractDockerClientTest.java
new file mode 100644
index 00000000..d8313ca4
--- /dev/null
+++ b/src/test/java/com/kpelykh/docker/client/test/AbstractDockerClientTest.java
@@ -0,0 +1,92 @@
+package com.kpelykh.docker.client.test;
+
+import com.kpelykh.docker.client.DockerClient;
+import com.kpelykh.docker.client.DockerException;
+import com.sun.jersey.api.client.ClientResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.ITestResult;
+
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
+public abstract class AbstractDockerClientTest extends Assert {
+
+ public static final Logger LOG = LoggerFactory
+ .getLogger(AbstractDockerClientTest.class);
+
+ protected DockerClient dockerClient;
+
+ protected List tmpImgs;
+ protected List tmpContainers;
+
+
+ public void beforeTest() throws DockerException {
+ LOG.info("======================= BEFORETEST =======================");
+ String url = System.getProperty("docker.url", "http://localhost:4243");
+ LOG.info("Connecting to Docker server at " + url);
+ dockerClient = new DockerClient(url);
+
+ LOG.info("Pulling image 'busybox'");
+ // need to block until image is pulled completely
+ logResponseStream(dockerClient.pull("busybox"));
+
+
+
+ assertNotNull(dockerClient);
+ LOG.info("======================= END OF BEFORETEST =======================\n\n");
+ }
+
+ public void afterTest() {
+ LOG.info("======================= END OF AFTERTEST =======================");
+ }
+
+
+ public void beforeMethod(Method method) {
+ tmpContainers = new ArrayList();
+ tmpImgs = new ArrayList();
+ LOG.info(String
+ .format("################################## STARTING %s ##################################",
+ method.getName()));
+ }
+
+ public void afterMethod(ITestResult result) {
+
+ for (String container : tmpContainers) {
+ LOG.info("Cleaning up temporary container {}", container);
+ try {
+ dockerClient.stopContainer(container);
+ dockerClient.kill(container);
+ dockerClient.removeContainer(container);
+ } catch (DockerException ignore) {
+ }
+ }
+
+ for (String image : tmpImgs) {
+ LOG.info("Cleaning up temporary image {}", image);
+ try {
+ dockerClient.removeImage(image);
+ } catch (DockerException ignore) {
+ }
+ }
+
+ LOG.info(
+ "################################## END OF {} ##################################\n",
+ result.getName());
+ }
+
+ protected String logResponseStream(ClientResponse response) {
+ String responseString;
+ try {
+ responseString = DockerClient.asString(response);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ LOG.info("Container log: {}", responseString);
+ return responseString;
+ }
+
+}
diff --git a/src/test/java/com/kpelykh/docker/client/test/DockerClientAuthTest.java b/src/test/java/com/kpelykh/docker/client/test/DockerClientAuthTest.java
new file mode 100644
index 00000000..8c7fc4fa
--- /dev/null
+++ b/src/test/java/com/kpelykh/docker/client/test/DockerClientAuthTest.java
@@ -0,0 +1,51 @@
+package com.kpelykh.docker.client.test;
+
+import com.kpelykh.docker.client.DockerException;
+import com.sun.jersey.api.client.UniformInterfaceException;
+
+import org.hamcrest.Matchers;
+import org.testng.ITestResult;
+import org.testng.annotations.*;
+
+import java.lang.reflect.Method;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class DockerClientAuthTest extends AbstractDockerClientTest {
+
+ @BeforeTest
+ public void beforeTest() throws DockerException {
+ super.beforeTest();
+ }
+ @AfterTest
+ public void afterTest() {
+ super.afterTest();
+ }
+
+ @BeforeMethod
+ public void beforeMethod(Method method) {
+ super.beforeMethod(method);
+ }
+
+ @AfterMethod
+ public void afterMethod(ITestResult result) {
+ super.afterMethod(result);
+ }
+
+ @Test
+ public void testAuth() throws Exception {
+ dockerClient.auth();
+ }
+
+ @Test
+ public void testAuthInvalid() throws Exception {
+ System.setProperty("docker.io.password", "garbage");
+ try {
+ dockerClient.auth();
+ fail();
+ } catch (DockerException e) {
+ assertThat(e.getCause(), Matchers.instanceOf(UniformInterfaceException.class));
+ assertEquals(((UniformInterfaceException) e.getCause()).getResponse().getStatus(), 401);
+ }
+ }
+}
diff --git a/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java b/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java
index 06656efa..f6af3823 100644
--- a/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java
+++ b/src/test/java/com/kpelykh/docker/client/test/DockerClientTest.java
@@ -1,777 +1,824 @@
package com.kpelykh.docker.client.test;
-import com.kpelykh.docker.client.DockerClient;
-import com.kpelykh.docker.client.DockerException;
-import com.kpelykh.docker.client.model.*;
+import static ch.lambdaj.Lambda.filter;
+import static ch.lambdaj.Lambda.selectUnique;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.endsWith;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.isEmptyString;
+import static org.hamcrest.Matchers.lessThan;
+import static org.hamcrest.Matchers.lessThanOrEqualTo;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
+import static org.hamcrest.Matchers.startsWith;
+import static org.testinfected.hamcrest.jpa.HasFieldWithValue.hasField;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.lang.reflect.Method;
+import java.net.DatagramSocket;
+import java.net.ServerSocket;
+import java.util.List;
+import java.util.Random;
-import com.sun.jersey.api.client.ClientResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang.math.RandomUtils;
import org.hamcrest.Matcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.testng.Assert;
import org.testng.ITestResult;
-import org.testng.annotations.*;
-
-import java.io.*;
-import java.lang.reflect.Method;
-import java.net.DatagramSocket;
-import java.net.ServerSocket;
-import java.util.ArrayList;
-import java.util.List;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.AfterTest;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
-import static ch.lambdaj.Lambda.filter;
-import static ch.lambdaj.Lambda.selectUnique;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.*;
-import static org.hamcrest.Matchers.hasItem;
-import static org.testinfected.hamcrest.jpa.HasFieldWithValue.hasField;
+import com.kpelykh.docker.client.DockerException;
+import com.kpelykh.docker.client.model.ChangeLog;
+import com.kpelykh.docker.client.model.CommitConfig;
+import com.kpelykh.docker.client.model.Container;
+import com.kpelykh.docker.client.model.ContainerConfig;
+import com.kpelykh.docker.client.model.ContainerCreateResponse;
+import com.kpelykh.docker.client.model.ContainerInspectResponse;
+import com.kpelykh.docker.client.model.Image;
+import com.kpelykh.docker.client.model.ImageInspectResponse;
+import com.kpelykh.docker.client.model.Info;
+import com.kpelykh.docker.client.model.Ports;
+import com.kpelykh.docker.client.model.SearchItem;
+import com.kpelykh.docker.client.model.Version;
+import com.sun.jersey.api.client.ClientResponse;
/**
* Unit test for DockerClient.
+ *
* @author Konstantin Pelykh (kpelykh@gmail.com)
*/
-public class DockerClientTest extends Assert
-{
- public static final Logger LOG = LoggerFactory.getLogger(DockerClientTest.class);
-
- private DockerClient dockerClient;
-
- private List tmpImgs = new ArrayList();
- private List tmpContainers = new ArrayList();
-
- @BeforeTest
- public void beforeTest() throws DockerException {
- LOG.info("======================= BEFORETEST =======================");
- String url = System.getProperty("docker.url", "http://localhost:4243");
- LOG.info("Connecting to Docker server at " + url);
- dockerClient = new DockerClient(url);
-
- LOG.info("Creating image 'busybox'");
- dockerClient.pull("busybox");
-
- assertNotNull(dockerClient);
- LOG.info("======================= END OF BEFORETEST =======================\n\n");
- }
+public class DockerClientTest extends AbstractDockerClientTest {
+ public static final Logger LOG = LoggerFactory
+ .getLogger(DockerClientTest.class);
+
+ @BeforeTest
+ public void beforeTest() throws DockerException {
+ super.beforeTest();
+ }
+ @AfterTest
+ public void afterTest() {
+ super.afterTest();
+ }
+
+ @BeforeMethod
+ public void beforeMethod(Method method) {
+ super.beforeMethod(method);
+ }
+
+ @AfterMethod
+ public void afterMethod(ITestResult result) {
+ super.afterMethod(result);
+ }
+
+ /*
+ * ######################### ## INFORMATION TESTS ##
+ * #########################
+ */
+
+ @Test
+ public void testDockerVersion() throws DockerException {
+ Version version = dockerClient.version();
+ LOG.info(version.toString());
+
+ assertTrue(version.getGoVersion().length() > 0);
+ assertTrue(version.getVersion().length() > 0);
+
+ assertEquals(StringUtils.split(version.getVersion(), ".").length, 3);
+
+ }
+
+ @Test
+ public void testDockerInfo() throws DockerException {
+ Info dockerInfo = dockerClient.info();
+ LOG.info(dockerInfo.toString());
+
+ assertTrue(dockerInfo.toString().contains("containers"));
+ assertTrue(dockerInfo.toString().contains("images"));
+ assertTrue(dockerInfo.toString().contains("debug"));
+
+ assertTrue(dockerInfo.getContainers() > 0);
+ assertTrue(dockerInfo.getImages() > 0);
+ assertTrue(dockerInfo.getNFd() > 0);
+ assertTrue(dockerInfo.getNGoroutines() > 0);
+ assertTrue(dockerInfo.isMemoryLimit());
+ }
+
+ @Test
+ public void testDockerSearch() throws DockerException {
+ List dockerSearch = dockerClient.search("busybox");
+ LOG.info("Search returned {}", dockerSearch.toString());
+
+ Matcher matcher = hasItem(hasField("name", equalTo("busybox")));
+ assertThat(dockerSearch, matcher);
+
+ assertThat(
+ filter(hasField("name", is("busybox")), dockerSearch).size(),
+ equalTo(1));
+ }
+
+ /*
+ * ################### ## LISTING TESTS ## ###################
+ */
+
+ @Test
+ public void testImages() throws DockerException {
+ List images = dockerClient.getImages(true);
+ assertThat(images, notNullValue());
+ LOG.info("Images List: {}", images);
+ Info info = dockerClient.info();
+
+ assertThat(images.size(), equalTo(info.getImages()));
+
+ Image img = images.get(0);
+ assertThat(img.getCreated(), is(greaterThan(0L)));
+ assertThat(img.getVirtualSize(), is(greaterThan(0L)));
+ assertThat(img.getId(), not(isEmptyString()));
+ assertThat(img.getTag(), not(isEmptyString()));
+ assertThat(img.getRepository(), not(isEmptyString()));
+ }
+
+ @Test
+ public void testListContainers() throws DockerException {
+
+ String testImage = "hackmann/empty";
+
+ LOG.info("Pulling image 'hackmann/empty'");
+ // need to block until image is pulled completely
+ logResponseStream(dockerClient.pull(testImage));
+ tmpImgs.add(testImage);
+
+ List containers = dockerClient.listContainers(true);
+ assertThat(containers, notNullValue());
+ LOG.info("Container List: {}", containers);
+
+ int size = containers.size();
+
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage(testImage);
+ containerConfig.setCmd(new String[] { "echo" });
+
+ ContainerCreateResponse container1 = dockerClient
+ .createContainer(containerConfig);
+
+ assertThat(container1.getId(), not(isEmptyString()));
+
+ ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container1.getId());
+
+ assertThat(containerInspectResponse.getConfig().getImage(), is(equalTo(testImage)));
+
+
+ dockerClient.startContainer(container1.getId());
+ tmpContainers.add(container1.getId());
+
+ LOG.info("container id: " + container1.getId());
+
+ List containers2 = dockerClient.listContainers(true);
+
+ for(Container container: containers2) {
+ LOG.info("listContainer: id=" + container.getId() +" image=" + container.getImage());
+ }
+
+ assertThat(size + 1, is(equalTo(containers2.size())));
+ Matcher matcher = hasItem(hasField("id", startsWith(container1.getId())));
+ assertThat(containers2, matcher);
+
+ List filteredContainers = filter(
+ hasField("id", startsWith(container1.getId())), containers2);
+ assertThat(filteredContainers.size(), is(equalTo(1)));
+
+ for(Container container: filteredContainers) {
+ LOG.info("filteredContainer: " + container.getImage());
+ }
+
+ Container container2 = filteredContainers.get(0);
+ assertThat(container2.getCommand(), not(isEmptyString()));
+ assertThat(container2.getImage(), equalTo(testImage + ":latest"));
+ }
+
+ /*
+ * ##################### ## CONTAINER TESTS ## #####################
+ */
+
+ @Test
+ public void testCreateContainer() throws DockerException {
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(new String[] { "true" });
+
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+
+ LOG.info("Created container {}", container.toString());
+
+ assertThat(container.getId(), not(isEmptyString()));
+
+ tmpContainers.add(container.getId());
+ }
+
+ @Test
+ public void testStartContainer() throws DockerException {
+
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(new String[] { "true" });
+
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+ LOG.info("Created container {}", container.toString());
+ assertThat(container.getId(), not(isEmptyString()));
+ boolean add = tmpContainers.add(container.getId());
+
+ dockerClient.startContainer(container.getId());
+
+ ContainerInspectResponse containerInspectResponse = dockerClient
+ .inspectContainer(container.getId());
+ LOG.info("Container Inspect: {}", containerInspectResponse.toString());
+
+ assertThat(containerInspectResponse.config, is(notNullValue()));
+ assertThat(containerInspectResponse.getId(), not(isEmptyString()));
+
+ assertThat(containerInspectResponse.getId(),
+ startsWith(container.getId()));
+
+ assertThat(containerInspectResponse.getImageId(), not(isEmptyString()));
+ assertThat(containerInspectResponse.getState(), is(notNullValue()));
- @AfterTest
- public void afterTest() {
- LOG.info("======================= END OF AFTERTEST =======================");
- }
+ assertThat(containerInspectResponse.getState().running, is(true));
- @BeforeMethod
- public void beforeMethod(Method method) {
- LOG.info(String.format("################################## STARTING %s ##################################", method.getName()));
- }
+ if (!containerInspectResponse.getState().running) {
+ assertThat(containerInspectResponse.getState().exitCode,
+ is(equalTo(0)));
+ }
- @AfterMethod
- public void afterMethod(ITestResult result) {
-
- for (String container : tmpContainers) {
- LOG.info("Cleaning up temporary container {}", container);
- try {
- dockerClient.stopContainer(container);
- dockerClient.kill(container);
- dockerClient.removeContainer(container);
- } catch (DockerException ignore) {}
- }
-
- for (String image : tmpImgs) {
- LOG.info("Cleaning up temporary image {}", image);
- try {
- dockerClient.removeImage(image);
- } catch (DockerException ignore) {}
- }
-
- LOG.info("################################## END OF {} ##################################\n", result.getName());
- }
+ }
- /*
- * #########################
- * ## INFORMATION TESTS ##
- * #########################
- */
+ @Test
+ public void testWaitContainer() throws DockerException {
- @Test
- public void testDockerVersion() throws DockerException {
- Version version = dockerClient.version();
- LOG.info(version.toString());
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(new String[] { "true" });
- assertTrue(version.getGoVersion().length() > 0);
- assertTrue(version.getVersion().length() > 0);
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+ LOG.info("Created container: {}", container.toString());
+ assertThat(container.getId(), not(isEmptyString()));
+ tmpContainers.add(container.getId());
- assertEquals(StringUtils.split(version.getVersion(), ".").length, 3);
+ dockerClient.startContainer(container.getId());
- }
+ int exitCode = dockerClient.waitContainer(container.getId());
+ LOG.info("Container exit code: {}", exitCode);
- @Test
- public void testDockerInfo() throws DockerException {
- Info dockerInfo = dockerClient.info();
- LOG.info(dockerInfo.toString());
-
- assertTrue(dockerInfo.toString().contains("containers"));
- assertTrue(dockerInfo.toString().contains("images"));
- assertTrue(dockerInfo.toString().contains("debug"));
-
- assertTrue(dockerInfo.getContainers() > 0);
- assertTrue(dockerInfo.getImages() > 0);
- assertTrue(dockerInfo.getNFd() > 0);
- assertTrue(dockerInfo.getNGoroutines() > 0);
- assertTrue(dockerInfo.isMemoryLimit());
- }
+ assertThat(exitCode, equalTo(0));
- @Test
- public void testDockerSearch() throws DockerException {
- List dockerSearch = dockerClient.search("busybox");
- LOG.info("Search returned {}", dockerSearch.toString());
+ ContainerInspectResponse containerInspectResponse = dockerClient
+ .inspectContainer(container.getId());
+ LOG.info("Container Inspect: {}", containerInspectResponse.toString());
- Matcher matcher = hasItem(hasField("name", equalTo("busybox")));
- assertThat(dockerSearch, matcher);
+ assertThat(containerInspectResponse.getState().running,
+ is(equalTo(false)));
+ assertThat(containerInspectResponse.getState().exitCode,
+ is(equalTo(exitCode)));
- assertThat(filter(hasField("name", is("busybox")), dockerSearch).size(), equalTo(1));
- }
+ }
- /*
- * ###################
- * ## LISTING TESTS ##
- * ###################
- */
+ @Test
+ public void testLogs() throws DockerException, IOException {
+ String snippet = "hello world";
- @Test
- public void testImages() throws DockerException {
- List images = dockerClient.getImages(true);
- assertThat(images, notNullValue());
- LOG.info("Images List: {}", images);
- Info info = dockerClient.info();
-
- assertThat(images.size(), equalTo(info.getImages()));
-
- Image img = images.get(0);
- assertThat(img.getCreated(), is(greaterThan(0L)) );
- assertThat(img.getVirtualSize(), is(greaterThan(0L)) );
- assertThat(img.getId(), not(isEmptyString()));
- assertThat(img.getTag(), not(isEmptyString()));
- assertThat(img.getRepository(), not(isEmptyString()));
- }
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(new String[] { "/bin/echo", snippet });
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+ LOG.info("Created container: {}", container.toString());
+ assertThat(container.getId(), not(isEmptyString()));
- @Test
- public void testListContainers() throws DockerException {
- List containers = dockerClient.listContainers(true);
- assertThat(containers, notNullValue());
- LOG.info("Container List: {}", containers);
+ dockerClient.startContainer(container.getId());
+ tmpContainers.add(container.getId());
- int size = containers.size();
+ int exitCode = dockerClient.waitContainer(container.getId());
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[]{"echo"});
+ assertThat(exitCode, equalTo(0));
- ContainerCreateResponse container1 = dockerClient.createContainer(containerConfig);
- assertThat(container1.getId(), not(isEmptyString()));
- dockerClient.startContainer(container1.getId());
- tmpContainers.add(container1.getId());
+ ClientResponse response = dockerClient.logContainer(container.getId());
- List containers2 = dockerClient.listContainers(true);
- assertThat(size + 1, is(equalTo(containers2.size())));
- Matcher matcher = hasItem(hasField("id", startsWith(container1.getId())));
- assertThat(containers2, matcher);
+ assertThat(logResponseStream(response), endsWith(snippet));
+ }
- List filteredContainers = filter(hasField("id", startsWith(container1.getId())), containers2);
- assertThat(filteredContainers.size(), is(equalTo(1)));
+ @Test
+ public void testDiff() throws DockerException {
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(new String[] { "touch", "/test" });
- Container container2 = filteredContainers.get(0);
- assertThat(container2.getCommand(), not(isEmptyString()));
- assertThat(container2.getImage(), equalTo("busybox:latest"));
- }
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+ LOG.info("Created container: {}", container.toString());
+ assertThat(container.getId(), not(isEmptyString()));
+ dockerClient.startContainer(container.getId());
+ boolean add = tmpContainers.add(container.getId());
+ int exitCode = dockerClient.waitContainer(container.getId());
+ assertThat(exitCode, equalTo(0));
+ List filesystemDiff = dockerClient.containerDiff(container.getId());
+ LOG.info("Container DIFF: {}", filesystemDiff.toString());
- /*
- * #####################
- * ## CONTAINER TESTS ##
- * #####################
- */
+ assertThat(filesystemDiff.size(), equalTo(1));
+ ChangeLog testChangeLog = selectUnique(filesystemDiff,
+ hasField("path", equalTo("/test")));
- @Test
- public void testCreateContainer() throws DockerException {
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[]{"true"});
+ assertThat(testChangeLog, hasField("path", equalTo("/test")));
+ assertThat(testChangeLog, hasField("kind", equalTo(1)));
+ }
+ @Test
+ public void testStopContainer() throws DockerException {
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(new String[] { "sleep", "9999" });
- LOG.info("Created container {}", container.toString());
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+ LOG.info("Created container: {}", container.toString());
+ assertThat(container.getId(), not(isEmptyString()));
+ dockerClient.startContainer(container.getId());
+ tmpContainers.add(container.getId());
- assertThat(container.getId(), not(isEmptyString()));
+ LOG.info("Stopping container: {}", container.getId());
+ dockerClient.stopContainer(container.getId(), 2);
- tmpContainers.add(container.getId());
- }
+ ContainerInspectResponse containerInspectResponse = dockerClient
+ .inspectContainer(container.getId());
+ LOG.info("Container Inspect: {}", containerInspectResponse.toString());
- @Test
- public void testStartContainer() throws DockerException {
+ assertThat(containerInspectResponse.getState().running,
+ is(equalTo(false)));
+ assertThat(containerInspectResponse.getState().exitCode,
+ not(equalTo(0)));
+ }
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[]{"true"});
+ @Test
+ public void testKillContainer() throws DockerException {
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
- LOG.info("Created container {}", container.toString());
- assertThat(container.getId(), not(isEmptyString()));
- boolean add = tmpContainers.add(container.getId());
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(new String[] { "sleep", "9999" });
- dockerClient.startContainer(container.getId());
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+ LOG.info("Created container: {}", container.toString());
+ assertThat(container.getId(), not(isEmptyString()));
+ dockerClient.startContainer(container.getId());
+ tmpContainers.add(container.getId());
- ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container.getId());
- LOG.info("Container Inspect: {}", containerInspectResponse.toString());
+ LOG.info("Killing container: {}", container.getId());
+ dockerClient.kill(container.getId());
- assertThat(containerInspectResponse.config, is(notNullValue()));
- assertThat(containerInspectResponse.getId(), not(isEmptyString()));
+ ContainerInspectResponse containerInspectResponse = dockerClient
+ .inspectContainer(container.getId());
+ LOG.info("Container Inspect: {}", containerInspectResponse.toString());
- assertThat(containerInspectResponse.getId(), startsWith(container.getId()));
+ assertThat(containerInspectResponse.getState().running,
+ is(equalTo(false)));
+ assertThat(containerInspectResponse.getState().exitCode,
+ not(equalTo(0)));
- assertThat(containerInspectResponse.getImage(), not(isEmptyString()));
- assertThat(containerInspectResponse.getState(), is(notNullValue()));
+ }
- assertThat(containerInspectResponse.getState().running, is(true));
+ @Test
+ public void restartContainer() throws DockerException {
- if (!containerInspectResponse.getState().running) {
- assertThat(containerInspectResponse.getState().exitCode, is(equalTo(0)));
- }
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(new String[] { "sleep", "9999" });
- }
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+ LOG.info("Created container: {}", container.toString());
+ assertThat(container.getId(), not(isEmptyString()));
+ dockerClient.startContainer(container.getId());
+ tmpContainers.add(container.getId());
- @Test
- public void testWaitContainer() throws DockerException {
+ ContainerInspectResponse containerInspectResponse = dockerClient
+ .inspectContainer(container.getId());
+ LOG.info("Container Inspect: {}", containerInspectResponse.toString());
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[]{"true"});
+ String startTime = containerInspectResponse.getState().startedAt;
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
- LOG.info("Created container: {}", container.toString());
- assertThat(container.getId(), not(isEmptyString()));
- tmpContainers.add(container.getId());
+ dockerClient.restart(container.getId(), 2);
- dockerClient.startContainer(container.getId());
+ ContainerInspectResponse containerInspectResponse2 = dockerClient
+ .inspectContainer(container.getId());
+ LOG.info("Container Inspect After Restart: {}",
+ containerInspectResponse2.toString());
- int exitCode = dockerClient.waitContainer(container.getId());
- LOG.info("Container exit code: {}", exitCode);
+ String startTime2 = containerInspectResponse2.getState().startedAt;
- assertThat(exitCode, equalTo(0));
+ assertThat(startTime, not(equalTo(startTime2)));
- ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container.getId());
- LOG.info("Container Inspect: {}", containerInspectResponse.toString());
+ assertThat(containerInspectResponse.getState().running,
+ is(equalTo(true)));
- assertThat(containerInspectResponse.getState().running, is(equalTo(false)));
- assertThat(containerInspectResponse.getState().exitCode, is(equalTo(exitCode)));
+ dockerClient.kill(container.getId());
+ }
- }
+ @Test
+ public void removeContainer() throws DockerException {
- @Test
- public void testLogs() throws DockerException, IOException {
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(new String[] { "true" });
- String snippet = "hello world";
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[] {"/bin/echo", snippet});
+ dockerClient.startContainer(container.getId());
+ dockerClient.waitContainer(container.getId());
+ tmpContainers.add(container.getId());
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
- LOG.info("Created container: {}", container.toString());
- assertThat(container.getId(), not(isEmptyString()));
+ LOG.info("Removing container: {}", container.getId());
+ dockerClient.removeContainer(container.getId());
- dockerClient.startContainer(container.getId());
- tmpContainers.add(container.getId());
+ List containers2 = dockerClient.listContainers(true);
+ Matcher matcher = not(hasItem(hasField("id",
+ startsWith(container.getId()))));
+ assertThat(containers2, matcher);
- int exitCode = dockerClient.waitContainer(container.getId());
+ }
- assertThat(exitCode, equalTo(0));
+ /*
+ * ################## ## IMAGES TESTS ## ##################
+ */
- ClientResponse response = dockerClient.logContainer(container.getId());
+ @Test
+ public void testPullImage() throws DockerException, IOException {
- StringWriter logwriter = new StringWriter();
+ // This should be an image that is not used by other repositories already
+ // pulled down, preferably small in size. If tag is not used pull will
+ // download all images in that repository but tmpImgs will only
+ // deleted 'latest' image but not images with other tags
+ String testImage = "hackmann/empty";
- try {
- LineIterator itr = IOUtils.lineIterator(response.getEntityInputStream(), "UTF-8");
- while (itr.hasNext()) {
- String line = itr.next();
- logwriter.write(line + (itr.hasNext() ? "\n" : ""));
- LOG.info(line);
- }
- } finally {
- IOUtils.closeQuietly(response.getEntityInputStream());
- }
+ LOG.info("Removing image: {}", testImage);
+ dockerClient.removeImage(testImage);
- String fullLog = logwriter.toString();
+ Info info = dockerClient.info();
+ LOG.info("Client info: {}", info.toString());
- LOG.info("Container log: {}", fullLog);
- assertThat(fullLog, endsWith(snippet));
- }
+ int imgCount = info.getImages();
- @Test
- public void testDiff() throws DockerException {
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[] {"touch", "/test"});
-
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
- LOG.info("Created container: {}", container.toString());
- assertThat(container.getId(), not(isEmptyString()));
- dockerClient.startContainer(container.getId());
- boolean add = tmpContainers.add(container.getId());
- int exitCode = dockerClient.waitContainer(container.getId());
- assertThat(exitCode, equalTo(0));
-
- List filesystemDiff = dockerClient.containterDiff(container.getId());
- LOG.info("Container DIFF: {}", filesystemDiff.toString());
-
- assertThat(filesystemDiff.size(), equalTo(3));
- ChangeLog testChangeLog = selectUnique(filesystemDiff, hasField("path", equalTo("/test")));
-
- assertThat(testChangeLog, hasField("path", equalTo("/test")));
- assertThat(testChangeLog, hasField("kind", equalTo(1)));
- }
+ LOG.info("Pulling image: {}", testImage);
- @Test
- public void testStopContainer() throws DockerException {
-
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[] {"sleep", "9999"});
+ tmpImgs.add(testImage);
+ ClientResponse response = dockerClient.pull(testImage);
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
- LOG.info("Created container: {}", container.toString());
- assertThat(container.getId(), not(isEmptyString()));
- dockerClient.startContainer(container.getId());
- tmpContainers.add(container.getId());
+ assertThat(logResponseStream(response), containsString("Download complete"));
- LOG.info("Stopping container: {}", container.getId());
- dockerClient.stopContainer(container.getId(), 2);
+ info = dockerClient.info();
+ LOG.info("Client info after pull, {}", info.toString());
- ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container.getId());
- LOG.info("Container Inspect: {}", containerInspectResponse.toString());
+ // TODO: imgCount should differ (maybe a docker bug?)
+ assertThat(imgCount, lessThanOrEqualTo(info.getImages()));
- assertThat(containerInspectResponse.getState().running, is(equalTo(false)));
- assertThat(containerInspectResponse.getState().exitCode, not(equalTo(0)));
- }
-
- @Test
- public void testKillContainer() throws DockerException {
+ ImageInspectResponse imageInspectResponse = dockerClient
+ .inspectImage(testImage);
+ LOG.info("Image Inspect: {}", imageInspectResponse.toString());
+ assertThat(imageInspectResponse, notNullValue());
+ }
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[] {"sleep", "9999"});
+ @Test
+ public void commitImage() throws DockerException {
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
- LOG.info("Created container: {}", container.toString());
- assertThat(container.getId(), not(isEmptyString()));
- dockerClient.startContainer(container.getId());
- tmpContainers.add(container.getId());
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(new String[] { "touch", "/test" });
- LOG.info("Killing container: {}", container.getId());
- dockerClient.kill(container.getId());
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+ LOG.info("Created container: {}", container.toString());
+ assertThat(container.getId(), not(isEmptyString()));
+ dockerClient.startContainer(container.getId());
+ tmpContainers.add(container.getId());
- ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container.getId());
- LOG.info("Container Inspect: {}", containerInspectResponse.toString());
+ LOG.info("Commiting container: {}", container.toString());
+ String imageId = dockerClient
+ .commit(new CommitConfig(container.getId()));
+ tmpImgs.add(imageId);
- assertThat(containerInspectResponse.getState().running, is(equalTo(false)));
- assertThat(containerInspectResponse.getState().exitCode, not(equalTo(0)));
-
- }
+ ImageInspectResponse imageInspectResponse = dockerClient
+ .inspectImage(imageId);
+ LOG.info("Image Inspect: {}", imageInspectResponse.toString());
+
+ assertThat(imageInspectResponse,
+ hasField("container", startsWith(container.getId())));
+ assertThat(imageInspectResponse.getContainerConfig().getImage(),
+ equalTo("busybox"));
+
+ ImageInspectResponse busyboxImg = dockerClient.inspectImage("busybox");
+
+ assertThat(imageInspectResponse.getParent(),
+ equalTo(busyboxImg.getId()));
+ }
+
+ @Test
+ public void testRemoveImage() throws DockerException, InterruptedException {
+
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(new String[] { "touch", "/test" });
+
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+ LOG.info("Created container: {}", container.toString());
+ assertThat(container.getId(), not(isEmptyString()));
+ dockerClient.startContainer(container.getId());
+ tmpContainers.add(container.getId());
+
+ LOG.info("Commiting container {}", container.toString());
+ String imageId = dockerClient
+ .commit(new CommitConfig(container.getId()));
+ tmpImgs.add(imageId);
+
+ dockerClient.stopContainer(container.getId());
+ dockerClient.kill(container.getId());
+ dockerClient.removeContainer(container.getId());
+
+ tmpContainers.remove(container.getId());
+ LOG.info("Removing image: {}", imageId);
+ dockerClient.removeImage(imageId);
+
+ List containers = dockerClient.listContainers(true);
+ Matcher matcher = not(hasItem(hasField("id", startsWith(imageId))));
+ assertThat(containers, matcher);
+ }
+
+ @Test
+ public void testTagImage() throws DockerException, InterruptedException {
+ String tag = String.valueOf(RandomUtils.nextInt(Integer.MAX_VALUE));
+
+ Integer result = dockerClient.tag("busybox:latest", "docker-java/busybox", tag, false);
+ assertThat(result, equalTo(Integer.valueOf(201)));
+
+ dockerClient.removeImage("docker-java/busybox:" + tag);
+ }
+
+ /*
+ *
+ * ################ ## MISC TESTS ## ################
+ */
+
+ @Test
+ public void testRunShlex() throws DockerException {
+
+ String[] commands = new String[] {
+ "true",
+ "echo \"The Young Descendant of Tepes & Septette for the Dead Princess\"",
+ "echo -n 'The Young Descendant of Tepes & Septette for the Dead Princess'",
+ "/bin/sh -c echo Hello World", "/bin/sh -c echo 'Hello World'",
+ "echo 'Night of Nights'", "true && echo 'Night of Nights'" };
+
+ for (String command : commands) {
+ LOG.info("Running command: [{}]", command);
+
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(commands);
+
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+ dockerClient.startContainer(container.getId());
+ tmpContainers.add(container.getId());
+ int exitcode = dockerClient.waitContainer(container.getId());
+ assertThat(exitcode, equalTo(0));
+ }
+ }
+
+ @Test
+ public void testNginxDockerfileBuilder() throws DockerException,
+ IOException {
+ File baseDir = new File(Thread.currentThread().getContextClassLoader()
+ .getResource("nginx").getFile());
+
+ ClientResponse response = dockerClient.build(baseDir);
+
+ StringWriter logwriter = new StringWriter();
+
+ try {
+ LineIterator itr = IOUtils.lineIterator(
+ response.getEntityInputStream(), "UTF-8");
+ while (itr.hasNext()) {
+ String line = itr.next();
+ logwriter.write(line + "\n");
+ LOG.info(line);
+ }
+ } finally {
+ IOUtils.closeQuietly(response.getEntityInputStream());
+ }
+
+ String fullLog = logwriter.toString();
+ assertThat(fullLog, containsString("Successfully built"));
+
+ String imageId = StringUtils.substringBetween(fullLog,
+ "Successfully built ", "\\n\"}").trim();
+
+ ImageInspectResponse imageInspectResponse = dockerClient
+ .inspectImage(imageId);
+ assertThat(imageInspectResponse, not(nullValue()));
+ LOG.info("Image Inspect: {}", imageInspectResponse.toString());
+ tmpImgs.add(imageInspectResponse.getId());
+
+ assertThat(imageInspectResponse.getAuthor(),
+ equalTo("Guillaume J. Charmes \"guillaume@dotcloud.com\""));
+ }
+
+ @Test
+ public void testDockerBuilderAddUrl() throws DockerException, IOException {
+ File baseDir = new File(Thread.currentThread().getContextClassLoader()
+ .getResource("testAddUrl").getFile());
+ dockerfileBuild(baseDir, "docker.io");
+ }
@Test
- public void restartContainer() throws DockerException {
-
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[] {"sleep", "9999"});
-
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
- LOG.info("Created container: {}", container.toString());
- assertThat(container.getId(), not(isEmptyString()));
- dockerClient.startContainer(container.getId());
- tmpContainers.add(container.getId());
-
- ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container.getId());
- LOG.info("Container Inspect: {}", containerInspectResponse.toString());
-
- String startTime = containerInspectResponse.getState().startedAt;
-
- dockerClient.restart(container.getId(), 2);
-
- ContainerInspectResponse containerInspectResponse2 = dockerClient.inspectContainer(container.getId());
- LOG.info("Container Inspect After Restart: {}", containerInspectResponse2.toString());
-
- String startTime2 = containerInspectResponse2.getState().startedAt;
-
- assertThat(startTime, not(equalTo(startTime2)));
-
- assertThat(containerInspectResponse.getState().running, is(equalTo(true)));
-
- dockerClient.kill(container.getId());
- }
-
- @Test
- public void removeContainer() throws DockerException {
-
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[] {"true"});
-
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
-
- dockerClient.startContainer(container.getId());
- dockerClient.waitContainer(container.getId());
- tmpContainers.add(container.getId());
-
- LOG.info("Removing container: {}", container.getId());
- dockerClient.removeContainer(container.getId());
-
- List containers2 = dockerClient.listContainers(true);
- Matcher matcher = not(hasItem(hasField("id", startsWith(container.getId()))));
- assertThat(containers2, matcher);
-
+ public void testDockerBuilderAddFileInSubfolder() throws DockerException, IOException {
+ File baseDir = new File(Thread.currentThread().getContextClassLoader()
+ .getResource("testAddFileInSubfolder").getFile());
+ dockerfileBuild(baseDir, "Successfully executed testrun.sh");
}
- /*
- * ##################
- * ## IMAGES TESTS ##
- * ##################
- * */
-
- @Test
- public void testPullImage() throws DockerException, IOException {
-
- String testImage = "kpelykh/vimbase";
-
- LOG.info("Removing image: {}", testImage);
- dockerClient.removeImage(testImage);
-
- Info info = dockerClient.info();
- LOG.info("Client info: {}", info.toString());
-
- int imgCount= info.getImages();
-
- LOG.info("Pulling image: {}", testImage);
-
- ClientResponse response = dockerClient.pull(testImage);
-
- StringWriter logwriter = new StringWriter();
-
- try {
- LineIterator itr = IOUtils.lineIterator(response.getEntityInputStream(), "UTF-8");
- while (itr.hasNext()) {
- String line = itr.next();
- logwriter.write(line + "\n");
- LOG.info(line);
- }
- } finally {
- IOUtils.closeQuietly(response.getEntityInputStream());
- }
-
- String fullLog = logwriter.toString();
- assertThat(fullLog, containsString("Pulling repository kpelykh/vimbase"));
-
- tmpImgs.add(testImage);
-
- info = dockerClient.info();
- LOG.info("Client info after pull, {}", info.toString());
-
- assertThat(imgCount + 1, equalTo(info.getImages()));
-
- ImageInspectResponse imageInspectResponse = dockerClient.inspectImage(testImage);
- LOG.info("Image Inspect: {}", imageInspectResponse.toString());
- assertThat(imageInspectResponse, notNullValue());
- }
-
-
- @Test
- public void commitImage() throws DockerException {
-
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[] {"touch", "/test"});
-
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
- LOG.info("Created container: {}", container.toString());
- assertThat(container.getId(), not(isEmptyString()));
- dockerClient.startContainer(container.getId());
- tmpContainers.add(container.getId());
-
- LOG.info("Commiting container: {}", container.toString());
- String imageId = dockerClient.commit(new CommitConfig(container.getId()));
- tmpImgs.add(imageId);
-
- ImageInspectResponse imageInspectResponse = dockerClient.inspectImage(imageId);
- LOG.info("Image Inspect: {}", imageInspectResponse.toString());
-
- assertThat(imageInspectResponse, hasField("container", startsWith(container.getId())));
- assertThat(imageInspectResponse.getContainerConfig().getImage(), equalTo("busybox"));
-
- ImageInspectResponse busyboxImg = dockerClient.inspectImage("busybox");
-
- assertThat(imageInspectResponse.getParent(), equalTo(busyboxImg.getId()));
- }
-
- @Test
- public void testRemoveImage() throws DockerException, InterruptedException {
-
-
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd(new String[] {"touch", "/test"});
-
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
- LOG.info("Created container: {}", container.toString());
- assertThat(container.getId(), not(isEmptyString()));
- dockerClient.startContainer(container.getId());
- tmpContainers.add(container.getId());
-
- LOG.info("Commiting container {}", container.toString());
- String imageId = dockerClient.commit(new CommitConfig(container.getId()));
- tmpImgs.add(imageId);
-
- dockerClient.stopContainer(container.getId());
- dockerClient.kill(container.getId());
- dockerClient.removeContainer(container.getId());
-
- tmpContainers.remove(container.getId());
- LOG.info("Removing image: {}", imageId);
- dockerClient.removeImage(imageId);
-
- List containers = dockerClient.listContainers(true);
- Matcher matcher = not(hasItem(hasField("id", startsWith(imageId))));
- assertThat(containers, matcher);
- }
-
-
- /*
- *
- * ################
- * ## MISC TESTS ##
- * ################
- */
-
- @Test
- public void testRunShlex() throws DockerException {
-
- String[] commands = new String[] {
- "true",
- "echo \"The Young Descendant of Tepes & Septette for the Dead Princess\"",
- "echo -n 'The Young Descendant of Tepes & Septette for the Dead Princess'",
- "/bin/sh -c echo Hello World",
- "/bin/sh -c echo 'Hello World'",
- "echo 'Night of Nights'",
- "true && echo 'Night of Nights'"
- };
-
- for (String command : commands) {
- LOG.info("Running command: [{}]", command);
-
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage("busybox");
- containerConfig.setCmd( commands );
-
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
- dockerClient.startContainer(container.getId());
- tmpContainers.add(container.getId());
- int exitcode = dockerClient.waitContainer(container.getId());
- assertThat(exitcode, equalTo(0));
- }
- }
-
-
- @Test
- public void testNginxDockerfileBuilder() throws DockerException, IOException {
- File baseDir = new File(Thread.currentThread().getContextClassLoader().getResource("nginx").getFile());
-
- ClientResponse response = dockerClient.build(baseDir);
-
- StringWriter logwriter = new StringWriter();
-
- try {
- LineIterator itr = IOUtils.lineIterator(response.getEntityInputStream(), "UTF-8");
- while (itr.hasNext()) {
- String line = itr.next();
- logwriter.write(line + "\n");
- LOG.info(line);
- }
- } finally {
- IOUtils.closeQuietly(response.getEntityInputStream());
- }
-
- String fullLog = logwriter.toString();
- assertThat(fullLog, containsString("Successfully built"));
-
- String imageId = StringUtils.substringBetween(fullLog, "Successfully built ", "\\n\"}").trim();
-
- ImageInspectResponse imageInspectResponse = dockerClient.inspectImage(imageId);
- assertThat(imageInspectResponse, not(nullValue()));
- LOG.info("Image Inspect: {}", imageInspectResponse.toString());
- tmpImgs.add(imageInspectResponse.getId());
-
- assertThat(imageInspectResponse.getAuthor(), equalTo("Guillaume J. Charmes \"guillaume@dotcloud.com\""));
- }
-
- @Test
- public void testDockerBuilderAddFile() throws DockerException, IOException {
- File baseDir = new File(Thread.currentThread().getContextClassLoader().getResource("testAddFile").getFile());
- dockerfileBuild(baseDir, "Successfully executed testrun.sh");
- }
-
- @Test
- public void testDockerBuilderAddFolder() throws DockerException, IOException {
- File baseDir = new File(Thread.currentThread().getContextClassLoader().getResource("testAddFolder").getFile());
- dockerfileBuild(baseDir, "Successfully executed testAddFolder.sh");
- }
-
- @Test
- public void testNetCatDockerfileBuilder() throws DockerException, IOException, InterruptedException {
- File baseDir = new File(Thread.currentThread().getContextClassLoader().getResource("netcat").getFile());
-
- ClientResponse response = dockerClient.build(baseDir);
-
- StringWriter logwriter = new StringWriter();
-
- try {
- LineIterator itr = IOUtils.lineIterator(response.getEntityInputStream(), "UTF-8");
- while (itr.hasNext()) {
- String line = itr.next();
- logwriter.write(line + "\n");
- LOG.info(line);
- }
- } finally {
- IOUtils.closeQuietly(response.getEntityInputStream());
- }
-
- String fullLog = logwriter.toString();
- assertThat(fullLog, containsString("Successfully built"));
-
- String imageId = StringUtils.substringBetween(fullLog, "Successfully built ", "\\n\"}").trim();
-
- ImageInspectResponse imageInspectResponse = dockerClient.inspectImage(imageId);
- assertThat(imageInspectResponse, not(nullValue()));
- LOG.info("Image Inspect: {}", imageInspectResponse.toString());
- tmpImgs.add(imageInspectResponse.getId());
-
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage(imageInspectResponse.getId());
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
- assertThat(container.getId(), not(isEmptyString()));
- dockerClient.startContainer(container.getId());
- tmpContainers.add(container.getId());
-
- ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainer(container.getId());
-
- assertThat(containerInspectResponse.getId(), notNullValue());
- assertThat(containerInspectResponse.getNetworkSettings().ports, notNullValue());
-
- //No use as such if not running on the server
- for(String portstr : containerInspectResponse.getNetworkSettings().ports.getAllPorts().keySet()){
-
- Ports.Port p = containerInspectResponse.getNetworkSettings().ports.getAllPorts().get(portstr);
- int port = Integer.valueOf(p.getHostPort());
- LOG.info("Checking port {} is open", port);
- assertThat(available(port), is(false));
- }
- dockerClient.stopContainer(container.getId(), 0);
-
- }
-
-
- // UTIL
-
- /**
- * Checks to see if a specific port is available.
- *
- * @param port the port to check for availability
- */
- public static boolean available(int port) {
- if (port < 1100 || port > 60000) {
- throw new IllegalArgumentException("Invalid start port: " + port);
- }
-
- ServerSocket ss = null;
- DatagramSocket ds = null;
- try {
- ss = new ServerSocket(port);
- ss.setReuseAddress(true);
- ds = new DatagramSocket(port);
- ds.setReuseAddress(true);
- return true;
- } catch (IOException e) {
- } finally {
- if (ds != null) {
- ds.close();
- }
-
- if (ss != null) {
- try {
- ss.close();
- } catch (IOException e) {
- /* should not be thrown */
- }
- }
- }
-
- return false;
- }
-
- private void dockerfileBuild(File baseDir, String expectedText) throws DockerException, IOException {
-
- //Build image
- ClientResponse response = dockerClient.build(baseDir);
-
- StringWriter logwriter = new StringWriter();
-
- try {
- LineIterator itr = IOUtils.lineIterator(response.getEntityInputStream(), "UTF-8");
- while (itr.hasNext()) {
- String line = itr.next();
- logwriter.write(line + "\n");
- LOG.info(line);
- }
- } finally {
- IOUtils.closeQuietly(response.getEntityInputStream());
- }
-
- String fullLog = logwriter.toString();
- assertThat(fullLog, containsString("Successfully built"));
-
- String imageId = StringUtils.substringBetween(fullLog, "Successfully built ", "\\n\"}").trim();
-
- //Create container based on image
- ContainerConfig containerConfig = new ContainerConfig();
- containerConfig.setImage(imageId);
- ContainerCreateResponse container = dockerClient.createContainer(containerConfig);
- LOG.info("Created container: {}", container.toString());
- assertThat(container.getId(), not(isEmptyString()));
-
- dockerClient.startContainer(container.getId());
- dockerClient.waitContainer(container.getId());
-
- tmpContainers.add(container.getId());
-
- //Log container
- ClientResponse logResponse = dockerClient.logContainer(container.getId());
-
- StringWriter logwriter2 = new StringWriter();
-
- try {
- LineIterator itr = IOUtils.lineIterator(logResponse.getEntityInputStream(), "UTF-8");
- while (itr.hasNext()) {
- String line = itr.next();
- logwriter2.write(line + (itr.hasNext() ? "\n" : ""));
- LOG.info(line);
- }
- } finally {
- IOUtils.closeQuietly(logResponse.getEntityInputStream());
- }
-
- assertThat(logwriter2.toString(), endsWith(expectedText));
- }
+ @Test
+ public void testDockerBuilderAddFolder() throws DockerException,
+ IOException {
+ File baseDir = new File(Thread.currentThread().getContextClassLoader()
+ .getResource("testAddFolder").getFile());
+ dockerfileBuild(baseDir, "Successfully executed testAddFolder.sh");
+ }
+
+ @Test
+ public void testNetCatDockerfileBuilder() throws DockerException,
+ IOException, InterruptedException {
+ File baseDir = new File(Thread.currentThread().getContextClassLoader()
+ .getResource("netcat").getFile());
+
+ ClientResponse response = dockerClient.build(baseDir);
+
+ StringWriter logwriter = new StringWriter();
+
+ try {
+ LineIterator itr = IOUtils.lineIterator(
+ response.getEntityInputStream(), "UTF-8");
+ while (itr.hasNext()) {
+ String line = itr.next();
+ logwriter.write(line + "\n");
+ LOG.info(line);
+ }
+ } finally {
+ IOUtils.closeQuietly(response.getEntityInputStream());
+ }
+
+ String fullLog = logwriter.toString();
+ assertThat(fullLog, containsString("Successfully built"));
+
+ String imageId = StringUtils.substringBetween(fullLog,
+ "Successfully built ", "\\n\"}").trim();
+
+ ImageInspectResponse imageInspectResponse = dockerClient
+ .inspectImage(imageId);
+ assertThat(imageInspectResponse, not(nullValue()));
+ LOG.info("Image Inspect: {}", imageInspectResponse.toString());
+ tmpImgs.add(imageInspectResponse.getId());
+
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage(imageInspectResponse.getId());
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+ assertThat(container.getId(), not(isEmptyString()));
+ dockerClient.startContainer(container.getId());
+ tmpContainers.add(container.getId());
+
+ ContainerInspectResponse containerInspectResponse = dockerClient
+ .inspectContainer(container.getId());
+
+ assertThat(containerInspectResponse.getId(), notNullValue());
+ assertThat(containerInspectResponse.getNetworkSettings().ports,
+ notNullValue());
+
+ // No use as such if not running on the server
+ for (String portstr : containerInspectResponse.getNetworkSettings().ports
+ .getAllPorts().keySet()) {
+
+ Ports.Port p = containerInspectResponse.getNetworkSettings().ports
+ .getAllPorts().get(portstr);
+ int port = Integer.valueOf(p.getHostPort());
+ LOG.info("Checking port {} is open", port);
+ assertThat(available(port), is(false));
+ }
+ dockerClient.stopContainer(container.getId(), 0);
+
+ }
+
+ // UTIL
+
+ /**
+ * Checks to see if a specific port is available.
+ *
+ * @param port
+ * the port to check for availability
+ */
+ public static boolean available(int port) {
+ if (port < 1100 || port > 60000) {
+ throw new IllegalArgumentException("Invalid start port: " + port);
+ }
+
+ ServerSocket ss = null;
+ DatagramSocket ds = null;
+ try {
+ ss = new ServerSocket(port);
+ ss.setReuseAddress(true);
+ ds = new DatagramSocket(port);
+ ds.setReuseAddress(true);
+ return true;
+ } catch (IOException e) {
+ } finally {
+ if (ds != null) {
+ ds.close();
+ }
+
+ if (ss != null) {
+ try {
+ ss.close();
+ } catch (IOException e) {
+ /* should not be thrown */
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private String dockerfileBuild(File baseDir, String expectedText)
+ throws DockerException, IOException {
+
+ // Build image
+ ClientResponse response = dockerClient.build(baseDir);
+
+ StringWriter logwriter = new StringWriter();
+
+ try {
+ LineIterator itr = IOUtils.lineIterator(
+ response.getEntityInputStream(), "UTF-8");
+ while (itr.hasNext()) {
+ String line = itr.next();
+ logwriter.write(line + "\n");
+ LOG.info(line);
+ }
+ } finally {
+ IOUtils.closeQuietly(response.getEntityInputStream());
+ }
+
+ String fullLog = logwriter.toString();
+ assertThat(fullLog, containsString("Successfully built"));
+
+ String imageId = StringUtils.substringBetween(fullLog,
+ "Successfully built ", "\\n\"}").trim();
+
+ // Create container based on image
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage(imageId);
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+ LOG.info("Created container: {}", container.toString());
+ assertThat(container.getId(), not(isEmptyString()));
+
+ dockerClient.startContainer(container.getId());
+ dockerClient.waitContainer(container.getId());
+
+ tmpContainers.add(container.getId());
+
+ // Log container
+ ClientResponse logResponse = dockerClient.logContainer(container
+ .getId());
+
+ assertThat(logResponseStream(logResponse), containsString(expectedText));
+
+ return container.getId();
+ }
}
\ No newline at end of file
diff --git a/src/test/java/com/kpelykh/docker/client/test/DockerPushTest.java b/src/test/java/com/kpelykh/docker/client/test/DockerPushTest.java
new file mode 100644
index 00000000..7e6d88a9
--- /dev/null
+++ b/src/test/java/com/kpelykh/docker/client/test/DockerPushTest.java
@@ -0,0 +1,86 @@
+package com.kpelykh.docker.client.test;
+
+
+import com.kpelykh.docker.client.DockerException;
+import com.kpelykh.docker.client.model.CommitConfig;
+import com.kpelykh.docker.client.model.ContainerConfig;
+import com.kpelykh.docker.client.model.ContainerCreateResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.ITestResult;
+import org.testng.annotations.*;
+
+import java.lang.reflect.Method;
+
+import static com.kpelykh.docker.client.DockerClient.asString;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
+
+// delete here : https://index.docker.io/u/alexec/busybox/delete/
+public class DockerPushTest extends AbstractDockerClientTest {
+
+ public static final Logger LOG = LoggerFactory
+ .getLogger(DockerPushTest.class);
+
+ String username;
+
+ @BeforeTest
+ public void beforeTest() throws DockerException {
+ super.beforeTest();
+ username = dockerClient.authConfig().getUsername();
+ }
+ @AfterTest
+ public void afterTest() {
+ super.afterTest();
+ }
+
+ @BeforeMethod
+ public void beforeMethod(Method method) {
+ super.beforeMethod(method);
+ }
+
+ @AfterMethod
+ public void afterMethod(ITestResult result) {
+ super.afterMethod(result);
+ }
+
+ @Test
+ public void testPushLatest() throws Exception {
+
+
+ ContainerConfig containerConfig = new ContainerConfig();
+ containerConfig.setImage("busybox");
+ containerConfig.setCmd(new String[] { "true" });
+
+ ContainerCreateResponse container = dockerClient
+ .createContainer(containerConfig);
+
+ LOG.info("Created container {}", container.toString());
+
+ assertThat(container.getId(), not(isEmptyString()));
+
+ tmpContainers.add(container.getId());
+
+ LOG.info("Commiting container: {}", container.toString());
+ CommitConfig commitConfig = new CommitConfig(container.getId());
+
+ commitConfig.setRepo(username + "/busybox");
+
+ String imageId = dockerClient.commit(commitConfig);
+
+ logResponseStream(dockerClient.push(username + "/busybox"));
+
+ dockerClient.removeImage(imageId);
+
+ assertThat(asString(dockerClient.pull(username + "/busybox")), not(containsString("404")));
+ }
+
+ @Test
+ public void testNotExistentImage() throws Exception {
+
+ assertThat(logResponseStream(dockerClient.push(username + "/xxx")), containsString("error"));
+ }
+
+
+}
+
diff --git a/src/test/resources/testAddFile/Dockerfile b/src/test/resources/testAddFile/Dockerfile
index 6efbf091..2900a5e7 100644
--- a/src/test/resources/testAddFile/Dockerfile
+++ b/src/test/resources/testAddFile/Dockerfile
@@ -2,8 +2,8 @@ FROM ubuntu
# Copy testrun.sh files into the container
-add ./testrun.sh /tmp/
+ADD ./testrun.sh /tmp/
-run cp /tmp/testrun.sh /usr/local/bin/ && chmod +x /usr/local/bin/testrun.sh
+RUN cp /tmp/testrun.sh /usr/local/bin/ && chmod +x /usr/local/bin/testrun.sh
CMD ["testrun.sh"]
diff --git a/src/test/resources/testAddFileInSubfolder/Dockerfile b/src/test/resources/testAddFileInSubfolder/Dockerfile
new file mode 100644
index 00000000..41d8f437
--- /dev/null
+++ b/src/test/resources/testAddFileInSubfolder/Dockerfile
@@ -0,0 +1,9 @@
+FROM ubuntu
+
+# Copy testrun.sh files into the container
+
+ADD ./files/testrun.sh /tmp/
+
+RUN cp /tmp/testrun.sh /usr/local/bin/ && chmod +x /usr/local/bin/testrun.sh
+
+CMD ["testrun.sh"]
diff --git a/src/test/resources/testAddFileInSubfolder/files/testrun.sh b/src/test/resources/testAddFileInSubfolder/files/testrun.sh
new file mode 100755
index 00000000..80b468e7
--- /dev/null
+++ b/src/test/resources/testAddFileInSubfolder/files/testrun.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+echo "Successfully executed testrun.sh"
diff --git a/src/test/resources/testAddFolder/Dockerfile b/src/test/resources/testAddFolder/Dockerfile
index 73173ad4..b2a8e2a1 100644
--- a/src/test/resources/testAddFolder/Dockerfile
+++ b/src/test/resources/testAddFolder/Dockerfile
@@ -2,7 +2,7 @@ FROM ubuntu
# Copy testrun.sh files into the container
-add . /src/
+ADD . /src/
run ls -la /src
diff --git a/src/test/resources/testAddUrl/Dockerfile b/src/test/resources/testAddUrl/Dockerfile
new file mode 100644
index 00000000..1d76926c
--- /dev/null
+++ b/src/test/resources/testAddUrl/Dockerfile
@@ -0,0 +1,10 @@
+FROM ubuntu
+
+# Copy testrun.sh files into the container
+
+ADD http://www.docker.io /tmp/docker_home.html
+ADD ./testrun.sh /tmp/
+
+RUN cp /tmp/testrun.sh /usr/local/bin/ && chmod +x /usr/local/bin/testrun.sh
+
+CMD ["testrun.sh"]
\ No newline at end of file
diff --git a/src/test/resources/testAddUrl/testrun.sh b/src/test/resources/testAddUrl/testrun.sh
new file mode 100755
index 00000000..8eb4630b
--- /dev/null
+++ b/src/test/resources/testAddUrl/testrun.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+
+cat /tmp/docker_home.html
+
diff --git a/src/test/resources/testImportImageFromTar/empty.tar b/src/test/resources/testImportImageFromTar/empty.tar
new file mode 100644
index 00000000..b055b9c2
Binary files /dev/null and b/src/test/resources/testImportImageFromTar/empty.tar differ
diff --git a/src/test/resources/testReadFile/Dockerfile b/src/test/resources/testReadFile/Dockerfile
new file mode 100644
index 00000000..3dfe89f9
--- /dev/null
+++ b/src/test/resources/testReadFile/Dockerfile
@@ -0,0 +1,9 @@
+FROM ubuntu
+
+# Copy testrun.sh files into the container
+
+ADD ./testrun.sh /tmp/
+ADD ./oldFile.txt /
+RUN cp /tmp/testrun.sh /usr/local/bin/ && chmod +x /usr/local/bin/testrun.sh
+
+CMD ["testrun.sh"]
diff --git a/src/test/resources/testReadFile/oldFile.txt b/src/test/resources/testReadFile/oldFile.txt
new file mode 100644
index 00000000..ac1acee1
--- /dev/null
+++ b/src/test/resources/testReadFile/oldFile.txt
@@ -0,0 +1 @@
+Old File
\ No newline at end of file
diff --git a/src/test/resources/testReadFile/testrun.sh b/src/test/resources/testReadFile/testrun.sh
new file mode 100755
index 00000000..d8b9508d
--- /dev/null
+++ b/src/test/resources/testReadFile/testrun.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+
+echo "Hello Word" > hello.txt
+echo "hello.txt Created"