JsonModelFactory extends AbstractWroModelFactory { @Override public synchronized WroModel create() { final StopWatch stopWatch = new StopWatch("Create Wro Model from Groovy"); try { stopWatch.start("createModel"); final Type type = new TypeToken<WroModel>() {}.getType(); final InputStream is = getModelResourceAsStream(); if (is == null) { throw new WroRuntimeException("Invalid model stream provided!"); } final WroModel model = new Gson().fromJson(new InputStreamReader(new AutoCloseInputStream(is)), type); LOG.debug("json model: {}", model); if (model == null) { throw new WroRuntimeException("Invalid content provided, cannot build model!"); } return model; } catch (final Exception e) { throw new WroRuntimeException("Invalid model found!", e); } finally { stopWatch.stop(); LOG.debug(stopWatch.prettyPrint()); } }  @Override synchronized WroModel create(); static final String ALIAS; }
@Test(expected = WroRuntimeException.class) public void testInvalidContent() { factory = new JsonModelFactory() { @Override protected InputStream getModelResourceAsStream() throws IOException { return new ByteArrayInputStream("".getBytes()); }; }; Assert.assertNull(factory.create()); }
@Test public void createValidModel() { factory = new JsonModelFactory() { @Override protected InputStream getModelResourceAsStream() throws IOException { return TestGroovyModelFactory.class.getResourceAsStream("wro.json"); }; }; final WroModel model = factory.create(); Assert.assertNotNull(model); Assert.assertEquals(Arrays.asList("g1", "g2"), new WroModelInspector(model).getGroupNames()); LOG.debug("model: {}", model); }
@Test public void createIncompleteModel() { factory = new JsonModelFactory() { @Override protected InputStream getModelResourceAsStream() throws IOException { return getClass().getResourceAsStream("incomplete-wro.json"); }; }; final WroModel model = factory.create(); Assert.assertNotNull(model); Assert.assertEquals(1, model.getGroups().size()); final Group group = new ArrayList<Group>(model.getGroups()).get(0); Assert.assertNull(group.getResources().get(0).getType()); LOG.debug("model: {}", model); }
@Test public void shouldBeThreadSafe() throws Exception { factory = new JsonModelFactory() { @Override protected InputStream getModelResourceAsStream() throws IOException { return TestGroovyModelFactory.class.getResourceAsStream("wro.json"); }; }; WroTestUtils.init(factory); final WroModel expected = factory.create(); WroTestUtils.runConcurrently(new Callable<Void>() { @Override public Void call() throws Exception { Assert.assertEquals(expected, factory.create()); return null; } }, 10); }
@Test(expected = WroRuntimeException.class) public void testInvalidStream() throws Exception { factory = new JsonModelFactory() { @Override protected InputStream getModelResourceAsStream() throws IOException { throw new IOException(); }; }; factory.create(); }