Search in sources :

Example 1 with Container

use of com.cloudbees.jenkins.support.api.Container in project support-core-plugin by jenkinsci.

the class NetworkInterfacesTest method testGetNetworkInterface.

@Test
public void testGetNetworkInterface() throws Exception {
    // This machine might not have a network interface. But how did it get this code?
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    if (!networkInterfaces.hasMoreElements())
        return;
    NetworkInterface networkInterface = networkInterfaces.nextElement();
    String expectedName = networkInterface.getDisplayName();
    NetworkInterfaces ni = new NetworkInterfaces();
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ni.addContents(new Container() {

        @Override
        public void add(@CheckForNull Content content) {
            try {
                content.writeTo(baos);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    String masterNetworkInterfaces = baos.toString();
    assertThat("Should at least contain one network interface.", masterNetworkInterfaces, containsString(expectedName));
}
Also used : Container(com.cloudbees.jenkins.support.api.Container) Content(com.cloudbees.jenkins.support.api.Content) NetworkInterface(java.net.NetworkInterface) Matchers.containsString(org.hamcrest.Matchers.containsString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Test(org.junit.Test)

Example 2 with Container

use of com.cloudbees.jenkins.support.api.Container in project support-core-plugin by jenkinsci.

the class SupportPlugin method writeBundle.

public static void writeBundle(OutputStream outputStream, final List<Component> components) throws IOException {
    // TODO why is this not SupportPlugin.logger?
    Logger logger = Logger.getLogger(SupportPlugin.class.getName());
    final java.util.Queue<Content> toProcess = new ConcurrentLinkedQueue<Content>();
    final Set<String> names = new TreeSet<String>();
    Container container = new Container() {

        @Override
        public void add(@CheckForNull Content content) {
            if (content != null) {
                names.add(content.getName());
                toProcess.add(content);
            }
        }
    };
    StringBuilder manifest = new StringBuilder();
    SupportPlugin plugin = SupportPlugin.getInstance();
    SupportProvider supportProvider = plugin == null ? null : plugin.getSupportProvider();
    String bundleName = (supportProvider == null ? "Support" : supportProvider.getDisplayName()) + " Bundle Manifest";
    manifest.append(bundleName).append('\n');
    manifest.append(StringUtils.repeat("=", bundleName.length())).append('\n');
    manifest.append("\n");
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    manifest.append("Generated on ").append(f.format(new Date())).append("\n");
    manifest.append("\n");
    manifest.append("Requested components:\n\n");
    StringWriter errors = new StringWriter();
    PrintWriter errorWriter = new PrintWriter(errors);
    for (Component c : components) {
        try {
            manifest.append("  * ").append(c.getDisplayName()).append("\n\n");
            names.clear();
            c.addContents(container);
            for (String name : names) {
                manifest.append("      - `").append(name).append("`\n\n");
            }
        } catch (Throwable e) {
            String cDisplayName = null;
            try {
                cDisplayName = c.getDisplayName();
            } catch (Throwable e1) {
                // be very defensive
                cDisplayName = c.getClass().getName();
            }
            LogRecord logRecord = new LogRecord(Level.WARNING, "Could not get content from ''{0}'' for support bundle");
            logRecord.setThrown(e);
            logRecord.setParameters(new Object[] { cDisplayName });
            logger.log(logRecord);
            errorWriter.println(MessageFormat.format("Could not get content from ''{0}'' for support bundle", cDisplayName));
            errorWriter.println("-----------------------------------------------------------------------");
            errorWriter.println();
            SupportLogFormatter.printStackTrace(e, errorWriter);
            errorWriter.println();
        }
    }
    toProcess.add(new StringContent("manifest.md", manifest.toString()));
    try {
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(zip, 16384) {

                @Override
                public void close() throws IOException {
                    // don't let any of the contents accidentally close the zip stream
                    super.flush();
                }
            };
            while (!toProcess.isEmpty()) {
                Content c = toProcess.poll();
                if (c == null) {
                    continue;
                }
                final String name = c.getName();
                try {
                    ZipEntry entry = new ZipEntry(name);
                    entry.setTime(c.getTime());
                    zip.putNextEntry(entry);
                    c.writeTo(bos);
                } catch (Throwable e) {
                    LogRecord logRecord = new LogRecord(Level.WARNING, "Could not attach ''{0}'' to support bundle");
                    logRecord.setThrown(e);
                    logRecord.setParameters(new Object[] { name });
                    logger.log(logRecord);
                    errorWriter.println(MessageFormat.format("Could not attach ''{0}'' to support bundle", name));
                    errorWriter.println("-----------------------------------------------------------------------");
                    errorWriter.println();
                    SupportLogFormatter.printStackTrace(e, errorWriter);
                    errorWriter.println();
                } finally {
                    bos.flush();
                }
                zip.flush();
            }
            errorWriter.close();
            String errorContent = errors.toString();
            if (!StringUtils.isBlank(errorContent)) {
                try {
                    zip.putNextEntry(new ZipEntry("manifest/errors.txt"));
                    zip.write(errorContent.getBytes("utf-8"));
                } catch (IOException e) {
                // ignore
                }
                zip.flush();
            }
        } finally {
            zip.close();
        }
    } finally {
        outputStream.flush();
    }
}
Also used : ZipEntry(org.apache.tools.zip.ZipEntry) Logger(java.util.logging.Logger) Container(com.cloudbees.jenkins.support.api.Container) StringWriter(java.io.StringWriter) LogRecord(java.util.logging.LogRecord) TreeSet(java.util.TreeSet) CheckForNull(edu.umd.cs.findbugs.annotations.CheckForNull) Component(com.cloudbees.jenkins.support.api.Component) BufferedOutputStream(java.io.BufferedOutputStream) PrintWriter(java.io.PrintWriter) StringContent(com.cloudbees.jenkins.support.api.StringContent) SupportProvider(com.cloudbees.jenkins.support.api.SupportProvider) IOException(java.io.IOException) Date(java.util.Date) StringContent(com.cloudbees.jenkins.support.api.StringContent) Content(com.cloudbees.jenkins.support.api.Content) ZipOutputStream(org.apache.tools.zip.ZipOutputStream) JSONObject(net.sf.json.JSONObject) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) SimpleDateFormat(java.text.SimpleDateFormat)

Example 3 with Container

use of com.cloudbees.jenkins.support.api.Container in project support-core-plugin by jenkinsci.

the class SupportTestUtils method invokeComponentToString.

/**
 * Invoke a component, and return the component contents as a String.
 */
public static String invokeComponentToString(final Component component) {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    component.addContents(new Container() {

        @Override
        public void add(@CheckForNull Content content) {
            try {
                content.writeTo(baos);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    return baos.toString();
}
Also used : Container(com.cloudbees.jenkins.support.api.Container) Content(com.cloudbees.jenkins.support.api.Content) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 4 with Container

use of com.cloudbees.jenkins.support.api.Container in project support-core-plugin by jenkinsci.

the class AgentsConfigFileTest method agentsConfigFile.

@Test
public void agentsConfigFile() throws Exception {
    j.createSlave("node1", "node1", new EnvVars());
    AgentsConfigFile comp = new AgentsConfigFile();
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    comp.addContents(new Container() {

        @Override
        public void add(@CheckForNull Content content) {
            try {
                content.writeTo(baos);
            } catch (IOException e) {
                Assert.fail(e.getMessage());
            }
        }
    });
    String fileContent = baos.toString();
    Assert.assertTrue(fileContent.contains("<name>node1</name>"));
}
Also used : Container(com.cloudbees.jenkins.support.api.Container) EnvVars(hudson.EnvVars) Content(com.cloudbees.jenkins.support.api.Content) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

Container (com.cloudbees.jenkins.support.api.Container)4 Content (com.cloudbees.jenkins.support.api.Content)4 IOException (java.io.IOException)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 Test (org.junit.Test)2 Component (com.cloudbees.jenkins.support.api.Component)1 StringContent (com.cloudbees.jenkins.support.api.StringContent)1 SupportProvider (com.cloudbees.jenkins.support.api.SupportProvider)1 CheckForNull (edu.umd.cs.findbugs.annotations.CheckForNull)1 EnvVars (hudson.EnvVars)1 BufferedOutputStream (java.io.BufferedOutputStream)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 NetworkInterface (java.net.NetworkInterface)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 TreeSet (java.util.TreeSet)1 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)1 LogRecord (java.util.logging.LogRecord)1 Logger (java.util.logging.Logger)1