ApiListenerServlet extends HttpServletBase { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uri = request.getPathInfo(); String method = request.getMethod().toUpperCase(); log.trace("ApiListenerServlet dispatching uri ["+uri+"] and method ["+method+"]"); if (uri==null) { response.setStatus(400); log.warn("Aborting request with status [400], empty uri"); return; } if(uri.startsWith("/")) uri = uri.substring(1); if(uri.endsWith("/")) uri = uri.substring(0, uri.length()-1); if(uri.equalsIgnoreCase("openapi.json")) { JsonObject jsonSchema = dispatcher.generateOpenApiJsonSchema(); returnJson(response, 200, jsonSchema); return; } if(uri.endsWith("/openapi.json")) { uri = uri.substring(0, uri.length()-"/openapi.json".length()); List<ApiDispatchConfig> apiConfigs = dispatcher.findMatchingConfigsForUri(uri); JsonObject jsonSchema = dispatcher.generateOpenApiJsonSchema(apiConfigs); returnJson(response, 200, jsonSchema); return; } PipeLineSessionBase messageContext = new PipeLineSessionBase(); messageContext.put(IPipeLineSession.HTTP_REQUEST_KEY, request); messageContext.put(IPipeLineSession.HTTP_RESPONSE_KEY, response); messageContext.put(IPipeLineSession.SERVLET_CONTEXT_KEY, getServletContext()); messageContext.setSecurityHandler(new HttpSecurityHandler(request)); try { ApiDispatchConfig config = dispatcher.findConfigForUri(uri); if(config == null) { response.setStatus(404); if(log.isTraceEnabled()) log.trace("Aborting request with status [404], no ApiListener configured for ["+uri+"]"); return; } String origin = request.getHeader("Origin"); if(method.equals("OPTIONS") || origin != null) { response.setHeader("Access-Control-Allow-Origin", CorsAllowOrigin); String headers = request.getHeader("Access-Control-Request-Headers"); if (headers != null) response.setHeader("Access-Control-Allow-Headers", headers); response.setHeader("Access-Control-Expose-Headers", CorsExposeHeaders); StringBuilder methods = new StringBuilder(); for (String mtd : config.getMethods()) { methods.append(", ").append(mtd); } response.setHeader("Access-Control-Allow-Methods", methods.toString()); if(method.equals("OPTIONS")) { response.setStatus(200); if(log.isTraceEnabled()) log.trace("Aborting preflight request with status [200], method ["+method+"]"); return; } } ApiListener listener = config.getApiListener(method); if(listener == null) { response.setStatus(405); if(log.isTraceEnabled()) log.trace("Aborting request with status [405], method ["+method+"] not allowed"); return; } if(log.isTraceEnabled()) log.trace("ApiListenerServlet calling service ["+listener.getName()+"]"); ApiPrincipal userPrincipal = null; if(!AuthenticationMethods.NONE.equals(listener.getAuthenticationMethod())) { String authorizationToken = null; Cookie authorizationCookie = null; switch (listener.getAuthenticationMethod()) { case COOKIE: Cookie[] cookies = request.getCookies(); if(cookies != null) { for (Cookie cookie : cookies) { if("authenticationToken".equals(cookie.getName())) { authorizationToken = cookie.getValue(); authorizationCookie = cookie; authorizationCookie.setPath("/"); } } } break; case HEADER: authorizationToken = request.getHeader("Authorization"); break; case AUTHROLE: List<String> roles = listener.getAuthenticationRoles(); if(roles != null) { for (String role : roles) { if(request.isUserInRole(role)) { userPrincipal = new ApiPrincipal(); break; } } } break; default: break; } if(authorizationToken != null && cache.containsKey(authorizationToken)) userPrincipal = (ApiPrincipal) cache.get(authorizationToken); if(userPrincipal == null || !userPrincipal.isLoggedIn()) { cache.remove(authorizationToken); if(authorizationCookie != null) { authorizationCookie.setMaxAge(0); response.addCookie(authorizationCookie); } response.setStatus(401); if(log.isTraceEnabled()) log.trace("Aborting request with status [401], no (valid) credentials supplied"); return; } if(authorizationCookie != null) { authorizationCookie.setMaxAge(authTTL); response.addCookie(authorizationCookie); } if(authorizationToken != null) { userPrincipal.updateExpiry(); userPrincipal.setToken(authorizationToken); cache.put(authorizationToken, userPrincipal, authTTL); messageContext.put("authorizationToken", authorizationToken); } } messageContext.put("remoteAddr", request.getRemoteAddr()); if(userPrincipal != null) messageContext.put(IPipeLineSession.API_PRINCIPAL_KEY, userPrincipal); messageContext.put("uri", uri); String acceptHeader = request.getHeader("Accept"); if(StringUtils.isNotEmpty(acceptHeader)) { if(!listener.accepts(acceptHeader)) { response.setStatus(406); response.getWriter().print("It appears you expected the MediaType ["+acceptHeader+"] but I only support the MediaType ["+listener.getContentType()+"] :)"); if(log.isTraceEnabled()) log.trace("Aborting request with status [406], client expects ["+acceptHeader+"] got ["+listener.getContentType()+"] instead"); return; } } if(request.getContentType() != null && !listener.isConsumable(request.getContentType())) { response.setStatus(415); if(log.isTraceEnabled()) log.trace("Aborting request with status [415], did not match consumes ["+listener.getConsumes()+"] got ["+request.getContentType()+"] instead"); return; } String etagCacheKey = ApiCacheManager.buildCacheKey(uri); log.debug("Evaluating preconditions for listener["+listener.getName()+"] etagKey["+etagCacheKey+"]"); if(cache.containsKey(etagCacheKey)) { String cachedEtag = (String) cache.get(etagCacheKey); log.debug("found etag value["+cachedEtag+"] for key["+etagCacheKey+"]"); if(method.equals("GET")) { String ifNoneMatch = request.getHeader("If-None-Match"); if(ifNoneMatch != null && ifNoneMatch.equals(cachedEtag)) { response.setStatus(304); if(log.isTraceEnabled()) log.trace("Aborting request with status [304], matched if-none-match ["+ifNoneMatch+"]"); return; } } else { String ifMatch = request.getHeader("If-Match"); if(ifMatch != null && !ifMatch.equals(cachedEtag)) { response.setStatus(412); if(log.isTraceEnabled()) log.trace("Aborting request with status [412], matched if-match ["+ifMatch+"] method ["+method+"]"); return; } } } messageContext.put("updateEtag", listener.getUpdateEtag()); String patternSegments[] = listener.getUriPattern().split("/"); String uriSegments[] = uri.split("/"); int uriIdentifier = 0; for (int i = 0; i < patternSegments.length; i++) { String segment = patternSegments[i]; String name = null; if("*".equals(segment)) { name = "uriIdentifier_"+uriIdentifier; } else if(segment.startsWith("{") && segment.endsWith("}")) { name = segment.substring(1, segment.length()-1); } if(name != null) { uriIdentifier++; if(log.isTraceEnabled()) log.trace("setting uriSegment ["+name+"] to ["+uriSegments[i]+"]"); messageContext.put(name, uriSegments[i]); } } Enumeration<String> paramnames = request.getParameterNames(); while (paramnames.hasMoreElements()) { String paramname = paramnames.nextElement(); String paramvalue = request.getParameter(paramname); if(log.isTraceEnabled()) log.trace("setting queryParameter ["+paramname+"] to ["+paramvalue+"]"); messageContext.put(paramname, paramvalue); } Enumeration<String> headers = request.getHeaderNames(); XmlBuilder headersXml = new XmlBuilder("headers"); while (headers.hasMoreElements()) { String headerName = headers.nextElement().toLowerCase(); if(IGNORE_HEADERS.contains(headerName)) continue; String headerValue = request.getHeader(headerName); try { XmlBuilder headerXml = new XmlBuilder("header"); headerXml.addAttribute("name", headerName); headerXml.setValue(headerValue); headersXml.addSubElement(headerXml); } catch (Throwable t) { log.info("unable to convert header to xml name["+headerName+"] value["+headerValue+"]"); } } messageContext.put("headers", headersXml.toXML()); String body = ""; if (ServletFileUpload.isMultipartContent(request)) { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> items = servletFileUpload.parseRequest(request); XmlBuilder attachments = new XmlBuilder("parts"); int i = 0; String multipartBodyName = listener.getMultipartBodyName(); for (FileItem item : items) { String fieldName = item.getFieldName(); if((i == 0 && multipartBodyName == null) || fieldName.equalsIgnoreCase(multipartBodyName)) { body = Misc.streamToString(item.getInputStream(),"\n",false); } XmlBuilder attachment = new XmlBuilder("part"); attachment.addAttribute("name", fieldName); if (item.isFormField()) { String fieldValue = item.getString(); if(log.isTraceEnabled()) log.trace("setting multipart formField ["+fieldName+"] to ["+fieldValue+"]"); messageContext.put(fieldName, fieldValue); attachment.addAttribute("type", "text"); attachment.addAttribute("value", fieldValue); } else { String fieldNameName = fieldName + "Name"; String fileName = FilenameUtils.getName(item.getName()); if(log.isTraceEnabled()) log.trace("setting multipart formFile ["+fieldNameName+"] to ["+fileName+"]"); messageContext.put(fieldNameName, fileName); if(log.isTraceEnabled()) log.trace("setting parameter ["+fieldName+"] to input stream of file ["+fileName+"]"); messageContext.put(fieldName, item.getInputStream()); attachment.addAttribute("type", "file"); attachment.addAttribute("filename", fileName); attachment.addAttribute("size", item.getSize()); attachment.addAttribute("sessionKey", fieldName); String contentType = item.getContentType(); if(contentType != null) { String mimeType = contentType; int semicolon = contentType.indexOf(";"); if(semicolon >= 0) { mimeType = contentType.substring(0, semicolon); String mightContainCharSet = contentType.substring(semicolon+1).trim(); if(mightContainCharSet.contains("charset=")) { String charSet = mightContainCharSet.substring(mightContainCharSet.indexOf("charset=")+8); attachment.addAttribute("charSet", charSet); } } else { mimeType = contentType; } attachment.addAttribute("mimeType", mimeType); } } attachments.addSubElement(attachment); i++; } messageContext.put("multipartAttachments", attachments.toXML()); } StringBuilder methods = new StringBuilder(); methods.append("OPTIONS, "); for (String mtd : config.getMethods()) { methods.append(mtd + ", "); } messageContext.put("allowedMethods", methods.substring(0, methods.length()-2)); if (!ServletFileUpload.isMultipartContent(request)) { body = Misc.streamToString(request.getInputStream(),"\n",false); } String messageId = null; if(StringUtils.isNotEmpty(listener.getMessageIdHeader())) { String messageIdHeader = request.getHeader(listener.getMessageIdHeader()); if(StringUtils.isNotEmpty(messageIdHeader)) { messageId = messageIdHeader; } } PipeLineSessionBase.setListenerParameters(messageContext, messageId, null, null, null); String result = listener.processRequest(null, body, messageContext); if(messageContext.get("updateEtag", true)) { log.debug("calculating etags over processed result"); String cleanPattern = listener.getCleanPattern(); if(result != null && method.equals("GET") && cleanPattern != null) { String eTag = ApiCacheManager.buildEtag(cleanPattern, result.hashCode()); log.debug("adding/overwriting etag with key["+etagCacheKey+"] value["+eTag+"]"); cache.put(etagCacheKey, eTag); response.addHeader("etag", eTag); } else { log.debug("removing etag with key["+etagCacheKey+"]"); cache.remove(etagCacheKey); String key = ApiCacheManager.getParentCacheKey(listener, uri); if(key != null) { log.debug("removing parent etag with key["+key+"]"); cache.remove(key); } } } response.addHeader("Allow", (String) messageContext.get("allowedMethods")); String contentType = listener.getContentType(); if(listener.getProduces().equals("ANY")) { contentType = messageContext.get("contentType", contentType); } response.setHeader("Content-Type", contentType); int statusCode = messageContext.get("exitcode", 0); if(statusCode > 0) response.setStatus(statusCode); if(result != null) response.getWriter().print(result); if(log.isTraceEnabled()) log.trace("ApiListenerServlet finished with statusCode ["+statusCode+"] result ["+result+"]"); } catch (Exception e) { log.warn("ApiListenerServlet caught exception, will rethrow as ServletException", e); try { response.reset(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (IllegalStateException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }  @Override void init(); @Override void destroy(); void returnJson(HttpServletResponse response, int status, JsonObject json); @Override String getUrlMapping();  }
@Test public void noUri() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("test", Methods.GET); Response result = service(createRequest(null, Methods.GET, null)); assertEquals(400, result.getStatus()); }
@Test public void uriNotFound() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("test", Methods.GET); Response result = service(createRequest("not-test", Methods.GET, null)); assertEquals(404, result.getStatus()); }
@Test public void methodNotAllowed() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("test", Methods.GET); Response result = service(createRequest("test", Methods.PUT, null)); assertEquals(405, result.getStatus()); assertNull(result.getErrorMessage()); }
@Test public void simpleGet() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("test1", Methods.GET); Response result = service(createRequest("test1", Methods.GET, null)); assertEquals(200, result.getStatus()); assertEquals("OPTIONS, GET", result.getHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void simpleGetWithSlashes() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("/test2/", Methods.GET); Response result = service(createRequest("test2/", Methods.GET, null)); assertEquals(200, result.getStatus()); assertEquals("OPTIONS, GET", result.getHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void preFlightRequest() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("preflight/", Methods.GET); Response result = service(createRequest("preflight/", Methods.OPTIONS, null)); assertEquals(200, result.getStatus()); assertEquals("", result.getContentAsString()); assertNull(result.getErrorMessage()); assertTrue(result.containsHeader("Access-Control-Allow-Origin")); assertFalse(result.containsHeader("Access-Control-Allow-Headers")); assertTrue(result.containsHeader("Access-Control-Expose-Headers")); assertTrue(result.containsHeader("Access-Control-Allow-Methods")); }
@Test public void preFlightRequestWithRequestHeader() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("preflight/", Methods.GET); Map<String, String> headers = new HashMap<String, String>(); headers.put("Access-Control-Request-Headers", "Message-Id,CustomHeader"); Response result = service(createRequest("preflight/", Methods.OPTIONS, null, headers)); assertEquals(200, result.getStatus()); assertEquals("", result.getContentAsString()); assertNull(result.getErrorMessage()); assertTrue(result.containsHeader("Access-Control-Allow-Origin")); assertTrue(result.containsHeader("Access-Control-Allow-Headers")); assertEquals(result.getHeader("Access-Control-Allow-Headers"), "Message-Id,CustomHeader"); assertTrue(result.containsHeader("Access-Control-Expose-Headers")); assertTrue(result.containsHeader("Access-Control-Allow-Methods")); }
@Test public void corsGetRequest() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("not-preflight/", Methods.POST); Map<String, String> headers = new HashMap<String, String>(); headers.put("origin", "https: headers.put("Access-Control-Request-Headers", "Message-Id,CustomHeader"); Response result = service(createRequest("not-preflight/", Methods.POST, "data", headers)); assertEquals(200, result.getStatus()); assertEquals("data", result.getContentAsString()); assertNull(result.getErrorMessage()); assertTrue(result.containsHeader("Access-Control-Allow-Origin")); assertTrue(result.containsHeader("Access-Control-Allow-Headers")); assertEquals(result.getHeader("Access-Control-Allow-Headers"), "Message-Id,CustomHeader"); assertTrue(result.containsHeader("Access-Control-Expose-Headers")); assertTrue(result.containsHeader("Access-Control-Allow-Methods")); assertEquals("OPTIONS, POST", result.getHeader("Allow")); }
@Test public void apiListenerThatProducesXML() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("/ApiListenerThatProducesXML/", Methods.PUT, null, MediaTypes.XML); Response result = service(createRequest("ApiListenerThatProducesXML", Methods.PUT, "<xml>data</xml>")); assertEquals(200, result.getStatus()); assertEquals("<xml>data</xml>", result.getContentAsString()); assertEquals("OPTIONS, PUT", result.getHeader("Allow")); assertTrue("Content-Type header does not contain [application/xml]", result.getContentType().contains("application/xml")); assertNull(result.getErrorMessage()); }
@Test public void apiListenerThatProducesJSON() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("/ApiListenerThatProducesJSON/", Methods.POST, null, MediaTypes.JSON); Response result = service(createRequest("ApiListenerThatProducesJSON", Methods.POST, "{}")); assertEquals(200, result.getStatus()); assertEquals("{}", result.getContentAsString()); assertEquals("OPTIONS, POST", result.getHeader("Allow")); assertTrue("Content-Type header does not contain [application/json]", result.getContentType().contains("application/json")); assertNull(result.getErrorMessage()); }
@Test public void clientAcceptHeaderDoesNotLikeJSON() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("/ApiListenerAllow/", Methods.POST, null, MediaTypes.JSON); Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/xml"); Response result = service(createRequest("ApiListenerAllow", Methods.POST, "{}", headers)); assertEquals(406, result.getStatus()); }
@Test public void clientAcceptHeaderLovesJSON() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("/ApiListenerAllow/", Methods.POST, null, MediaTypes.JSON); Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); Response result = service(createRequest("ApiListenerAllow", Methods.POST, "{}", headers)); assertEquals(200, result.getStatus()); assertEquals("{}", result.getContentAsString()); assertEquals("OPTIONS, POST", result.getHeader("Allow")); assertTrue("Content-Type header does not contain [application/json]", result.getContentType().contains("application/json")); assertNull(result.getErrorMessage()); }
@Test public void listenerDoesNotLikeContentTypeJSON() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("listenerDoesNotAcceptContentType", Methods.POST, MediaTypes.XML, null); Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); headers.put("content-type", "application/json"); Response result = service(createRequest("listenerDoesNotAcceptContentType", Methods.POST, "{}", headers)); assertEquals(415, result.getStatus()); System.out.println(result); }
@Test public void listenerLovesContentTypeJSON() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("listenerLovesContentTypeJSON", Methods.POST, MediaTypes.JSON, MediaTypes.JSON); Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); headers.put("content-type", "application/json"); Response result = service(createRequest("listenerLovesContentTypeJSON", Methods.POST, "{}", headers)); assertEquals(200, result.getStatus()); assertEquals("{}", result.getContentAsString()); assertEquals("OPTIONS, POST", result.getHeader("Allow")); assertTrue("Content-Type header does not contain [application/json]", result.getContentType().contains("application/json")); assertNull(result.getErrorMessage()); }
@Test public void getRequestWithQueryParameters() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("queryParamTest", Methods.GET); Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); headers.put("content-type", "application/json"); Response result = service(createRequest("queryParamTest?name=JOHN-DOE&GENDER=MALE", Methods.GET, null, headers)); assertEquals(200, result.getStatus()); assertEquals("JOHN-DOE", session.get("name")); assertEquals("MALE", session.get("GENDER")); assertEquals("OPTIONS, GET", result.getHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void getRequestWithDynamicPath() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("dynamic/{poef}", Methods.GET); Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); headers.put("content-type", "application/json"); Response result = service(createRequest("dynamic/tralala", Methods.GET, null, headers)); assertEquals(200, result.getStatus()); assertEquals("tralala", session.get("poef")); assertEquals("OPTIONS, GET", result.getHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void getRequestWithAsteriskPath() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("dynamic/*", Methods.GET); Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); headers.put("content-type", "application/json"); Response result = service(createRequest("dynamic/tralala", Methods.GET, null, headers)); System.out.println(session); assertEquals(200, result.getStatus()); assertEquals("tralala", session.get("uriIdentifier_0")); assertEquals("OPTIONS, GET", result.getHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void customExitCode() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("exitcode", Methods.GET); Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); headers.put("content-type", "application/json"); session = new HashMap<String, Object>(); session.put("exitcode", "234"); Response result = service(createRequest("exitcode", Methods.GET, null, headers)); assertEquals(234, result.getStatus()); assertEquals("OPTIONS, GET", result.getHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void apiListenerShouldReturnEtag() throws ServletException, IOException, ListenerException, ConfigurationException { addListener("etag1", Methods.GET); Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); headers.put("content-type", "application/json"); session = new HashMap<String, Object>(); session.put("response-content", "{\"tralalalallala\":true}"); Response result = service(createRequest("etag1", Methods.GET, null, headers)); assertEquals(200, result.getStatus()); assertEquals("OPTIONS, GET", result.getHeader("Allow")); assertNull(result.getErrorMessage()); assertTrue(result.containsHeader("etag")); }
@Test public void eTagGetEtagMatches() throws ServletException, IOException, ListenerException, ConfigurationException { String uri = "etag32"; addListener(uri, Methods.GET); String etagCacheKey = ApiCacheManager.buildCacheKey(uri); ApiCacheManager.getInstance().put(etagCacheKey, "my-etag-value"); Map<String, String> headers = new HashMap<String, String>(); headers.put("if-none-match", "my-etag-value"); session = new HashMap<String, Object>(); session.put("response-content", "{\"tralalalallala\":true}"); Response result = service(createRequest(uri, Methods.GET, null, headers)); assertEquals(304, result.getStatus()); assertFalse(result.containsHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void eTagGetEtagDoesNotMatch() throws ServletException, IOException, ListenerException, ConfigurationException { String uri = "etag32"; addListener(uri, Methods.GET); String etagCacheKey = ApiCacheManager.buildCacheKey(uri); ApiCacheManager.getInstance().put(etagCacheKey, "my-etag-value"); Map<String, String> headers = new HashMap<String, String>(); headers.put("if-none-match", "my-etag-value7"); session = new HashMap<String, Object>(); session.put("response-content", "{\"tralalalallala\":true}"); Response result = service(createRequest(uri, Methods.GET, null, headers)); assertEquals(200, result.getStatus()); assertTrue(result.containsHeader("Allow")); assertEquals("{\"tralalalallala\":true}", result.getContentAsString()); assertNull(result.getErrorMessage()); }
@Test public void eTagPostEtagIfMatches() throws ServletException, IOException, ListenerException, ConfigurationException { String uri = "etag45"; addListener(uri, Methods.POST); String etagCacheKey = ApiCacheManager.buildCacheKey(uri); ApiCacheManager.getInstance().put(etagCacheKey, "my-etag-value"); Map<String, String> headers = new HashMap<String, String>(); headers.put("if-match", "my-etag-value"); Response result = service(createRequest(uri, Methods.POST, "{\"tralalalallala\":true}", headers)); System.out.println(result); assertEquals(200, result.getStatus()); assertEquals("{\"tralalalallala\":true}", result.getContentAsString()); assertTrue(result.containsHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void eTagPostEtagDoesNotMatch() throws ServletException, IOException, ListenerException, ConfigurationException { String uri = "etag46"; addListener(uri, Methods.POST); String etagCacheKey = ApiCacheManager.buildCacheKey(uri); ApiCacheManager.getInstance().put(etagCacheKey, "my-etag-value"); Map<String, String> headers = new HashMap<String, String>(); headers.put("if-match", "my-etag-value2"); Response result = service(createRequest(uri, Methods.POST, "{\"tralalalallala\":true}", headers)); assertEquals(412, result.getStatus()); assertFalse(result.containsHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void cookieAuthentication401() throws ServletException, IOException, ListenerException, ConfigurationException { String uri = "cookie"; addListener(uri, Methods.POST, AuthMethods.COOKIE); Map<String, String> headers = new HashMap<String, String>(); Response result = service(createRequest(uri, Methods.POST, "{\"tralalalallala\":true}", headers)); assertEquals(401, result.getStatus()); assertFalse(result.containsHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void cookieNotFoundInCache401() throws ServletException, IOException, ListenerException, ConfigurationException { String uri = "cookie"; addListener(uri, Methods.POST, AuthMethods.COOKIE); Map<String, String> headers = new HashMap<String, String>(); MockHttpServletRequest request = createRequest(uri, Methods.POST, "{\"tralalalallala\":true}", headers); Cookie cookies = new Cookie("authenticationToken", "myToken"); request.setCookies(cookies); Response result = service(request); assertEquals(401, result.getStatus()); assertFalse(result.containsHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void cookieAuthentication200() throws ServletException, IOException, ListenerException, ConfigurationException { String uri = "cookie"; addListener(uri, Methods.POST, AuthMethods.COOKIE); String authToken = "random-token_thing"; ApiPrincipal principal = new ApiPrincipal(); assertTrue("principal is not logged in? ttl expired?", principal.isLoggedIn()); ApiCacheManager.getInstance().put(authToken, principal); Map<String, String> headers = new HashMap<String, String>(); MockHttpServletRequest request = createRequest(uri, Methods.POST, "{\"tralalalallala\":true}", headers); Cookie cookies = new Cookie("authenticationToken", authToken); request.setCookies(cookies); Response result = service(request); String sessionAuthToken = (String) session.get("authorizationToken"); assertNotNull("session should contain auth token", sessionAuthToken); assertEquals("auth tokens should match", authToken, sessionAuthToken); assertEquals(200, result.getStatus()); assertTrue(result.containsHeader("Allow")); assertNull(result.getErrorMessage()); assertTrue("response contains auth cookie", result.containsCookie("authenticationToken")); }
@Test public void headerAuthentication401() throws ServletException, IOException, ListenerException, ConfigurationException { String uri = "cookie"; addListener(uri, Methods.POST, AuthMethods.HEADER); Map<String, String> headers = new HashMap<String, String>(); headers.put("Authorization", "blalablaaaa"); Response result = service(createRequest(uri, Methods.POST, "{\"tralalalallala\":true}", headers)); assertEquals(401, result.getStatus()); assertFalse(result.containsHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void headerAuthentication200() throws ServletException, IOException, ListenerException, ConfigurationException { String uri = "header"; addListener(uri, Methods.POST, AuthMethods.HEADER); String authToken = "random-token_thing"; ApiPrincipal principal = new ApiPrincipal(); assertTrue("principal is not logged in? ttl expired?", principal.isLoggedIn()); ApiCacheManager.getInstance().put(authToken, principal); Map<String, String> headers = new HashMap<String, String>(); headers.put("Authorization", authToken); Response result = service(createRequest(uri, Methods.POST, "{\"tralalalallala\":true}", headers)); String sessionAuthToken = (String) session.get("authorizationToken"); assertNotNull("session should contain auth token", sessionAuthToken); assertEquals("auth tokens should match", authToken, sessionAuthToken); assertEquals(200, result.getStatus()); assertTrue(result.containsHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void authRoleAuthentication401() throws ServletException, IOException, ListenerException, ConfigurationException { String uri = "authRole2"; addListener(uri, Methods.POST, AuthMethods.AUTHROLE); Map<String, String> headers = new HashMap<String, String>(); headers.put("Authorization", "am9objpkb2U="); MockHttpServletRequest request = createRequest(uri, Methods.POST, "{\"tralalalallala\":true}", headers); request.setAuthType("BASIC_AUTH"); request.addUserRole("non-existing-role"); Response result = service(request); assertEquals(401, result.getStatus()); assertFalse(result.containsHeader("Allow")); assertNull(result.getErrorMessage()); }
@Test public void authRoleAuthentication200() throws ServletException, IOException, ListenerException, ConfigurationException { String uri = "authRole2"; addListener(uri, Methods.POST, AuthMethods.AUTHROLE); Map<String, String> headers = new HashMap<String, String>(); headers.put("Authorization", "am9objpkb2U="); MockHttpServletRequest request = createRequest(uri, Methods.POST, "{\"tralalalallala\":true}", headers); request.setAuthType("BASIC_AUTH"); request.addUserRole("IbisObserver"); Response result = service(request); assertEquals(200, result.getStatus()); assertTrue(result.containsHeader("Allow")); assertNull(result.getErrorMessage()); }