View Javadoc
1   package de.mxro.webapiexample.internal.services;
2   
3   import java.io.FileInputStream;
4   import java.io.FileNotFoundException;
5   import java.io.IOException;
6   import java.io.InputStream;
7   import java.util.Properties;
8   
9   import javax.servlet.ServletException;
10  import javax.servlet.http.HttpServlet;
11  import javax.servlet.http.HttpServletRequest;
12  import javax.servlet.http.HttpServletResponse;
13  
14  import delight.json.JSON;
15  import delight.json.JSONObject;
16  
17  /**
18   * <p>
19   * This service provides some metadata information about this server.
20   * 
21   * @author Max
22   *
23   */
24  public class ApplicationMetadataServlet extends HttpServlet {
25  
26  	private static final long serialVersionUID = 1L;
27  
28  	// this service will always return the same response, so we can pre-render it at service initialisation.
29  	private String cachedResponse = null;
30  	
31  
32  	@Override
33  	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
34  		
35  		response.setContentType("application/json");
36  		response.setStatus(HttpServletResponse.SC_OK);
37  		
38  		response.getWriter().println(cachedResponse);
39  		
40  	}
41  
42  	@Override
43  	public void init() throws ServletException {
44  		super.init();
45  
46  		readPropertiesAndRenderResponse();
47  
48  	}
49  
50  	private void readPropertiesAndRenderResponse() {
51  		Properties prop = new Properties();
52  		
53  		ClassLoader loader = Thread.currentThread().getContextClassLoader();
54  		
55  		try (InputStream input = loader.getResourceAsStream("versioninfo.txt")) {
56  
57  			// load a properties file
58  			prop.load(input);
59  			
60  			JSONObject jsonObject = JSON.create();
61  			jsonObject.add("version", prop.getProperty("version"));
62  			jsonObject.add("description", prop.getProperty("description"));
63  			jsonObject.add("lastcommit", prop.getProperty("lastcommit"));
64  			
65  			cachedResponse = jsonObject.render();
66  			
67  
68  		} catch (FileNotFoundException e) {
69  			throw new RuntimeException(e);
70  		} catch (IOException e) {
71  			throw new RuntimeException(e);
72  		}
73  	}
74  
75  }