Sunday, August 9, 2015

Read package name and version from Manifest file

Bean: 

public class BuildVersion {
   
    /** The build name. */
    private String buildName;
   
    /** The version. */
    private String version;

    /**
     * Gets the version.
     *
     * @return the version
     */
    public String getVersion() {
        return version;
    }

    /**
     * set version.
     *
     * @param version the new version
     */
    public void setVersion(String version) {
        this.version = version;
    }

    /**
     * Gets the builds the name.
     *
     * @return the builds the name
     */
    public String getBuildName() {
        return buildName;
    }

    /**
     * Sets the builds the name.
     *
     * @param buildName the new builds the name
     */
    public void setBuildName(String buildName) {
        this.buildName = buildName;
    }
}

VersionServiceImpl:

private BuildVersion getBuildVersion() {
        BuildVersion buildVersion = new BuildVersion();

        Class clazz = this.getClass();
        String className = clazz.getSimpleName() + ".class";
        String classPath = clazz.getResource(className).toString();
        try {
            String manifestPath = classPath.substring(0, classPath.lastIndexOf("/WEB-INF")) +
                    "/META-INF/MANIFEST.MF";
            Manifest manifest = new Manifest(new URL(manifestPath).openStream());
            Attributes attr = manifest.getMainAttributes();
            String title = attr.getValue("Specification-Title");
            String version = attr.getValue("Specification-Version");

            buildVersion.setBuildName(title);
            buildVersion.setVersion(version);
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
        return buildVersion;
    }

VersionEndpoint:

@Component
@Path ("/")
public class VersionEndpoint {
   
    /** The version service. */
    @Autowired
    private VersionService versionService;
   
    /**
     * getVersion service use to retrieve the current release version.   
     *
     * @param format the format
     * @return Version response
     */
    @GET
    @Path ("/version")
    @Produces ({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public Response getVersion(@DefaultValue (WSConstants.RESPONSE_TYPE_JSON) @QueryParam ("format") String format) {
        try {
            return Response.ok().entity(versionService.getVersion()).type(WSUtil.getWSResponseType(format)).build();
        } catch (Exception e) {
            return Response.ok().entity("Error: "  + e.getMessage()).type(WSUtil.getWSResponseType(format)).build();
        }       
    }                                       
}

No comments:

Post a Comment