Added service to fetch the build version from the manifest.
lbs-gitea/maptology/master This commit looks good

This commit is contained in:
2017-12-05 15:18:09 +01:00
parent b0df31ab42
commit 0ef59cd4b8
12 changed files with 583 additions and 0 deletions
+1
View File
@@ -32,6 +32,7 @@
<location>com.maptology.api.user.IUserService</location>
<location>com.maptology.api.notice.INoticeService</location>
<location>com.maptology.api.log.ILogService</location>
<location>com.maptology.api.version.IVersionService</location>
</locations>
<schemes>
<scheme>http</scheme>
@@ -0,0 +1,130 @@
package com.maptology.api.version;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Information about the build of the application.
*
* @author Marcus
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.ANY,
getterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@ApiModel(description="Represents version information about the running build.")
public class BuildVersion {
/**
* The build time.
*/
@XmlAttribute(required=true)
@ApiModelProperty(value="The build time in Epoch milliseconds.", required=true)
private long time;
/**
* The build number.
*/
@XmlAttribute(required=true)
@ApiModelProperty(value="The build number.", required=true)
private String build;
/**
* The user creating the build.
*/
@XmlAttribute(required=true)
@ApiModelProperty(value="The creator of the build.", required=true)
private String creator;
/**
* The maven package version.
*/
@XmlAttribute(required=true)
@ApiModelProperty(value="The version of the build.", required=true)
private String version;
/**
* Returns the time.
*
* @return The time.
*/
public long getTime() {
return time;
}
/**
* Sets the time.
*
* @param time The time to set.
*/
public void setTime(long time) {
this.time = time;
}
/**
* Returns the build.
*
* @return The build.
*/
public String getBuild() {
return build;
}
/**
* Sets the build.
*
* @param build The build to set.
*/
public void setBuild(String build) {
this.build = build;
}
/**
* Returns the creator.
*
* @return The creator.
*/
public String getCreator() {
return creator;
}
/**
* Sets the creator.
*
* @param creator The creator to set.
*/
public void setCreator(String creator) {
this.creator = creator;
}
/**
* Returns the version.
*
* @return The version.
*/
public String getVersion() {
return version;
}
/**
* Sets the version.
*
* @param version The version to set.
*/
public void setVersion(String version) {
this.version = version;
}
}
@@ -0,0 +1,40 @@
package com.maptology.api.version;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
* An api to retrieve the build version.
*
* @author Marcus
*
*/
@Api
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Path("/")
public interface IVersionService {
/**
* Returns the build version of the service.
*
* @return The build version of the service.
*/
@GET
@Path("version/build")
@ApiOperation(value = "Returns the build version.")
@ApiResponses({
@ApiResponse(code=HttpServletResponse.SC_OK, message="Build version retrieved successfully.", response=BuildVersion.class)
})
Response getBuildVersion();
}
@@ -0,0 +1,6 @@
/**
* A service to fetch build related information.
*
* @author Marcus
*/
package com.maptology.api.version;
@@ -0,0 +1,227 @@
package com.maptology.service.session;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.security.PermitAll;
import javax.ejb.Singleton;
import javax.inject.Inject;
import com.maptology.api.version.BuildVersion;
/**
* The version session bean manages the
* version information about the application.
*
* @author Marcus
*/
@Singleton
public class VersionSessionBean {
/**
* The logger injected by the container.
*/
@Inject
protected Logger log;
/**
* The build version that will be loaded
* upon creation of the bean.
*/
protected BuildVersion buildVersion;
/**
* Loads the version information on startup.
*/
@PostConstruct
protected void loadVersions() {
log.log(Level.INFO, "Loading versions.");
buildVersion = createBuildVersion();
}
/**
* Returns the current build version.
*
* @return The build version.
*/
@PermitAll
public BuildVersion getBuildVersion() {
return buildVersion;
}
/**
* Loads and returns the build version.
*
* @return A new build version.
*/
protected BuildVersion createBuildVersion() {
BuildVersion result = new BuildVersion();
result.setBuild("");
result.setCreator("");
result.setTime(System.currentTimeMillis());
result.setVersion("");
Manifest mf = getManifest(VersionSessionBean.class);
if (mf != null) {
Attributes attributes = mf.getMainAttributes();
String version = attributes.getValue("Implementation-Version");
if (version != null) result.setVersion(version);
else log.log(Level.INFO, "No version found using default.");
String creator = attributes.getValue("Built-By");
if (creator != null) result.setCreator(creator);
else log.log(Level.INFO, "No creator found using default.");
String build = attributes.getValue("Implementation-Build");
if (build != null) result.setBuild(build);
else log.log(Level.INFO, "No build found using default.");
} else {
log.log(Level.INFO, "Failed to load manifest.");
}
Long time = getTime(VersionSessionBean.class);
if (time != null) result.setTime(time);
else log.log(Level.INFO, "No time found using load time.");
return result;
}
/**
* Tries to load the manifest file (unpacked and packed).
*
* @param type The class file to load the manifest for.
* @return The manifest file (if successful) or null.
*/
protected Manifest getManifest(Class<?> type) {
ProtectionDomain domain = type.getProtectionDomain();
if (domain != null) {
CodeSource codeSource = domain.getCodeSource();
if (codeSource != null) {
URL url = codeSource.getLocation();
log.log(Level.INFO, "Code source is: '" + url.toExternalForm() + "'.");
String[] paths = url.getPath().split("/");
String[] endings = new String[] { ".ear", ".war", ".jar" };
// create a list of urls in reverse order that end with ear, war or jar
StringBuilder current = new StringBuilder();
List<URL> urls = new ArrayList<>();
for (String path: paths) {
current.append(path);
for (String ending: endings) {
if (path.endsWith(ending)) {
try {
URL load = new URL(url.getProtocol(), url.getHost(), url.getPort(), current.toString());
urls.add(0, load);
} catch (MalformedURLException e) {
log.log(Level.INFO, "Failed to create url.", e);
}
break;
}
}
current.append("/");
}
// try load them in their reverse order (most specific url first)
for (URL load: urls) {
log.log(Level.INFO, "Searching manifest in '" + load.toExternalForm() + "'.");
Manifest m = getExplodedManifest(load);
if (m == null) m = getPackedManifest(load);
if (m != null) return m;
}
}
}
return null;
}
/**
* Tries to load a manifest from an url that points to an exploded file.
*
* @param url The url.
* @return The manifest.
*/
protected Manifest getExplodedManifest(URL url) {
InputStream manifestStream = null;
try {
URL mfUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getPath() + "/" + JarFile.MANIFEST_NAME);
log.log(Level.INFO, "Loading exploded manifest from '" + mfUrl.toExternalForm() + "'.");
manifestStream = mfUrl.openStream();
return new Manifest(manifestStream);
} catch (Exception e) {
log.log(Level.INFO, "Failed to load exploded manifest.");
} finally {
if (manifestStream != null) {
try {
manifestStream.close();
} catch (IOException e) {
log.log(Level.INFO, "Failed to close stream to manifest file.");
}
}
}
return null;
}
/**
* Tries to load a manifest from an url that points to a jar.
*
* @param url The url pointing to the jar.
* @return The manifest or null.
*/
protected Manifest getPackedManifest(URL url) {
JarInputStream jis = null;
try {
log.log(Level.INFO, "Loading packed manifest from '" + url.toExternalForm() + "'.");
URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof JarURLConnection) {
log.log(Level.INFO, "Loading via jar connection.");
JarURLConnection jarUrlConnection = (JarURLConnection) urlConnection;
return jarUrlConnection.getManifest();
} else {
log.log(Level.INFO, "Loading via input stream.");
jis = new JarInputStream(urlConnection.getInputStream());
return jis.getManifest();
}
} catch (IOException e) {
log.log(Level.INFO, "Failed to load packed manifest.");
} finally {
if (jis != null) {
try {
jis.close();
} catch (IOException e) {
log.log(Level.INFO, "Failed to close stream to manifest file.");
}
}
}
return null;
}
/**
* Returns the modification date of the code source.
*
* @param type The type to find the code source.
* @return The time in system millis or null, if a failure occurs.
*/
protected Long getTime(Class<?> type) {
ProtectionDomain domain = type.getProtectionDomain();
if (domain == null) return null;
CodeSource codeSource = domain.getCodeSource();
if (codeSource == null) return null;
URL url = codeSource.getLocation();
if (url == null) return null;
try {
URLConnection c = url.openConnection();
return c.getLastModified();
} catch (IOException e) {
log.log(Level.INFO, "Failed to load the build time.");
return null;
}
}
}
@@ -3,6 +3,7 @@ package com.maptology.service.test;
import java.io.File;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
/**
@@ -23,6 +24,7 @@ public class EjbDeployment {
*/
public static JavaArchive createEjb() {
return ShrinkWrap.create(JavaArchive.class)
.addAsManifestResource(new StringAsset(getManifest()), "MANIFEST.MF")
.addPackages(true, "com.maptology.api", "com.maptology.service")
.addAsManifestResource(new File("src/test/resources/META-INF/beans.xml"), "beans.xml")
// use the persistence.xml from the test resource (in-memory db)
@@ -30,4 +32,18 @@ public class EjbDeployment {
.addAsResource(new File("src/test/resources/emails/"), "/emails/");
}
/**
* Returns a default manifest for testing.
*
* @return The manifest.
*/
private static String getManifest() {
StringBuilder b = new StringBuilder();
b.append("Manifest-Version: 1.0\n");
b.append("Implementation-Version: version\n");
b.append("Implementation-Build: build\n");
b.append("Built-By: creator\n\n");
return b.toString();
}
}
@@ -0,0 +1,40 @@
package com.maptology.service.test.session;
import javax.inject.Inject;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.maptology.api.version.BuildVersion;
import com.maptology.service.session.VersionSessionBean;
/**
* A test case for the version session bean.
*
* @author Marcus
*/
@RunWith(Arquillian.class)
public class VersionSessionTest extends AbstractSessionTest {
@Inject
VersionSessionBean versionSession;
/**
* Tests whether the get version call returns the manifest
* values defined in the ejb deployment.
*/
@Test
public void testGetBuildVersion() {
BuildVersion v = versionSession.getBuildVersion();
Assert.assertNotNull("Should receive a version.", v);
Assert.assertEquals("Creator should be set.", "creator", v.getCreator());
Assert.assertEquals("Version should be set.", "version", v.getVersion());
Assert.assertEquals("Build should be set.", "build", v.getBuild());
}
}
@@ -2,6 +2,7 @@ package com.maptology.service.swarm;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.formatter.Formatters;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.config.datasources.DataSource;
@@ -45,6 +46,8 @@ public class MaptologySwarm {
Swarm swarm = new Swarm();
// create the deployment
JAXRSArchive deployment = ShrinkWrap.create(JAXRSArchive.class);
// add manifest
deployment.addAsManifestResource(new StringAsset(getManifest()), "MANIFEST.MF");
// add code
deployment.addPackages(true, "com.maptology.api");
deployment.addPackages(true, "com.maptology.service");
@@ -65,6 +68,23 @@ public class MaptologySwarm {
swarm.deploy(deployment);
}
/**
* Returns a default manifest.
*
* @return The manifest.
*/
private static String getManifest() {
StringBuilder b = new StringBuilder();
b.append("Manifest-Version: 1.0\n");
b.append("Implementation-Version: swarms\n");
b.append("Implementation-Build: in-memory\n");
b.append("Built-By: ");
b.append(System.getProperty("user.name"));
b.append("\n\n");
return b.toString();
}
/**
* Unused example on how to configure a datasource using the datasources fraction.
*
@@ -10,6 +10,7 @@ import com.maptology.service.access.AccessControlFilter;
import com.maptology.service.rest.LogResource;
import com.maptology.service.rest.NoticeResource;
import com.maptology.service.rest.UserResource;
import com.maptology.service.rest.VersionResource;
/**
* The application is the main entry point of JAX-RS.
@@ -27,6 +28,7 @@ public class MaptologyApplication extends Application {
classes.add(UserResource.class);
classes.add(NoticeResource.class);
classes.add(LogResource.class);
classes.add(VersionResource.class);
return classes;
}
@@ -0,0 +1,46 @@
package com.maptology.service.rest;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import com.maptology.api.version.BuildVersion;
import com.maptology.api.version.IVersionService;
import com.maptology.service.session.VersionSessionBean;
/**
* Implements the versions service.
*
* @author Marcus
*/
@Stateless
public class VersionResource implements IVersionService {
/**
* The version session to compute the response.
*/
@EJB
protected VersionSessionBean versionSession;
/**
* The request to support caching.
*/
@Context
protected Request request;
@Override
public Response getBuildVersion() {
BuildVersion version = versionSession.getBuildVersion();
EntityTag tag = new EntityTag(Long.toString(version.getTime()));
ResponseBuilder response = request.evaluatePreconditions(tag);
if (response == null) {
response = Response.ok(version);
}
return response.tag(tag).build();
}
}
@@ -4,6 +4,7 @@ import java.io.File;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
@@ -34,6 +35,7 @@ public class WarDeployment {
.addAsResource(new ClassLoaderAsset("emails/new-email.txt"), "emails/new-email.txt")
.addAsResource(new ClassLoaderAsset("emails/new-user.txt"), "emails/new-user.txt")
.addAsResource(new ClassLoaderAsset("emails/reset-user.txt"), "emails/reset-user.txt")
.addAsManifestResource(new StringAsset(getManifest()), "MANIFEST.MF")
.addAsManifestResource(new File("src/test/resources/META-INF/beans.xml"), "beans.xml")
.addAsManifestResource(new File("src/test/resources/META-INF/jboss-ejb3.xml"), "jboss-ejb3.xml")
.addAsManifestResource(new File("src/test/resources/META-INF/persistence.xml"), "persistence.xml");
@@ -70,4 +72,19 @@ public class WarDeployment {
.addAsModule(createWar());
}
/**
* Returns a default manifest for testing.
*
* @return The manifest.
*/
private static String getManifest() {
StringBuilder b = new StringBuilder();
b.append("Manifest-Version: 1.0\n");
b.append("Implementation-Version: version\n");
b.append("Implementation-Build: build\n");
b.append("Built-By: creator\n\n");
return b.toString();
}
}
@@ -0,0 +1,38 @@
package com.maptology.service.test.rest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.maptology.api.version.BuildVersion;
import com.maptology.api.version.IVersionService;
/**
* Tests the version resource against the properties
* defined in the war deployment class.
*
* @author Marcus
*/
@RunWith(Arquillian.class)
public class VersionResourceTest extends AbstractResourceTest {
/**
* Tests the get build version method against the war deployment values.
*/
@Test
public void testGetBuildVersion() {
IVersionService service = getTarget().proxy(IVersionService.class);
Response r = service.getBuildVersion();
Assert.assertEquals("Should be ok.", HttpServletResponse.SC_OK, r.getStatus());
BuildVersion v = r.readEntity(BuildVersion.class);
Assert.assertNotNull("Should receive a version.", v);
Assert.assertEquals("Creator should be set.", "creator", v.getCreator());
Assert.assertEquals("Version should be set.", "version", v.getVersion());
Assert.assertEquals("Build should be set.", "build", v.getBuild());
}
}