Skip to content

Commit

Permalink
Demonstrating usage of SetContextClassLoader
Browse files Browse the repository at this point in the history
  • Loading branch information
basil committed Sep 25, 2023
1 parent 1a02e91 commit 48dec5b
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 14 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<properties>
<revision>2.3.8-2</revision>
<changelist>-SNAPSHOT</changelist>
<jenkins.version>2.361.4</jenkins.version>
<jenkins.version>2.387.3</jenkins.version>
<gitHubRepo>jenkinsci/${project.artifactId}-plugin</gitHubRepo>
</properties>

Expand Down
18 changes: 5 additions & 13 deletions src/test/java/io/jenkins/plugins/jaxb/JAXBContextTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import jenkins.util.SetContextClassLoader;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
Expand All @@ -31,8 +31,11 @@ private static void _smokes(JenkinsRule r) throws Throwable {
Book book = new Book();
book.setId(1L);
book.setName("Guide to JAXB");
JAXBContext context;
try (SetContextClassLoader sccl = new SetContextClassLoader(RealJenkinsRule.Endpoint.class)) {
context = JAXBContext.newInstance(Book.class);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JAXBContext context = getJAXBContext(Book.class);
context.createMarshaller().marshal(book, baos);
String xml = baos.toString(StandardCharsets.US_ASCII.name());
assertThat(xml, containsString("<book id=\"1\"><title>Guide to JAXB</title></book>"));
Expand All @@ -41,17 +44,6 @@ private static void _smokes(JenkinsRule r) throws Throwable {
assertEquals(book.getName(), book2.getName());
}

private static JAXBContext getJAXBContext(Class<?>... classesToBeBound) throws JAXBException {
Thread t = Thread.currentThread();
ClassLoader orig = t.getContextClassLoader();
t.setContextClassLoader(RealJenkinsRule.Endpoint.class.getClassLoader());
try {
return JAXBContext.newInstance(classesToBeBound);
} finally {
t.setContextClassLoader(orig);
}
}

@XmlRootElement(name = "book")
@XmlType(propOrder = {"id", "name"})
static class Book {
Expand Down

0 comments on commit 48dec5b

Please sign in to comment.