Example usage for java.io StringWriter getBuffer

List of usage examples for java.io StringWriter getBuffer

Introduction

In this page you can find the example usage for java.io StringWriter getBuffer.

Prototype

public StringBuffer getBuffer() 

Source Link

Document

Return the string buffer itself.

Usage

From source file:edu.cornell.med.icb.goby.stats.TestAnnotationAveragingWriter.java

@Test
public void testCase7() {
    String[] groups = new String[] { "group1" };
    String[] samples = new String[] { "sample1", "sample2", "sample3" };
    int[] positions = new int[] { 6, 8, 14, 16 };
    int[][] C = { { 5, 3, 9, 8 }, { 4, 6, 3, 2 }, { 8, 3, 8, 9 } };
    int[][] Cm = { { 9, 7, 1, 5 }, { 9, 7, 9, 3 }, { 2, 3, 2, 8 } };
    testSupport = new MethylCountProviderTestSupport(groups, samples, positions, "Case4", C, Cm);
    final StringWriter stringWriter = new StringWriter();
    AnnotationAveragingWriter testWriter = new AnnotationAveragingWriter(stringWriter, genome, testSupport);
    testWriter.setWriteNumSites(false);/*from  ww  w.j  a va2s  .com*/
    testWriter.setContexts(DEFAULT_TEST_CONTEXTS);
    testWriter.setAnnotationFilename("test-data/vcf-averaging/annotations-1.tsv");
    int[] a = { 0, 0, 0 };
    testWriter.setSampleIndexToGroupIndex(a);
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.close();
    assertEquals("Test Case 7 result: ",
            "Chromosome\tStart\tEnd\tFeature\tMR[sample1][CpG]\tMR[sample2][CpG]\tMR[sample3][CpG]\tMR[sample1][CpA]\tMR[sample2][CpA]\tMR[sample3][CpA]\tMR[sample1][CpC]\tMR[sample2][CpC]\tMR[sample3][CpC]\tMR[sample1][CpT]\tMR[sample2][CpT]\tMR[sample3][CpT]\tMR[sample1][CpN]\tMR[sample2][CpN]\tMR[sample3][CpN]\tMR[group1][CpG]\tMR[group1][CpA]\tMR[group1][CpC]\tMR[group1][CpT]\tMR[group1][CpN]\n"
                    + "Case4\t5\t9\tannotation7\t\t\t\t\t\t\t\t\t\t66.67\t61.54\t31.25\t\t\t\t\t\t\t56.06\t\n"
                    + "Case4\t13\t17\tannotation8\t\t\t\t26.09\t70.59\t37.04\t\t\t\t\t\t\t\t\t\t\t41.79\t\t\t\n",
            stringWriter.getBuffer().toString());

}

From source file:org.apache.solr.SolrTestCaseJ4.java

/**
 * Generates an <add><doc>... XML String with options
 * on the add./*from   w  ww .  j  a  v  a  2 s  . co  m*/
 *
 * @param doc the Document to add
 * @param args 0th and Even numbered args are param names, Odds are param values.
 * @see #add
 * @see #doc
 */
public static String add(XmlDoc doc, String... args) {
    try {
        StringWriter r = new StringWriter();

        // this is annoying
        if (null == args || 0 == args.length) {
            r.write("<add>");
            r.write(doc.xml);
            r.write("</add>");
        } else {
            XML.writeUnescapedXML(r, "add", doc.xml, (Object[]) args);
        }

        return r.getBuffer().toString();
    } catch (IOException e) {
        throw new RuntimeException("this should never happen with a StringWriter", e);
    }
}

From source file:org.hexlogic.model.DockerNode.java

@VsoMethod(showInApi = true, name = "startContainer")
public void startContainer(
        // complex objects
        @VsoParam(description = "The container to start") DockerContainer container,
        @VsoParam(description = "A array of links for the container") DockerLink[] links,
        @VsoParam(description = "A array of port bindings for the container") DockerPortBind[] portBindings,
        @VsoParam(description = "A array of volume bindings for the container") DockerVolumeBind[] volumeBindings,

        // strings
        @VsoParam(description = "A list of dns servers for the container to use") String[] dns,
        @VsoParam(description = "A list of DNS search domains") String[] dnsSearch,

        // bools//from  w ww . ja  v a 2 s .c  o  m
        @VsoParam(description = "Allocates a random host port for all of a container's exposed ports") boolean publishAllPorts,
        @VsoParam(description = "Runs this container in privileged mode") boolean privileged) throws Exception {
    if (container == null) {
        throw new Exception("Error: no container specified.");
    }

    log.debug("Starting container '" + id + "'.");

    try {
        configureNode();
        DockerClient dockerClient = getDockerClient();

        StartContainerCmd command = dockerClient.startContainerCmd(container.getContainerId())
                .withPublishAllPorts(publishAllPorts).withPrivileged(privileged);

        if (portBindings != null && (portBindings.length > 0)) {
            Ports pb = new Ports();
            for (DockerPortBind portBind : portBindings) {
                pb.bind(portBind.getPort().toExposedPort(), Ports.Binding(portBind.getPortNumber()));
            }
            command.withPortBindings(pb);
        }
        if (volumeBindings != null && (volumeBindings.length > 0)) {
            ArrayList<Bind> newBinds = new ArrayList<Bind>();
            for (DockerVolumeBind bind : volumeBindings) {
                Bind b;
                if (bind.getAccessMode().equals("ro")) {
                    b = new Bind(bind.getMountPoint(), bind.getVolume().toVolume(), AccessMode.ro);
                } else {
                    b = new Bind(bind.getMountPoint(), bind.getVolume().toVolume(), AccessMode.rw);
                }
                newBinds.add(b);
            }
            //convert ArrayList to Array
            Bind[] bindArray = new Bind[newBinds.size()];
            bindArray = newBinds.toArray(bindArray);
            command.withBinds(bindArray);
        }
        if (dns != null && (dns.length > 0)) {
            command.withDns(dns);
        }
        if (dnsSearch != null && (dnsSearch.length > 0)) {
            command.withDnsSearch(dnsSearch);
        }
        if (links != null && (links.length > 0)) {
            ArrayList<Link> linksArray = new ArrayList<Link>();
            for (DockerLink link : links) {
                Link dockerLink = new Link(link.getContainer().getName(), link.getLinkAlias());
                linksArray.add(dockerLink);
            }

            //convert ArrayList to Array
            Link[] dockerLinks = new Link[linksArray.size()];
            dockerLinks = linksArray.toArray(dockerLinks);

            command.withLinks(dockerLinks);
        }
        command.exec();
    } catch (NotFoundException e) {
        // container not found
        log.error(e.getMessage());
        // Throw error detail message so vCO can display it
        throw new Exception("Error: the container was not found.");
    } catch (NotModifiedException e) {
        // Container already started
        log.error(e.getMessage());
        // Throw error detail message so vCO can display it
        throw new Exception("Error: the container is already started.");
    } catch (Exception e) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);

        log.error("Error while starting container: " + sw.getBuffer().toString());
        throw new Exception("Error while starting container: " + sw.getBuffer().toString());
    }
    log.debug("Start operation finished.");

    container.reloadContainer();
}

From source file:org.hexlogic.model.DockerNode.java

@VsoMethod(showInApi = true, name = "createContainer", description = "Create a new container from an image on the docker node")
public String createContainer(
        // complex objects
        @VsoParam(description = "The image to build the container from") DockerImage image,
        @VsoParam(description = "Array of ports to expose on this container") DockerPort[] ports,
        @VsoParam(description = "An object mapping mountpoint paths inside the container to empty objects.") DockerVolume[] volumes,

        // strings
        @VsoParam(description = "Name for the container to use. Must be unique on every node") String name,
        @VsoParam(description = "Command(s) to run specified as a array of strings") String[] cmd,
        @VsoParam(description = "A string array of environment variables, each in the form of key=value") String[] env,
        @VsoParam(description = "A string value containing the working dir for commands to run in") String workingDir,
        @VsoParam(description = "A string value containing the desired hostname to use for the container") String hostname,
        @VsoParam(description = "A string value containg the user to use inside the container") String user,

        // bools/* w w  w .  j  av a2  s . c  o m*/
        @VsoParam(description = "Attaches container to stdin") boolean attachStdIn,
        @VsoParam(description = "Attaches container to stdout") boolean attachStdOut,
        @VsoParam(description = "Attaches container to stderr") boolean attachStdErr,
        @VsoParam(description = "Attach standard streams to a tty, including stdin if it is not closed") boolean tty,
        @VsoParam(description = "Opens stdin") boolean openStdIn,
        @VsoParam(description = "Close stdin after the 1 attached client disconnects") boolean stdInOnce,
        @VsoParam(description = "Boolean value, when true disables neworking for the container") boolean NetworkDisabled)
        throws Exception {
    if (image == null) {
        throw new Exception("Error: no image specified.");
    }

    log.debug("Creating new container...");

    CreateContainerResponse response = null;
    try {
        configureNode();
        DockerClient dockerClient = getDockerClient();

        CreateContainerCmd command = dockerClient.createContainerCmd(image.getImageId())
                .withAttachStdin(attachStdIn).withAttachStdout(attachStdOut).withAttachStderr(attachStdErr)
                .withTty(tty);

        if (cmd != null && (cmd.length > 0)) {
            command.withCmd(cmd);
        }
        if (env != null && (env.length > 0)) {
            command.withEnv(env);
        }
        if (name != null && !name.isEmpty()) {
            command.withName(name);
        }
        if (ports != null && (ports.length > 0)) {
            ArrayList<ExposedPort> newPorts = new ArrayList<ExposedPort>();
            for (DockerPort port : ports) {
                newPorts.add(port.toExposedPort());
            }
            //convert ArrayList to Array
            ExposedPort[] portArray = new ExposedPort[newPorts.size()];
            portArray = newPorts.toArray(portArray);

            command.withExposedPorts(portArray);
        }
        if (openStdIn) {
            // defaults to false
            command.withStdinOpen(true);
        }
        if (stdInOnce) {
            // defaults to false
            command.withStdInOnce(true);
        }
        if (workingDir != null && !workingDir.isEmpty()) {
            command.withWorkingDir(workingDir);
        }
        if (hostname != null && !hostname.isEmpty()) {
            command.withHostName(hostname);
        }
        if (NetworkDisabled) {
            // defaults to false
            command.withDisableNetwork(true);
        }
        if (user != null && !user.isEmpty()) {
            command.withUser(user);
        }
        if (volumes != null && (volumes.length > 0)) {
            //  Destination mount point within the container
            ArrayList<Volume> newVolumes = new ArrayList<Volume>();
            for (DockerVolume volume : volumes) {
                newVolumes.add(volume.toVolume());
            }
            //convert ArrayList to Array
            Volume[] volumeArray = new Volume[newVolumes.size()];
            volumeArray = newVolumes.toArray(volumeArray);
            command.withVolumes(volumeArray);
        }

        response = command.exec();
        log.debug("Created container '" + response.getId() + "'.");
    } catch (NotFoundException e) {
        // container not found
        log.error(e.getMessage());
        // Throw error detail message so vCO can display it
        throw new Exception("Error: the container was not found.");
    } catch (ConflictException e) {
        // Named container already exists
        log.error(e.getMessage());
        // Throw error detail message so vCO can display it
        throw new Exception("Error: a container with the specified name already exists.");
    } catch (Exception e) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);

        log.error("Error while creating container: " + sw.getBuffer().toString());
        throw new Exception("Error while creating container: " + sw.getBuffer().toString());
    }

    // reload images from docker node
    this.reloadContainers();
    // update inventory - another way to do this would be to update our ArrayList and call notifyElementUpdated on the container object
    notificationHandler.notifyElementInvalidate(toRef());

    // return container id
    return response.getId();
}

From source file:org.hexlogic.model.DockerNode.java

@VsoMethod(showInApi = false)
public void initContainers(boolean allContainers) {
    log.debug("About to load containers for node '" + this.id + "'");
    if ((this.hostName != null) && (this.hostPortNumber > 0) && (this.hostPortNumber < 65535)) {
        try {/*from w  ww.  j a v  a 2 s.  c  om*/
            // Get the list of docker containers from the host
            List<Container> newContainers = null;
            try {
                configureNode();
                DockerClient dockerClient = getDockerClient();
                log.debug("Loading containers with option all=" + allContainers + ".");
                newContainers = dockerClient.listContainersCmd().withShowAll(allContainers).exec();
            } catch (Exception e) {
                log.error("Error occured while loading containers: " + e.getMessage());
                // if a error occurs, clear the cache and throw an error to prevent the client from seeing outdated data
                log.debug("Clearing container cache on node '" + displayName + "'.");
                this.containers.clear();
                throw e;
            }

            // handle init / update in a synchronized manner
            synchronized (this.containers) {
                // 1. Collect diff information
                // 1a. Only in newList == addedContainers, add and notifyInvalidate(node) when done with everything. newList - oldList = addedContainers
                List<Container> addedContainers = new ArrayList<Container>(newContainers);
                Iterator<Container> addItr = addedContainers.iterator();
                log.debug("Checking for new containers...");
                while (addItr.hasNext()) {
                    Container cnt = addItr.next();
                    Iterator<DockerContainer> itr = this.containers.iterator();
                    while (itr.hasNext()) {
                        DockerContainer container = itr.next();
                        if (container.getContainerId().equals(cnt.getId())) {
                            // if the container exists in the oldList, remove it from the addedContainers
                            log.debug("Container '" + cnt.getId() + "' seems to be already cached.");
                            addItr.remove();
                        }
                    }
                }
                log.debug("New containers found are: " + addedContainers.toString());

                // 1b. Only in oldList == deletedContainers, delete and notifyDelete(container). oldList - newList = deletedContainers
                List<DockerContainer> deletedContainers = new ArrayList<DockerContainer>();
                Iterator<DockerContainer> delItr = this.containers.iterator();
                log.debug("Checking for deleted containers...");
                deleteloop: while (delItr.hasNext()) {
                    DockerContainer container = delItr.next();
                    Iterator<Container> itr = newContainers.iterator();
                    while (itr.hasNext()) {
                        Container cnt = itr.next();
                        if (cnt.getId().equals(container.getContainerId())) {
                            // if the container exists within the oldList, it's not deleted - check the next container
                            continue deleteloop;
                        }
                    }
                    // loop was not exited, so our container was not found in the newList and can be considered as deleted
                    log.debug("Container '" + container.getContainerId() + "' seems to be deleted.");
                    deletedContainers.add(container);
                }
                log.debug("Deleted containers found are: " + deletedContainers.toString());

                // 1c. In newList and in oldList == eventually updated containers, run inspectContainer and notifyUpdated(container). in both == updatedContainers      
                Iterator<Container> updItr = newContainers.iterator();
                log.debug("Updateing loaded containers on node's cache...");
                while (updItr.hasNext()) {
                    Container cnt = updItr.next();
                    Iterator<DockerContainer> itr = this.containers.iterator();
                    while (itr.hasNext()) {
                        DockerContainer container = itr.next();
                        if (cnt.getId().equals(container.getContainerId())) {
                            // if a container exists within the old and the new list, just update it's details
                            log.debug("Found container in node's cache. Updateing container info...");
                            container.reloadContainer();
                        }
                    }
                }
                log.debug("Finished updateing loaded containers on node's cache.");

                if (!addedContainers.isEmpty()) {
                    // for every added container, add it to our container list. This will also call updateChildInventory for that container
                    // Do not use for-loops for this, since it will cause ConcurrentModificationExceptions to be thrown!
                    log.debug("Adding loaded containers to node's cache...");
                    Iterator<Container> iterator = addedContainers.iterator();
                    while (iterator.hasNext()) {
                        Container c = iterator.next();
                        try {
                            log.debug("Adding container " + c.getId());
                            this.addContainer((new DockerContainer(this, c.getNames()[0], c.getId())));

                            //TODO call some notify method to let the node know there's a new child! (currently the constructor only calls update!)
                        } catch (Exception e) {
                            log.error("Error while adding container to container-cache. " + e.getMessage());
                        }
                    }
                    log.debug("Finished adding loaded containers to node's cache.");
                }

                if (!deletedContainers.isEmpty()) {
                    // for every deleted container, delete it from our list.
                    // Do not use for-loops for this, since it will cause ConcurrentModificationExceptions to be thrown!
                    log.debug("Removeing deleted containers from node's cache...");
                    Iterator<DockerContainer> iterator = deletedContainers.iterator();
                    while (iterator.hasNext()) {
                        DockerContainer c = iterator.next();
                        try {
                            Iterator<DockerContainer> itr = this.containers.iterator();
                            while (itr.hasNext()) {
                                DockerContainer cnt = itr.next();
                                if (cnt.getContainerId().equals(c.getContainerId())) {
                                    log.debug("Deleting container '" + cnt.getDisplayName()
                                            + "' from node cache...");
                                    InventoryRef ref = cnt.toRef();
                                    itr.remove();

                                    notificationHandler.notifyElementDeleted(ref);
                                }
                            }
                        } catch (Exception e) {
                            log.error("Error while removeing deleted container from container-list. "
                                    + e.getMessage());
                        }
                    }
                    log.debug("Finished removeing deleted containers from node's cache.");
                }
            }
        } catch (Exception e) {
            // this method is never called directly by a user, thus, don't throw exceptions but rather log them
            final StringWriter sw = new StringWriter();
            final PrintWriter pw = new PrintWriter(sw, true);
            e.printStackTrace(pw);
            log.error("Error: " + sw.getBuffer().toString());
        }
    } else {
        log.error("Failed to load containers from node '" + this.id + "'. Check the node's settings");
    }
    log.debug("Finished loading containers for node '" + this.id + "' into cache.");
}

From source file:org.hexlogic.model.DockerNode.java

@VsoMethod(showInApi = false)
public void initImages(boolean allImages) {
    log.debug("About to load images for node '" + this.id + "'");
    if ((this.hostName != null) && (this.hostPortNumber > 0) && (this.hostPortNumber < 65535)) {
        try {/* w  ww.  j a va2 s .  co  m*/
            // Get the list of docker images from the host
            List<Image> newImages = null;
            try {
                configureNode();
                DockerClient dockerClient = getDockerClient();
                log.debug("Loading Images with option all=" + allImages + ".");
                newImages = dockerClient.listImagesCmd().withShowAll(allImages).exec();
            } catch (Exception e) {
                log.error("Error occured while loading images: " + e.getMessage());
                // if a error occurs, clear the cache and throw an error to prevent the client from seeing out-dated data
                log.debug("Clearing image cache on node '" + displayName + "'.");
                this.images.clear();
                throw e;
            }

            // handle init / update in a synchronized manner
            synchronized (this.images) {
                // 1. Collect diff information
                // 1a. Only in newList == addedImages, add and notifyInvalidate(node) when done with everything. newList - oldList = addedImages
                List<Image> addedImages = new ArrayList<Image>(newImages);
                Iterator<Image> addItr = addedImages.iterator();
                log.debug("Checking for new images...");
                while (addItr.hasNext()) {
                    Image img = addItr.next();
                    Iterator<DockerImage> itr = this.images.iterator();
                    while (itr.hasNext()) {
                        DockerImage image = itr.next();
                        if (img.getId().equals(image.getImageId())) {
                            // if the image exists in the oldList, remove it from the addedImages
                            log.debug("Image '" + img.getId() + "' seems to be already cached.");
                            addItr.remove();
                        }
                    }
                }
                log.debug("New images found are: " + addedImages.toString());

                // 1b. Only in oldList == deletedImages, delete and notifyDelete(image). oldList - newList = deletedImages
                List<DockerImage> deletedImages = new ArrayList<DockerImage>();
                Iterator<DockerImage> delItr = this.images.iterator();
                log.debug("Checking for deleted images...");
                deleteloop: while (delItr.hasNext()) {
                    DockerImage image = delItr.next();
                    Iterator<Image> itr = newImages.iterator();
                    while (itr.hasNext()) {
                        Image img = itr.next();
                        if (img.getId().equals(image.getImageId())) {
                            // if the image exists within the oldList, it's not deleted - check the next image
                            continue deleteloop;
                        }
                    }
                    // loop was not exited, so our image was not found in the newList and can be considered as deleted
                    log.debug("Image '" + image.getImageId() + "' seems to be deleted.");
                    deletedImages.add(image);
                }
                log.debug("Deleted images found are: " + deletedImages.toString());

                // 1c. In newList and in oldList == eventually updated images, run inspectImage and notifyUpdated(image). in both == updatedImages      
                Iterator<Image> updItr = newImages.iterator();
                log.debug("Updateing loaded images on node's cache...");
                while (updItr.hasNext()) {
                    Image img = updItr.next();
                    Iterator<DockerImage> itr = this.images.iterator();
                    while (itr.hasNext()) {
                        DockerImage image = itr.next();
                        if (img.getId().equals(image.getImageId())) {
                            // if a image exists within the old and the new list, just update it's details
                            log.debug("Found image in node's cache. Updateing image info...");
                            image.reloadImage();
                        }
                    }
                }
                log.debug("Finished updateing loaded images on node's cache.");

                if (!addedImages.isEmpty()) {
                    // for every added image, add it to our image list. This will also call updateChildInventory for that image
                    // Do not use for-loops for this, since it will cause ConcurrentModificationExceptions to be thrown!
                    log.debug("Adding loaded images to node's cache...");
                    Iterator<Image> iterator = addedImages.iterator();
                    while (iterator.hasNext()) {
                        Image i = iterator.next();
                        String[] tags = i.getRepoTags();
                        // Tags may look like this : m451/drum-machine:latest
                        // Or this : base:ubuntu-12.10
                        String tag = tags[0];
                        String id = i.getId();

                        try {
                            log.debug("Adding image " + tag);
                            this.addImage((new DockerImage(this, tag, id)));

                            //TODO call some notify method to let the node know there's a new child! (currently the constructor only calls update!)

                        } catch (Exception e) {
                            log.error("Error while adding image to image-list. " + e.getMessage());
                        }
                    }
                    log.debug("Finished adding loaded images to node's cache.");
                }

                if (!deletedImages.isEmpty()) {
                    // for every deleted image, delete it from our list.
                    // Do not use for-loops for this, since it will cause ConcurrentModificationExceptions to be thrown!
                    log.debug("Removeing deleted images from node cache...");
                    Iterator<DockerImage> iterator = deletedImages.iterator();
                    while (iterator.hasNext()) {
                        DockerImage i = iterator.next();
                        try {
                            Iterator<DockerImage> itr = this.images.iterator();
                            while (itr.hasNext()) {
                                DockerImage img = itr.next();
                                if (img.getImageId().equals(i.getImageId())) {
                                    log.debug(
                                            "Deleting image '" + img.getDisplayName() + "' from node cache...");
                                    InventoryRef ref = img.toRef();
                                    itr.remove();

                                    notificationHandler.notifyElementDeleted(ref);
                                }
                            }
                        } catch (Exception e) {
                            log.error("Error while removeing deleted image from image-list. " + e.getMessage());
                        }
                    }
                    log.debug("Finished removeing deleted images from node's cache.");
                }
            }
        } catch (Exception e) {
            // this method is never called directly by a user, thus, don't throw exceptions but rather log them
            final StringWriter sw = new StringWriter();
            final PrintWriter pw = new PrintWriter(sw, true);
            e.printStackTrace(pw);
            log.error("Error: " + sw.getBuffer().toString());
        }
    } else {
        log.error("Failed to load images from node '" + this.id + "'. Check the node's settings");
    }
    log.debug("Finished loading images for node '" + this.id + "' into cache.");
}

From source file:com.redhat.rhn.frontend.taglibs.ListDisplayTag.java

/** {@inheritDoc} */
@Override//from w  w w  .ja va 2 s .  c o m
public int doStartTag() throws JspException {
    rowCnt = 0;
    numItemsChecked = 0;
    JspWriter out = null;
    showSetButtons = false;

    try {
        out = pageContext.getOut();

        setupPageList();

        // Now that we have setup the proper tag state we
        // need to return if this is an export render.
        if (isExport()) {
            return SKIP_PAGE;
        }

        String sortedColumn = getSortedColumn();
        if (sortedColumn != null) {
            doSort(sortedColumn);
        }

        out.print("<div class=\"spacewalk-list ");
        out.println(type + "\"");
        if (tableId != null) {
            out.print(" id=\"" + tableId + "\"");
        }
        out.println(">");

        /*
         * If pageList contains an index and pageList.size() (what we are
         * displaying on the page) is less than pageList.getTotalSize() (the
         * total number of items in the data result), render alphabar. This
         * prevents the alphabar from showing up on pages that show all of
         * the entries on a single page and is similar to how the perl code
         * behaves.
         */
        StringWriter alphaBarContent = new StringWriter();
        StringWriter paginationContent = new StringWriter();

        pageContext.pushBody(alphaBarContent);
        if (getPageList().getIndex().size() > 0 && getPageList().size() < getPageList().getTotalSize()) {

            //renderViewAllLink(alphaBarContent);
            renderAlphabar(alphaBarContent);
        }
        pageContext.popBody();

        pageContext.pushBody(paginationContent);
        if (isPaging()) {
            renderPagination(paginationContent, true);
            renderBoundsVariables(paginationContent);
        }
        pageContext.popBody();

        int topAddonsContentLen = alphaBarContent.getBuffer().length() + paginationContent.getBuffer().length();

        if (topAddonsContentLen > 0) {
            out.println("<div class=\"spacewalk-list-top-addons\">");
            out.println("<div class=\"spacewalk-list-alphabar\">");
            out.print(alphaBarContent.getBuffer().toString());
            out.println("</div>");
            out.print(paginationContent.getBuffer().toString());
            out.println("</div>");
        }

        out.print("<div class=\"panel panel-default\">");

        renderPanelHeading(out);

        out.print("<table class=\"table table-striped\">");
        // we render the pagination controls as an additional head
        out.println("<thead>");
        out.println("\n<tr>");

        if (getIterator() != null && getIterator().hasNext()) {
            // Push a new BodyContent writer onto the stack so that
            // we can buffer the body data.
            bodyContent = pageContext.pushBody();
            return EVAL_BODY_INCLUDE;
        }
        return SKIP_BODY;
    } catch (IOException ioe) {
        throw new JspException("IO error writing to JSP file:", ioe);
    }
}

From source file:org.hexlogic.model.DockerNode.java

@VsoMethod(showInApi = true, name = "pullImage", description = "Pull the image matching the given string from the docker hub repository, saving it on the docker host.")
public String pullImage(String imageName) throws Exception {
    log.debug("Pulling image '" + imageName + "'...");

    @SuppressWarnings("rawtypes")
    MappingIterator<Map> it = null;
    try {/* ww  w  .ja  v a2  s .co  m*/
        configureNode();
        DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
        log.debug("Starting pull operation...");

        /*
         * We will check the final result by comparing the initial image id, which is the first ID provided by the stream such as:
         * 
         * {status=Pulling image (latest) from dockerfile/nodejs, progressDetail={}, id=406eb4a4dcad}
         * 
         * to the image id of the last entity which owns id AND status which will look something like:
         * {status=Download complete, progressDetail={}, id=406eb4a4dcad}
         * 
         * If both IDs match, we know that the latest layer is the same as the requested image layer.
         * So the next step is to compare the download status of that layer
         */
        String firstId = null;
        String lastId = "";
        String lastStatus = "undefined";

        /*
         * In addition to the download status of the layer, we provide additional information about how the process went by
         * returning information to the user using the last entity which has no id and only a status, which looks like this:
         * {status=Status: Image is up to date for dockerfile/nodejs}
         * or
         * {status=Status: Downloaded newer image for dockerfile/nodejs}
         * or
         * {status=Repository dockerfile/nodejs already being pulled by another client. Waiting.}
         */
        String finalStatus = "undefined";

        for (it = new ObjectMapper().readValues(
                new JsonFactory().createJsonParser(dockerClient.pullImageCmd(imageName).exec()), Map.class); it
                        .hasNext();) {
            Map<?, ?> element = it.next();
            String id = "";
            String status = "";
            String progress = "";

            // info OUTPUT
            // log.debug("info: " + element);

            try {
                id = element.get("id").toString();
            } catch (NullPointerException e) {/* catch exception if key was not found */
            }
            try {
                status = element.get("status").toString();
            } catch (NullPointerException e) {/* catch exception if key was not found */
            }
            try {
                progress = element.get("progress").toString();
            } catch (NullPointerException e) {/* catch exception if key was not found */
            }

            // if the key was found and we got some status
            if (!id.isEmpty() && !status.isEmpty()) {
                // remember the first id of the output stream, which is the id of the image we want to pull
                if (firstId == null) {
                    log.debug("Remembering first id: " + id);
                    firstId = id;
                }

                // if the same layer is returned multiple times in a row, don't log everything but just the progress
                if (id.equals(lastId)) {
                    lastId = id;
                    lastStatus = status;
                    if (!progress.isEmpty()) {
                        log.debug("Progress: " + progress);
                    }
                } else {
                    lastId = id;
                    log.debug("Image '" + id + "' status is: " + status + ".");
                    if (!progress.isEmpty()) {
                        log.debug("Progress: " + progress);
                    }
                }
            }

            if (!status.isEmpty()) {
                finalStatus = status;
            }
        }

        // TODO find a more robust way to handle downloadStatus and finalStatus
        String downloadStatus = "undefined";
        if (lastId.equals(firstId)) {
            log.debug("Last download layer id does match the requested image id: " + firstId);
            if (StringUtils.containsIgnoreCase(lastStatus, "Download complete")) {
                downloadStatus = "successed";
                log.debug("The requested layer was downloaded successfuly.");
            } else {
                downloadStatus = "failed";
                log.error("The requested layer failed to download.");
                // throw exception in order for the workflow to fail
                throw new IllegalStateException("The requested layer failed to download.");
            }
        }

        // reload images from docker node
        this.reloadImages();
        // update inventory - another way to do this would be to update our ArrayList and call notifyElementDeleted on the image object
        notificationHandler.notifyElementInvalidate(toRef());

        log.debug("Pull operation " + downloadStatus + ". " + finalStatus + ".");
        return "Pull operation " + downloadStatus + ". " + finalStatus + ".";

    } catch (InternalServerErrorException e) {
        // image dosn't exist
        log.error("Error: the image was not found.");
        // Throw error detail message so vCO can display it
        throw new Exception("Error: the image was not found.");
    } catch (Exception e) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);

        log.error("Error while pulling image: " + sw.getBuffer().toString());
        // Throw error detail message so vCO can display it
        throw new Exception("Error while pulling image: " + sw.getBuffer().toString());
    } finally {
        if (it != null) {
            log.debug("Closeing pullImage stream...");
            it.close();
            log.debug("Closed pullImage stream.");
        }
    }

}