Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.nirima.docker.client;
  
 
 import  javax.annotation.Nullable;
 import java.io.File;
 import java.util.List;
 import java.util.Map;
 import java.util.UUID;

Created by magnayn on 02/02/2014.
 
 public class DockerClient {
 
     private static final Logger log = LoggerFactory.getLogger(DockerClient.class);
     private MultivaluedMap<StringObjectheaders;
 
     public enum Logging {
         NONE, SLF4J, JUL
     }
 
     public static Builder builder() {
         return new Builder();
     }
 
     public MultivaluedMap<String,ObjectgetHeaders() {
         if == null ) {
              = new MultivaluedHashMap<StringObject>();
             .putSingle("X-Registry-Auth","docker");
         }
         return ;
     }
 
     public static class Builder {
 
         private String       serverUrl;
         private ClientConfig cc  = new ClientConfig();
         private Logging      logging = .;
 
 
 
         Builder() {
             // Set some reasonable defaults
             .property(., 10000);
             .property(.,    10000);
 
             // Docker has an irritating habit of returning no data,
             // but saying the content type is text/plain.
 
             // MessageBodyReader not found for media type=text/plain; charset=utf-8, type=void, genericType=void
 
             .register(NullReader.class);
 
             if == . ) {
                 LoggingFilter lf = new LoggingFilter(java.util.logging.Logger.getLogger(LoggingFilter.class.getName()), true);
                .register(lf);
            } else if == . ) {
                .register(Slf4jLoggingFilter.builder().build() );
            }
        }
        public Builder withUrl(String url) {
            Preconditions.checkNotNull(url);
            this. = url;
            return this;
        }
        public Builder connectTimeout(int ms) {
            .property(.ms);
            return this;
        }
        public Builder readTimeout(int ms) {
            .property(.ms);
            return this;
        }
        public Builder withLogging(Logging logging) {
            Preconditions.checkNotNull(logging);
            this. = logging;
            return this;
        }
        public DockerClient build() {
            Preconditions.checkNotNull();
            return new DockerClient(,);
        }
    }
    private final String serverUrl;
    private final WebTarget webTarget;
    private DockerClient(String serverUrlClientConfig cc)
    {
        this. = serverUrl;
        this. = ClientBuilder.newClient(cc).target(serverUrl);
    }
    // Remote APIs------------------------------------------------------------------
    public ImagesClient imagesApi() {
        return WebResourceFactory.newResource(ImagesClient.classfalsegetHeaders(),
                Collections.<Cookie>emptyList(), new Form());
    }
    public ContainersClient containersApi() {
        return WebResourceFactory.newResource(ContainersClient.class);
    }
    public MiscClient miscApi() {
        return WebResourceFactory.newResource(MiscClient.class);
    }
    // Useful wrapper functions-----------------------------------------------------
    public class System {
        private System() {}
        public Info info() {
            return miscApi().info();
        }
        public Version version() {
            return miscApi().version();
        }
        public Collection<EventStreamItembuild(File dockerFolderString tagthrows 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
            // ARCHIVE TAR
            String archiveNameWithOutExtension = UUID.randomUUID().toString();
            File dockerFolderTar = null;
            File tmpDockerContextFolder = null;
            try {
                File dockerFile = new File(dockerFolder"Dockerfile");
                List<StringdockerFileContent = 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(dockerFiletmpDockerContextFolder);
                for (String cmd : dockerFileContent) {
                    String addArgs[] = StringUtils.split(cmd" \t");
                    if (addArgs.length > 0 && addArgs[0].equalsIgnoreCase("ADD")) {
                        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(dockerFolderaddArgs[1]).getCanonicalFile();
                        }
                        if (!src.exists()) {
                            throw new DockerException(String.format("Source file %s does not' exist"src));
                        }
                        if (src.isDirectory()) {
                            FileUtils.copyDirectory(srctmpDockerContextFolder);
                        } else {
                            FileUtils.copyFileToDirectory(srctmpDockerContextFolder);
                        }
                    }
                }
                dockerFolderTar = CompressArchiveUtil.archiveTARFiles(tmpDockerContextFolderarchiveNameWithOutExtension);
            } catch (IOException ex) {
                FileUtils.deleteQuietly(dockerFolderTar);
                FileUtils.deleteQuietly(tmpDockerContextFolder);
                throw new DockerException("Error occurred while preparing Docker context folder."ex);
            }
            try {
                return makeEventStream(miscApi().build(tagfalsefalse,false,false, FileUtils.openInputStream(dockerFolderTar)));
            } catch (Exception e) {
                throw new DockerException(e);
            } finally {
                FileUtils.deleteQuietly(dockerFolderTar);
                FileUtils.deleteQuietly(tmpDockerContextFolder);
            }
        }
        private Collection<EventStreamItemmakeEventStream(InputStream inputStreamthrows IOException {
            ObjectMapper mapper = new ObjectMapper();
            // we'll be reading instances of MyBean
            ObjectReader reader = mapper.reader(EventStreamItem.class);
            // and then do other configuration, if any, and read:
            Iterator<EventStreamItemitems = reader.readValues(inputStream);
            return ImmutableList.copyOf(items);
        }
    }
    public System system() {
        return new System();
    }
    public class PullCommandBuilder {
        private String fromImage;
        private String fromSrc;
        private String repo;
        private String tag;
        private String registry;
        private PullCommandBuilder() {}
        public PullCommandBuilder image(String image) {
            this. = image;
            return this;
        }
        public PullCommandBuilder fromSrc(String src) {
            this. = src;
            return this;
        }
        public PullCommandBuilder repository(String repo) {
            this. = repo;
            return this;
        }
        public PullCommandBuilder withTag(String tag) {
            this. = tag;
            return this;
        }
        public PullCommandBuilder fromRegistry(String registry) {
            this. = registry;
            return this;
        }
        public InputStream execute() {
         /*   if( tag == null )
                tag = "";
            if( registry == null )
                registry = "";
           */
            return imagesApi().createImage();
        }
    }
        return new PullCommandBuilder();
    }
    // Container functions-----------------------------------------------------
    public class Container {
        private final String containerId;
        private Container(String containerId) { this. = containerId; }
        public void start() {
            containersApi().startContainer(null);
        }
        public void start(HostConfig hostConfig) {
            containersApi().startContainer(hostConfig);
        }
        public void stop() {
            containersApi().stopContainer(null);
        }
        public void stop(long secondsToWait) {
            containersApi().stopContainer(secondsToWait);
        }
        public void remove() {
            try {
                containersApi().removeContainer();
            } catch(NotFoundException ex) {
                .warn("Remove container {} not found");
            }
        }
        public void remove(boolean includingVolumes) {
            containersApi().removeContainer(includingVolumesfalse);
        }
        public int waitForContainer() {
            return containersApi().waitForContainer().;
        }
        public List<FileChangesgetFilesystemChanges() {
            return containersApi(). getFilesystemChanges();
        }
        public void kill() {
            containersApi().killContainer();
        }
        public void restart() {
            containersApi().restartContainer(null);
        }
        public void restart(long secondsToWait) {
            containersApi().restartContainer(secondsToWait);
        }
        public ContainerInspectResponse inspect() {
            return containersApi().inspectContainer();
        }
        public CommitCommandBuilder createCommitCommand() {
            return new CommitCommandBuilder();
        }
        public InputStream log() throws IOException {
            InputStream inputStream = containersApi().attachToContainer(,true,false,false,true,true);
            // Skip the header.
            inputStream.readnew byte[8] );
            return inputStream;
        }
        public final class CommitCommandBuilder {
            private String repo;
            private String tag;
            private String message;
            private String author;
            private String run;
            private CommitCommandBuilder() {
            }
            public CommitCommandBuilder repo(String repo) {
                this. = repo;
                return this;
            }
            public CommitCommandBuilder tag(String tag) {
                this. = tag;
                return this;
            }
            public CommitCommandBuilder message(String message) {
                this. = message;
                return this;
            }
            public CommitCommandBuilder author(String author) {
                this. = author;
                return this;
            }
            public CommitCommandBuilder run(String run) {
                this. = run;
                return this;
            }
            public String execute() {
                return miscApi().commit(,,,).getId();
            }
        }
    }
    public class ContainerFinder
    {
        private boolean allContainers;
        private boolean latest = false;
        private int limit = -1;
        private boolean showSize;
        private String since;
        private String before;

        
Show all containers (including ones that have finished : I.E: docker list -a

Parameters:
allContainers
Returns:
        public ContainerFinder allContainers(boolean allContainers) {
            this. = allContainers;
            return this;
        }
        public ContainerFinder latest(boolean latest) {
            this. = latest;
            return this;
        }
        public ContainerFinder limit(int limit) {
            this. = limit;
            return this;
        }
        public ContainerFinder showSize(boolean showSize) {
            this. = showSize;
            return this;
        }
        public ContainerFinder since(String since) {
            this. = since;
            return this;
        }
        public ContainerFinder before(String before) {
            this. = before;
            return this;
        }
        public List<com.nirima.docker.client.model.Containerlist() {
        }
    }
    public class Containers {
        private Containers() {}
        public ContainerFinder finder() {
            return new ContainerFinder();
        }
        public ContainerCreateResponse create(ContainerConfig containerConfig) {
            return containersApi().createContainer(nullcontainerConfig);
        }
    }
    public Containers containers() {
        return new Containers();
    }
    public Container container(String containerId) {
        Preconditions.checkNotNull(containerId);
        return new Container(containerId);
    }
    // -------------------------------------------------------------------------------------------------
    public class ImageFinder {
        private String filter;
        private boolean allImages = false;
        public ImageFinder filter(String filter) {
            this. = filter;
            return this;
        }
        public ImageFinder allImages(boolean allImages) {
            this. = allImages;
            return this;
        }
        public List<com.nirima.docker.client.model.Imagelist() {
            return imagesApi().listImages();
        }
    }
    public class Images {
        public List<com.nirima.docker.client.model.SearchItemsearch(String term) {
            return imagesApi().searchForImage(term);
        }
        public void remove(Collection<Stringimagesthrows DockerException {
            Preconditions.checkNotNull(images"List of images can't be null");
            for (String imageName : images) {
                imagesApi().removeImage(imageNamefalsefalse);
            }
        }
        public ImageFinder finder() {
            return new ImageFinder();
        }
    }
    public class Image {
        private final String imageId;
        private Image(String imageId) { this. = imageId; }
        public void remove() {
            try {
                imagesApi().removeImage(falsefalse);
            }
            catch(NotFoundException ex) {
                .warn("Remove Image {} not found");
            }
        }
        public RemoveCommand removeCommand() {
            return new RemoveCommand();
        }
        public class RemoveCommand {
            boolean force = false;
            boolean noprune = false;
            public RemoveCommand force(boolean force) {
                this. = force;
                return this;
            }
            public RemoveCommand noPrune(boolean noprune) {
                this. = noprune;
                return this;
            }
            public Collection<ImageActionexecute() {
                try {
                    List<Map<StringString>> items = imagesApi().removeImage();
                    return Collections2.transform(itemsnew Function<Map<StringString>, ImageAction>() {
                        @Override
                        public ImageAction apply(@Nullable Map<StringStringinput) {
                            Map.Entry<StringStringentry = Iterators.get(input.entrySet().iterator(), 0);
                            return new ImageAction( ImageAction.ActionType.valueOf(entry.getKey()), entry.getValue());
                        }
                    });
                }
                catch(NotFoundException ex) {
                    .warn("Remove Image {} not found");
                    return Collections.emptySet();
                }
            }
        }
        public ImageInspectResponse inspect() {
            return imagesApi().inspectImage();
        }
        public void tag(String nameboolean b) {
            imagesApi().tagImage(nameb);
        }
        public void push(String registry) {
            imagesApi().pushImageOnRegistry(registry"");
        }
    }
    public Images images() { return new Images(); }
    public Image image(String imageId) {
        Preconditions.checkNotNull(imageId);
        return new Image(imageId);
    }
New to GrepCode? Check out our FAQ X