OraMonRESTgetData.java 8.55 KB


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import se.lil.om.OraMon;
import se.lil.om.Registry;

/**
 * Servlet implementation class OraMonREST
 */
@WebServlet(description = "REST API for OraMon", urlPatterns = { "/OraMonREST/getData" })
public class OraMonRESTgetData extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OraMonRESTgetData() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		try {
			StringBuffer sb = new StringBuffer();
			int age = 0;
			if(request.getParameterMap().containsKey("age")) {
				try {
					age = Integer.parseInt(request.getParameter("age"));
				} catch (Exception e) {
					response.setStatus(400);
					response.getWriter().println("{\"error\":true,\"msg\":\"The specified age parameter is not a valid integer number\"}");
					return;
				}
			}
			
			if(request.getParameterMap().containsKey("connectionString")) {
				// We have a connection string, find the monitor or create it and call getData() on the monitor
				OraMon monitor = null;
				if(request.getParameter("connectionString").startsWith("jdbc:oracle")) {
					// Full con string
					String[] shortConArray = request.getParameter("connectionString").split("@");
					if(shortConArray.length != 2) {
						// Error, wrong format of string
						response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
						response.getWriter().println("{\"error\":true,\"msg\":\"connectionString needs to be in format jdbc:oracle:thin:@//host:port/servicename or jdbc:oracle:thin:@(<TNS Connection String>) with optional :username:password at the end.\"}");
						return;
					}
					String[] shortConArray2 = shortConArray[1].split(":");
					if(shortConArray2[0].startsWith("(")) {
						// TNS Format
						if(shortConArray2.length == 3) {
							// We have a TNS connection string and username + password
							monitor = Registry.findOrCreate(shortConArray[0] + "@" + shortConArray2[0], shortConArray2[1], shortConArray2[2]);
						} else if (shortConArray2.length == 1) {
							// We only have the TNS connection string, no username or password
							monitor = Registry.find(shortConArray[0] + "@" + shortConArray2[0]);
						} else {
							// We have something else, not implemented
							response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
							response.getWriter().println("{\"error\":true,\"msg\":\"connectionString needs to be in format jdbc:oracle:thin:@(<TNS Connection String>) with optional :username:password at the end.\"}");
							return;
						}
					} else {
						// JDBC Format
						if(shortConArray2[0].startsWith("//") && shortConArray2.length == 4) {
							// We have new style and username and password, we can try to create the monitor if it doesnt exist
							monitor = Registry.findOrCreate(shortConArray[0] +  "@" + shortConArray2[0] + ":" + shortConArray2[1], shortConArray2[2], shortConArray2[3]);
						} else if(!shortConArray2[0].startsWith("//") && shortConArray2.length == 5) {
							// We have old style with sid with :username:password, try to find or create it
							monitor = Registry.findOrCreate(shortConArray[0] +  "@" + shortConArray2[0] + ":" + shortConArray2[1] + ":" + shortConArray2[2], shortConArray2[3], shortConArray2[4]);
						} else if(shortConArray2[0].startsWith("//") && shortConArray2.length == 2) {
							// We have new style but only have the connection string, try to find it (we cant create one without username/password)
							monitor = Registry.find(request.getParameter("connectionString"));
						} else if(!shortConArray2[0].startsWith("//") && shortConArray2.length == 3) {
							// We have old style sid and no :username:password
							monitor = Registry.find(request.getParameter("connectionString"));
						} else {
							// Wrong format
							response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
							response.getWriter().println("{\"error\":true,\"msg\":\"connectionString needs to be in format jdbc:oracle:thin:@//host:port/servicename with optional :username:password at the end.\"}");
							return;
						}
					}
				} else {
					// Short con string
					// Check that we have a valid connection string (added support to handle diffrent kinds of connection strings)
					String[] conStrParamArray = request.getParameter("connectionString").split(":");
					Boolean serviceName = false;
					if(conStrParamArray.length == 4) {
						// Check if service name is used ( / instead of : )
						if(conStrParamArray[1].indexOf("/") >= 0) {
							serviceName = true;
						}
					}
					if(conStrParamArray.length != 5 && serviceName == false) {
						// Error, we need 5 parts in the connection string
						response.setStatus(400);
						response.getWriter().println("{\"error\":true,\"msg\":\"connectionString needs to be in format host:port:sid:username:password or host:port/servicename:username:password\"}");
						return;
					}
					String conStr, usrStr, pwdStr;
					if(serviceName) {
						conStr = "jdbc:oracle:thin:@//" + conStrParamArray[0] + ":" + conStrParamArray[1];
						usrStr = conStrParamArray[2];
						pwdStr = conStrParamArray[3];
					} else {
						conStr = "jdbc:oracle:thin:@" + conStrParamArray[0] + ":" + conStrParamArray[1] + ":" + conStrParamArray[2];
						usrStr = conStrParamArray[3];
						pwdStr = conStrParamArray[4];
					}
					
					// Try to find the monitor in our list
					monitor = Registry.findOrCreate(conStr, usrStr, pwdStr);
				}
				
				String pdbName = null;
				if(request.getParameterMap().containsKey("pdbName")) { 
					String temp = request.getParameter("pdbName");
					if (!temp.isEmpty()) pdbName = temp;
				}
				
				if(monitor != null) {
					// Call getData()
					boolean didUpdate = monitor.getData(age,pdbName);
					String dbName = monitor.getFriendlyName(pdbName);
					if(didUpdate) {
						sb.append("{\"error\":false,\"msg\":\"Sucessfully collected data on '" + dbName + "'\"");
						sb.append(",\"ms\":"+monitor.getLastRTms()+"}");
					} else {
						response.setStatus(HttpServletResponse.SC_ACCEPTED);
						sb.append("{\"error\":false");
						sb.append(",\"msg\":\"Data does not need to be updated on '" + dbName + "' either because another thread did concurrently update the monitor and we just waited for it to complete, or because the age (if) specified was higher than the monitors data age.\"");
						sb.append(",\"age\":"+monitor.getAgeTs()+"}");
					}
				} else {
					response.setStatus(HttpServletResponse.SC_NOT_FOUND);
					sb.append("{\"error\":true,\"msg\":\"Monitor not found and can't create one without :username:password '" + request.getParameter("connectionString") + "'\"");
					sb.append("}");
				}
				
			} else {
				// No input, just return the list of monitors
				sb.append("{\"count\":" + Registry.getList().size() + "}");
			}
			
			response.getWriter().println(sb.toString());
			
		} catch (Throwable e) {
			response.setStatus(500);
			response.getWriter().println("{\"error\":true,\"msg\":\""+e.toString().replace("\n"," ").replace("\"","\\\"").trim()+"\"}");
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse)
	 */
	protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doDelete(HttpServletRequest, HttpServletResponse)
	 */
	protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doHead(HttpServletRequest, HttpServletResponse)
	 */
	protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}