TemplateEngineJsonP implements TemplateEngine { @Override public void invoke(Context context, Result result) { ResponseStreams responseStreams = context.finalizeHeaders(result); String callback = getCallbackName(context); try (OutputStream outputStream = responseStreams.getOutputStream()) { objectMapper.writeValue(outputStream, new JSONPObject(callback, result.getRenderable())); } catch (IOException e) { logger.error("Error while rendering jsonp.", e); } } @Inject  TemplateEngineJsonP(ObjectMapper objectMapper, NinjaProperties properties); @Override void invoke(Context context, Result result); @Override String getContentType(); @Override String getSuffixOfTemplatingEngine(); static boolean isThisASecureCallbackName(String callback);  }
@Test public void testCorrectFlow() throws IOException { when(context.getParameter("callback", TemplateEngineJsonP.DEFAULT_CALLBACK_PARAMETER_VALUE)).thenReturn("App.callback"); TemplateEngineJsonP jsonpEngine = new TemplateEngineJsonP(objectMapper, properties); jsonpEngine.invoke(context, result); String jsonp = new String(outputStream.toByteArray(), "UTF-8"); assertEquals("App.callback([123])", jsonp); verify(context).finalizeHeaders(result); }
@Test public void testMissingCallbackVariableFlow() throws IOException { TemplateEngineJsonP jsonpEngine = new TemplateEngineJsonP(objectMapper, properties); jsonpEngine.invoke(context, result); String jsonp = new String(outputStream.toByteArray(), "UTF-8"); assertEquals(TemplateEngineJsonP.DEFAULT_CALLBACK_PARAMETER_VALUE + "([123])", jsonp); verify(context).finalizeHeaders(result); }
@Test public void testBadCallbackNameFlow() throws IOException { when(context.getParameter("callback", TemplateEngineJsonP.DEFAULT_CALLBACK_PARAMETER_VALUE)).thenReturn(".callback"); TemplateEngineJsonP jsonpEngine = new TemplateEngineJsonP(objectMapper, properties); jsonpEngine.invoke(context, result); String jsonp = new String(outputStream.toByteArray(), "UTF-8"); assertEquals(TemplateEngineJsonP.DEFAULT_CALLBACK_PARAMETER_VALUE + "([123])", jsonp); verify(context).finalizeHeaders(result); }