test_class.declarator: apiServer
test_class.modifier: @Mock
test_class.original_string: @Mock
      ApiServer apiServer;
test_class.type: ApiServer
test_class.var_name: apiServer
test_class.declarator: request
test_class.modifier: @Mock
test_class.original_string: @Mock
      HttpServletRequest request;
test_class.type: HttpServletRequest
test_class.var_name: request
test_class.declarator: response
test_class.modifier: @Mock
test_class.original_string: @Mock
      HttpServletResponse response;
test_class.type: HttpServletResponse
test_class.var_name: response
test_class.declarator: accountService
test_class.modifier: @Mock
test_class.original_string: @Mock
      AccountService accountService;
test_class.type: AccountService
test_class.var_name: accountService
test_class.declarator: authManager
test_class.modifier: @Mock
test_class.original_string: @Mock
      APIAuthenticationManager authManager;
test_class.type: APIAuthenticationManager
test_class.var_name: authManager
test_class.declarator: authenticator
test_class.modifier: @Mock
test_class.original_string: @Mock
      APIAuthenticator authenticator;
test_class.type: APIAuthenticator
test_class.var_name: authenticator
test_class.declarator: user
test_class.modifier: @Mock
test_class.original_string: @Mock
      User user;
test_class.type: User
test_class.var_name: user
test_class.declarator: account
test_class.modifier: @Mock
test_class.original_string: @Mock
      Account account;
test_class.type: Account
test_class.var_name: account
test_class.declarator: session
test_class.modifier: @Mock
test_class.original_string: @Mock
      HttpSession session;
test_class.type: HttpSession
test_class.var_name: session
test_class.declarator: managementServer
test_class.modifier: @Mock
test_class.original_string: @Mock
      ManagementServer managementServer;
test_class.type: ManagementServer
test_class.var_name: managementServer
test_class.declarator: responseWriter
test_class.original_string: StringWriter responseWriter;
test_class.type: StringWriter
test_class.var_name: responseWriter
test_class.declarator: servlet
test_class.original_string: ApiServlet servlet;
test_class.type: ApiServlet
test_class.var_name: servlet
test_class.file: cosmic-core/server/src/test/java/com/cloud/api/ApiServletTest.java
test_class.identifier: ApiServletTest
test_case.body: @Test
      public void processRequestInContextLogout() throws UnknownHostException {
          Mockito.when(request.getMethod()).thenReturn("GET");
          Mockito.when(request.getSession(Mockito.anyBoolean())).thenReturn(
                  session);
          Mockito.when(session.getAttribute("userid")).thenReturn(1l);
          Mockito.when(session.getAttribute("accountobj")).thenReturn(account);
          final HashMap<String, String[]> params = new HashMap<>();
          params.put(ApiConstants.COMMAND, new String[]{"logout"});
          Mockito.when(request.getParameterMap()).thenReturn(params);
  
          Mockito.when(authenticator.getAPIType()).thenReturn(APIAuthenticationType.LOGOUT_API);
  
          servlet.processRequestInContext(request, response);
  
          Mockito.verify(authManager).getAPIAuthenticator("logout");
          Mockito.verify(authenticator).authenticate(Mockito.anyString(), Mockito.anyMap(), Mockito.isA(HttpSession.class),
                  Mockito.eq(InetAddress.getByName("127.0.0.1")), Mockito.anyString(), Mockito.isA(StringBuilder.class), Mockito.isA(HttpServletRequest.class), Mockito.isA
                          (HttpServletResponse.class));
          Mockito.verify(session).invalidate();
      }
test_case.class_method_signature: ApiServletTest.processRequestInContextLogout()
test_case.full_signature: @Test public void processRequestInContextLogout()
test_case.identifier: processRequestInContextLogout
test_case.invocations: thenReturn when getMethod thenReturn when getSession anyBoolean thenReturn when getAttribute thenReturn when getAttribute put thenReturn when getParameterMap thenReturn when getAPIType processRequestInContext getAPIAuthenticator verify authenticate verify anyString anyMap isA eq getByName anyString isA isA isA invalidate verify
test_case.modifiers: @Test public
test_case.parameters: ()
test_case.return: void
test_case.signature: void processRequestInContextLogout()
focal_class.declarator: s_logger = LoggerFactory.getLogger(ApiServlet.class.getName())
focal_class.modifier: public static final
focal_class.original_string: public static final Logger s_logger = LoggerFactory.getLogger(ApiServlet.class.getName());
focal_class.type: Logger
focal_class.var_name: s_logger
focal_class.declarator: s_clientAddressHeaders = Collections
              .unmodifiableList(Arrays.asList("X-Forwarded-For",
                      "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "Remote_Addr"))
focal_class.modifier: private final static
focal_class.original_string: private final static List<String> s_clientAddressHeaders = Collections
              .unmodifiableList(Arrays.asList("X-Forwarded-For",
                      "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "Remote_Addr"));
focal_class.type: List<String>
focal_class.var_name: s_clientAddressHeaders
focal_class.declarator: _apiServer
focal_class.modifier: @Inject
focal_class.original_string: @Inject
      ApiServerService _apiServer;
focal_class.type: ApiServerService
focal_class.var_name: _apiServer
focal_class.declarator: _accountMgr
focal_class.modifier: @Inject
focal_class.original_string: @Inject
      AccountService _accountMgr;
focal_class.type: AccountService
focal_class.var_name: _accountMgr
focal_class.declarator: _entityMgr
focal_class.modifier: @Inject
focal_class.original_string: @Inject
      EntityManager _entityMgr;
focal_class.type: EntityManager
focal_class.var_name: _entityMgr
focal_class.declarator: _managedContext
focal_class.modifier: @Inject
focal_class.original_string: @Inject
      ManagedContext _managedContext;
focal_class.type: ManagedContext
focal_class.var_name: _managedContext
focal_class.declarator: _authManager
focal_class.modifier: @Inject
focal_class.original_string: @Inject
      APIAuthenticationManager _authManager;
focal_class.type: APIAuthenticationManager
focal_class.var_name: _authManager
focal_class.file: cosmic-core/server/src/main/java/com/cloud/api/ApiServlet.java
focal_class.identifier: ApiServlet
focal_class.class_method_signature: ApiServlet.ApiServlet()
focal_class.full_signature: public  ApiServlet()
focal_class.identifier: ApiServlet
focal_class.modifiers: public
focal_class.parameters: ()
focal_class.signature:  ApiServlet()
focal_class.class_method_signature: ApiServlet.init(final ServletConfig config)
focal_class.full_signature: @Override public void init(final ServletConfig config)
focal_class.identifier: init
focal_class.modifiers: @Override public
focal_class.parameters: (final ServletConfig config)
focal_class.return: void
focal_class.signature: void init(final ServletConfig config)
focal_class.class_method_signature: ApiServlet.doGet(final HttpServletRequest req, final HttpServletResponse resp)
focal_class.full_signature: @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
focal_class.identifier: doGet
focal_class.modifiers: @Override protected
focal_class.parameters: (final HttpServletRequest req, final HttpServletResponse resp)
focal_class.return: void
focal_class.signature: void doGet(final HttpServletRequest req, final HttpServletResponse resp)
focal_class.class_method_signature: ApiServlet.doPost(final HttpServletRequest req, final HttpServletResponse resp)
focal_class.full_signature: @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
focal_class.identifier: doPost
focal_class.modifiers: @Override protected
focal_class.parameters: (final HttpServletRequest req, final HttpServletResponse resp)
focal_class.return: void
focal_class.signature: void doPost(final HttpServletRequest req, final HttpServletResponse resp)
focal_class.class_method_signature: ApiServlet.processRequest(final HttpServletRequest req, final HttpServletResponse resp)
focal_class.full_signature: private void processRequest(final HttpServletRequest req, final HttpServletResponse resp)
focal_class.identifier: processRequest
focal_class.modifiers: private
focal_class.parameters: (final HttpServletRequest req, final HttpServletResponse resp)
focal_class.return: void
focal_class.signature: void processRequest(final HttpServletRequest req, final HttpServletResponse resp)
focal_class.class_method_signature: ApiServlet.processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp)
focal_class.full_signature:  void processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp)
focal_class.identifier: processRequestInContext
focal_class.parameters: (final HttpServletRequest req, final HttpServletResponse resp)
focal_class.return: void
focal_class.signature: void processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp)
focal_class.class_method_signature: ApiServlet.denyAuthenticationRequest(final HttpServletResponse resp, final StringBuilder auditTrailSb, final String responseType, final Map<String, Object[]> params, final
      HttpSession session)
focal_class.full_signature: private void denyAuthenticationRequest(final HttpServletResponse resp, final StringBuilder auditTrailSb, final String responseType, final Map<String, Object[]> params, final
      HttpSession session)
focal_class.identifier: denyAuthenticationRequest
focal_class.modifiers: private
focal_class.parameters: (final HttpServletResponse resp, final StringBuilder auditTrailSb, final String responseType, final Map<String, Object[]> params, final
      HttpSession session)
focal_class.return: void
focal_class.signature: void denyAuthenticationRequest(final HttpServletResponse resp, final StringBuilder auditTrailSb, final String responseType, final Map<String, Object[]> params, final
      HttpSession session)
focal_class.class_method_signature: ApiServlet.getClientAddress(final HttpServletRequest request)
focal_class.full_signature: static String getClientAddress(final HttpServletRequest request)
focal_class.identifier: getClientAddress
focal_class.modifiers: static
focal_class.parameters: (final HttpServletRequest request)
focal_class.return: String
focal_class.signature: String getClientAddress(final HttpServletRequest request)
focal_class.class_method_signature: ApiServlet.utf8Fixup(final HttpServletRequest req, final Map<String, Object[]> params)
focal_class.full_signature:  void utf8Fixup(final HttpServletRequest req, final Map<String, Object[]> params)
focal_class.identifier: utf8Fixup
focal_class.parameters: (final HttpServletRequest req, final Map<String, Object[]> params)
focal_class.return: void
focal_class.signature: void utf8Fixup(final HttpServletRequest req, final Map<String, Object[]> params)
focal_class.class_method_signature: ApiServlet.getCorrectIPAddress(final String ip)
focal_class.full_signature: private static String getCorrectIPAddress(final String ip)
focal_class.identifier: getCorrectIPAddress
focal_class.modifiers: private static
focal_class.parameters: (final String ip)
focal_class.return: String
focal_class.signature: String getCorrectIPAddress(final String ip)
focal_class.class_method_signature: ApiServlet.decodeUtf8(final String value)
focal_class.full_signature: private String decodeUtf8(final String value)
focal_class.identifier: decodeUtf8
focal_class.modifiers: private
focal_class.parameters: (final String value)
focal_class.return: String
focal_class.signature: String decodeUtf8(final String value)
focal_class.superclass: extends HttpServlet
focal_method.body: void processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp) {
          final String remoteAddress = getClientAddress(req);
          final StringBuilder auditTrailSb = new StringBuilder(128);
          auditTrailSb.append(" ").append(remoteAddress);
          auditTrailSb.append(" -- ").append(req.getMethod()).append(' ');
          // get the response format since we'll need it in a couple of places
          String responseType = HttpUtils.RESPONSE_TYPE_XML;
          final Map<String, Object[]> params = new HashMap<>();
          params.putAll(req.getParameterMap());
  
          // For HTTP GET requests, it seems that HttpServletRequest.getParameterMap() actually tries
          // to unwrap URL encoded content from ISO-9959-1.
          // After failed in using setCharacterEncoding() to control it, end up with following hacking:
          // for all GET requests, we will override it with our-own way of UTF-8 based URL decoding.
          utf8Fixup(req, params);
  
          // logging the request start and end in management log for easy debugging
          String reqStr = "";
          final String cleanQueryString = StringUtils.cleanString(req.getQueryString());
          if (s_logger.isDebugEnabled()) {
              reqStr = auditTrailSb.toString() + " " + cleanQueryString;
              s_logger.debug("===START=== " + reqStr);
          }
  
          try {
  
              if (HttpUtils.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
                  resp.setContentType(ApiServer.getJSONContentType());
              } else if (HttpUtils.RESPONSE_TYPE_XML.equalsIgnoreCase(responseType)) {
                  resp.setContentType(HttpUtils.XML_CONTENT_TYPE);
              }
  
              HttpSession session = req.getSession(false);
              final Object[] responseTypeParam = params.get(ApiConstants.RESPONSE);
              if (responseTypeParam != null) {
                  responseType = (String) responseTypeParam[0];
              }
  
              final Object[] commandObj = params.get(ApiConstants.COMMAND);
              if (commandObj != null) {
                  final String command = (String) commandObj[0];
  
                  final APIAuthenticator apiAuthenticator = _authManager.getAPIAuthenticator(command);
                  if (apiAuthenticator != null) {
                      auditTrailSb.append("command=");
                      auditTrailSb.append(command);
  
                      int httpResponseCode = HttpServletResponse.SC_OK;
                      String responseString;
  
                      if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGIN_API) {
                          if (session != null) {
                              try {
                                  session.invalidate();
                              } catch (final IllegalStateException e) {
                                  s_logger.warn("Previously ignored exception", e);
                              }
                          }
                          session = req.getSession(true);
                          if (ApiServer.isSecureSessionCookieEnabled()) {
                              resp.setHeader("SET-COOKIE", String.format("JSESSIONID=%s;Secure;HttpOnly;Path=/client", session.getId()));
                              s_logger.debug("Session cookie is marked secure!");
                          }
                      }
  
                      try {
                          responseString = apiAuthenticator.authenticate(command, params, session, InetAddress.getByName(remoteAddress), responseType, auditTrailSb, req, resp);
                          if (session != null && session.getAttribute(ApiConstants.SESSIONKEY) != null) {
                              resp.addHeader("SET-COOKIE", String.format("%s=%s;HttpOnly", ApiConstants.SESSIONKEY, session.getAttribute(ApiConstants.SESSIONKEY)));
                          }
                      } catch (final ServerApiException e) {
                          httpResponseCode = e.getErrorCode().getHttpCode();
                          responseString = e.getMessage();
                          s_logger.debug("Authentication failure: " + e.getMessage());
                      } catch (final UnknownHostException e) {
                          httpResponseCode = 400;
                          responseString = e.getMessage();
                          s_logger.debug("Authentication failure: " + e.getMessage());
                      }
  
                      if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGOUT_API) {
                          if (session != null) {
                              final Long userId = (Long) session.getAttribute("userid");
                              final Account account = (Account) session.getAttribute("accountobj");
                              Long accountId = null;
                              if (account != null) {
                                  accountId = account.getId();
                              }
                              auditTrailSb.insert(0, "(userId=" + userId + " accountId=" + accountId + " sessionId=" + session.getId() + ")");
                              if (userId != null) {
                                  _apiServer.logoutUser(userId);
                              }
                              try {
                                  session.invalidate();
                              } catch (final IllegalStateException e) {
                                  s_logger.warn("Previously ignored exception", e);
                              }
                          }
                          final Cookie sessionKeyCookie = new Cookie(ApiConstants.SESSIONKEY, "");
                          sessionKeyCookie.setMaxAge(0);
                          resp.addCookie(sessionKeyCookie);
                      }
                      HttpUtils.writeHttpResponse(resp, responseString, httpResponseCode, responseType, ApiServer.getJSONContentType());
                      return;
                  }
              }
  
              auditTrailSb.append(cleanQueryString);
              final boolean isNew = ((session == null) ? true : session.isNew());
  
              // Initialize an empty context and we will update it after we have verified the request below,
              // we no longer rely on web-session here, verifyRequest will populate user/account information
              // if a API key exists
              Long userId = null;
  
              if (!isNew) {
                  userId = (Long) session.getAttribute("userid");
                  final String account = (String) session.getAttribute("account");
                  final Object accountObj = session.getAttribute("accountobj");
                  if (!HttpUtils.validateSessionKey(session, params, req.getCookies(), ApiConstants.SESSIONKEY)) {
                      denyAuthenticationRequest(resp, auditTrailSb, responseType, params, session);
                      return;
                  }
  
                  // Do a sanity check here to make sure the user hasn't already been deleted
                  if ((userId != null) && (account != null) && (accountObj != null) && _apiServer.verifyUser(userId)) {
                      final String[] command = (String[]) params.get(ApiConstants.COMMAND);
                      if (command == null) {
                          s_logger.info("missing command, ignoring request...");
                          auditTrailSb.append(" " + HttpServletResponse.SC_BAD_REQUEST + " " + "no command specified");
                          final String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType);
                          HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType, ApiServer.getJSONContentType());
                          return;
                      }
                      final User user = _entityMgr.findById(User.class, userId);
                      CallContext.register(user, (Account) accountObj);
                  } else {
                      // Invalidate the session to ensure we won't allow a request across management server
                      // restarts if the userId was serialized to the stored session
                      denyAuthenticationRequest(resp, auditTrailSb, responseType, params, session);
                  }
              } else {
                  CallContext.register(_accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
              }
  
              if (_apiServer.verifyRequest(params, userId, remoteAddress)) {
                  auditTrailSb.insert(0, "(userId=" + CallContext.current().getCallingUserId() + " accountId=" + CallContext.current().getCallingAccount().getId() +
                          " sessionId=" + (session != null ? session.getId() : null) + ")");
  
                  // Add the HTTP method (GET/POST/PUT/DELETE) as well into the params map.
                  params.put("httpmethod", new String[]{req.getMethod()});
                  final String response = _apiServer.handleRequest(params, responseType, auditTrailSb);
                  HttpUtils.writeHttpResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType, ApiServer.getJSONContentType());
              } else {
                  if (session != null) {
                      try {
                          session.invalidate();
                      } catch (final IllegalStateException e) {
                          s_logger.warn("Previously ignored exception", e);
                      }
                  }
  
                  final String errorMessage = "Permission denied due to: Expired session, unavailable API command or non-authorised from ip-address '" + remoteAddress + "'";
                  auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + errorMessage);
                  final String serializedResponse =
                          _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, errorMessage, params, responseType);
                  HttpUtils.writeHttpResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType, ApiServer.getJSONContentType());
              }
          } catch (final ServerApiException se) {
              final String serializedResponseText = _apiServer.getSerializedApiError(se, params, responseType);
              resp.setHeader("X-Description", se.getDescription());
              HttpUtils.writeHttpResponse(resp, serializedResponseText, se.getErrorCode().getHttpCode(), responseType, ApiServer.getJSONContentType());
              auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription());
          } catch (final CloudRuntimeException e) {
              s_logger.error("Caught runtime exception while writing api response", e);
              auditTrailSb.append("Caught runtime exception while writing api response");
          } finally {
              s_logger.info(auditTrailSb.toString());
              if (s_logger.isDebugEnabled()) {
                  s_logger.debug("===END=== " + reqStr);
              }
              // cleanup user context to prevent from being peeked in other request context
              CallContext.unregister();
          }
      }
focal_method.class_method_signature: ApiServlet.processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp)
focal_method.full_signature:  void processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp)
focal_method.identifier: processRequestInContext
focal_method.invocations: getClientAddress append append append append append getMethod putAll getParameterMap utf8Fixup cleanString getQueryString isDebugEnabled toString debug equalsIgnoreCase setContentType getJSONContentType equalsIgnoreCase setContentType getSession get get getAPIAuthenticator append append getAPIType invalidate warn getSession isSecureSessionCookieEnabled setHeader format getId debug authenticate getByName getAttribute addHeader format getAttribute getHttpCode getErrorCode getMessage debug getMessage getMessage debug getMessage getAPIType getAttribute getAttribute getId insert getId logoutUser invalidate warn setMaxAge addCookie writeHttpResponse getJSONContentType append isNew getAttribute getAttribute getAttribute validateSessionKey getCookies denyAuthenticationRequest verifyUser get info append getSerializedApiError writeHttpResponse getJSONContentType findById register denyAuthenticationRequest register getSystemUser getSystemAccount verifyRequest insert getCallingUserId current getId getCallingAccount current getId put getMethod handleRequest writeHttpResponse getJSONContentType invalidate warn append getSerializedApiError writeHttpResponse getJSONContentType getSerializedApiError setHeader getDescription writeHttpResponse getHttpCode getErrorCode getJSONContentType append getErrorCode getDescription error append info toString isDebugEnabled debug unregister
focal_method.parameters: (final HttpServletRequest req, final HttpServletResponse resp)
focal_method.return: void
focal_method.signature: void processRequestInContext(final HttpServletRequest req, final HttpServletResponse resp)