method2testcases
stringlengths
118
3.08k
### Question: TexHexTriplet { public static TexHexTriplet parse(String s) throws NumberFormatException { String hex = s.startsWith("#") ? s.substring(1) : s; if(hex.length() == 6) { return parse(Integer.parseInt(hex, 16)); } else { throw new NumberFormatException(hex + " is not a valid hex triplet"); } } TexHexTriplet(int roughgrass, int mud, int dirt); int getRoughgrass(); int getMud(); int getDirt(); String getHexString(); int getTexture(); ColorDef getColorDef(); static TexHexTriplet of(double roughgrass, double mud, double dirt); static TexHexTriplet of(int roughgrass, int mud, int dirt); static TexHexTriplet of(ColorDef c); static TexHexTriplet parse(String s); static TexHexTriplet parse(int hex); static String convertToHexString(int roughgrass, int mud, int dirt); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); final int roughgrass; final int mud; final int dirt; }### Answer: @Test public void testParseInt() { TexHexTriplet actual = TexHexTriplet.parse(0x42ff11); assertEquals(texExpected, actual); } @Test public void testParseString() { TexHexTriplet actual = TexHexTriplet.parse(strExpected); assertEquals(texExpected, actual); } @Test public void testParseString2() { TexHexTriplet actual = TexHexTriplet.parse("#" + strExpected); assertEquals(texExpected, actual); } @Test public void testParseString3() { try { TexHexTriplet.parse("2f11"); fail("Should have thrown exception"); } catch(NumberFormatException e) { } }
### Question: OsmHash { public OsmHash(Area bounds, List<EntityDef> entities, boolean fullDataSet) throws TextureProcessingException { this.fullDataSet = fullDataSet; this.entityHash = fullDataSet ? "all" : getQueryHashEntities(entities); try { this.locationHash = getQueryHashLocation(bounds); this.queryHash = locationHash + "-" + entityHash; } catch(IOException e) { throw new TextureProcessingException("Unexpected Exception: Could not generate hash for this location", e); } } OsmHash(Area bounds, List<EntityDef> entities, boolean fullDataSet); OsmHash(Area bounds, List<EntityDef> entities); OsmHash(Area bounds); String getQueryHash(); boolean hasFullDataSet(); Area getHashedLocation(); boolean isCached(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testOsmHash() throws Exception { Area ar = new Area(48, 11, 49, 12); OsmHash h = new OsmHash(ar); String expected = "IcAInQB7wCHA-all"; String actual = h.getQueryHash(); assertEquals(expected, actual); }
### Question: OverpassBridge { public String buildOverpassQuery() { if(exceedsQueryLimit()) { return buildQueryFullyRecursive(); } else { return buildQueryEntityConcat(); } } OverpassBridge(Config conf); OverpassBridge(Area bounds, OsmDef osm); File getResult(); String buildOverpassQuery(); }### Answer: @Test public void testBuildOverpassQuery() { OverpassBridge ob = new OverpassBridge(c); String expected = "(way[\"landuse\"~\"forest|wood\"](48.39650842,11.73723469,48.40549158,11.75076531);way[\"waterway\"=\"riverbank\"](48.39650842,11.73723469,48.40549158,11.75076531);way[\"bridge\"](48.39650842,11.73723469,48.40549158,11.75076531);way[\"highway\"~\"_link\"](48.39650842,11.73723469,48.40549158,11.75076531););(._;>;);out meta;"; String actual = ob.buildOverpassQuery(); assertEquals(expected, actual); }
### Question: OverpassBridge { protected StringBuilder buildSingleEntityQueryPart(EntityDef entity, StringBuilder sb) { sb.append(entity.getType()); sb.append("[\""); sb.append(escapeOverpassQuery(entity.key)); sb.append('"'); if(!entity.allowsAnyValue()) { if(entity.hasRegexValue()) { sb.append('~'); } else { sb.append('='); } sb.append('"'); sb.append(escapeOverpassQuery(entity.getValue())); sb.append('"'); } sb.append(']'); sb.append(bounds.getStringOverpassBounds()); sb.append(';'); return sb; } OverpassBridge(Config conf); OverpassBridge(Area bounds, OsmDef osm); File getResult(); String buildOverpassQuery(); }### Answer: @Test public void testBuildSingleEntityQueryPart() { OverpassBridge ob = new OverpassBridge(c); EntityDef entity = ((OsmDef) c.getTextureTrans()).entities.get(0); StringBuilder sb = new StringBuilder(); ob.buildSingleEntityQueryPart(entity, sb); String expected = "way[\"landuse\"~\"forest|wood\"](48.39650842,11.73723469,48.40549158,11.75076531);"; String actual = sb.toString(); assertEquals(expected, actual); }
### Question: OverpassBridge { protected URL buildQueryURL(String server) { try { return new URL(server + URLEncoder.encode(buildOverpassQuery(), "UTF-8")); } catch (Exception e) { String error = "Creating of Overpass-Query URL failed"; log.error(error, e); throw new RuntimeException(error, e); } } OverpassBridge(Config conf); OverpassBridge(Area bounds, OsmDef osm); File getResult(); String buildOverpassQuery(); }### Answer: @Test public void testBuildOverpassQueryURL() { OverpassBridge ob = new OverpassBridge(c); try { String server = OverpassBridge.servers[0]; String expected = server + URLEncoder.encode("(way[\"landuse\"~\"forest|wood\"](48.39650842,11.73723469,48.40549158,11.75076531);way[\"waterway\"=\"riverbank\"](48.39650842,11.73723469,48.40549158,11.75076531);way[\"bridge\"](48.39650842,11.73723469,48.40549158,11.75076531);way[\"highway\"~\"_link\"](48.39650842,11.73723469,48.40549158,11.75076531););(._;>;);out meta;", "UTF-8"); String actual = ob.buildQueryURL(server).toString(); assertEquals(expected, actual); } catch (UnsupportedEncodingException e) { fail("URL encoding failure!"); } }
### Question: OverpassBridge { protected static String escapeOverpassQuery(String query) { StringBuilder sb = new StringBuilder((int) (query.length() * 1.3)); for (int i = 0; i < query.length(); i++) { char c = query.charAt(i); if(escapeChars.containsKey(c)) { sb.append(escapeChars.get(c)); } else { sb.append(c); } } return sb.toString(); } OverpassBridge(Config conf); OverpassBridge(Area bounds, OsmDef osm); File getResult(); String buildOverpassQuery(); }### Answer: @Test public void testEscapeOverpassQuery() throws Exception { String input = "test\tquery\\and\nescape'chars'"; String expected = "test\\tquery\\\\and\\nescape\\'chars\\'"; String actual = OverpassBridge.escapeOverpassQuery(input); assertEquals(expected, actual); }
### Question: TileDownload { protected static int getNumAfterIndex(String s, int start) throws ParseException { if (!Character.isDigit(s.charAt(start))) { throw new ParseException(String.format("No digit recognized at " + "index %s in %s, just '%s'", start, s, s.charAt(start)), start); } int last = start + 1; search: while (last < s.length()) { if (Character.isDigit(s.charAt(last))) { last++; } else { break search; } } return Integer.parseInt(s.substring(start, last)); } boolean exists(double lat, double lon); abstract boolean exists(int lat, int lon); File[][] getTiles(Area ar); File getTile(CoordinateInt c); File getTile(double lat, double lon); abstract File getTile(int lat, int lon); static String getNonationNSEW(int lat, int lon); }### Answer: @Test public void testGetNumAfterIndex() throws Exception { String input = "N47E011.hgt.zip"; try { int n = TileDownload.getNumAfterIndex(input, 1); int e = TileDownload.getNumAfterIndex(input, 4); assertEquals(47, n); assertEquals(11, e); } catch(NumberFormatException ex) { fail(ex.getMessage()); } catch(ParseException ex) { fail(ex.getMessage()); } }
### Question: TileDownload { protected static CoordinateInt parseCoordinate(String hgtFileName) throws ParseException { String parse = hgtFileName.trim(); int lat = Integer.MIN_VALUE; int lon = Integer.MIN_VALUE; for (int i = 0; i < parse.length(); i++) { char c = parse.charAt(i); if (c == 'N') { lat = getNumAfterIndex(parse, ++i); } else if (c == 'S') { lat = -(getNumAfterIndex(parse, ++i)); } else if (c == 'E') { lon = getNumAfterIndex(parse, ++i); } else if (c == 'W') { lon = -(getNumAfterIndex(parse, ++i)); } } if (lat < -90 || lat > 90) { throw new ParseException(String.format("Latitude must be between " + "[-90;+90], but is %s", lat), -1); } else if (lon < -180 || lon > 180) { throw new ParseException(String.format("Longitude must be between " + "[-180;+180], but is %s", lon), -1); } return new CoordinateInt(lat, lon); } boolean exists(double lat, double lon); abstract boolean exists(int lat, int lon); File[][] getTiles(Area ar); File getTile(CoordinateInt c); File getTile(double lat, double lon); abstract File getTile(int lat, int lon); static String getNonationNSEW(int lat, int lon); }### Answer: @Test public void testParseCoordinate() throws Exception { helpTestParseCoordinate("N47E011.hgt.zip", 47, 11); }
### Question: UpdateChecker { protected static Update getUpdateXml() { Exception lastException = null; for (String s : updateURLs) { try { URL url = new URL(s); File xml = Cache.temporaray(xmlFileName); Network.downloadToFile(url, xml); try { return Serializer.deserialize(Update.class, xml); } catch (Exception e) { lastException = e; log.warn("Error while parsing update.xml", e); } } catch (IOException e) { lastException = e; log.warn(String.format("Could not retrieve file %s from update server.", s), e); } } throw new RuntimeException("Update check failed", lastException); } UpdateChecker(); UpdateChecker(ProgramVersion version, Branch branch); boolean isUpdateAvailable(); boolean isUpdateAvailable(String currentVersion, String branch); boolean isUpdateAvailable(ProgramVersion currentVersion, Branch branch); Update getUpdate(); }### Answer: @Test public void testGetUpdateXml() throws Exception { }
### Question: Update { public Release getStable() { return getBranch(Branch.stable); } Release getStable(); Release getTesting(); Release getBranch(Branch branch); Release getBranch(String branch); @Override String toString(); @XmlElementWrapper(name = "releases") @XmlElement(name = "release") public List<Release> releases; @XmlElementWrapper(name = "notifications") @XmlElement(name = "notification") public List<Notification> notifications; @XmlElement(name = "lastUpdate") public Date lastUpdate; }### Answer: @Test public void deserializeTest() { try { Update u = Serializer.deserialize(Update.class, serialize, schema); assertNotNull(u.getStable().version); } catch (Exception e) { fail("deserialization failed: " + e); } } @Test public void deserializeTest2() { try { Update u = Serializer.deserialize(Update.class, serialize, true); assertNotNull(u.getStable().version); } catch (Exception e) { fail("deserialization failed: " + e); } }
### Question: TextureChooser extends JDialog { protected static int[] getPixelsForImageResource(String resource) { ImagePlus img = ImageJUtils.openFromResource(resource); return (int[]) img.getProcessor().getPixels(); } TextureChooser(); int showDialog(); int showDialog(String texture); TexHexTriplet getTexture(); static final int CANCEL_OPTION; static final int APPROVE_OPTION; static final int ERROR_OPTION; }### Answer: @Test public void testGetPixelsForImageResource() throws Exception { int[] test = TextureChooser.getPixelsForImageResource(TextureChooser.resTextureGrass); assertEquals(5476, test.length); }
### Question: TextureChooser extends JDialog { protected static int pixelBlend(int rgb1, double a1, int rgb2, double a2, int rgb3, double a3, int rgb4, double a4) { return 0xFF000000 | (int) (((rgb1 >>> 16) & 0xFF) * a1 + ((rgb2 >>> 16) & 0xFF) * a2 + ((rgb3 >>> 16) & 0xFF) * a3 + ((rgb4 >>> 16) & 0xFF) * a4 + 0.5) << 16 | (int) (((rgb1 >>> 8) & 0xFF) * a1 + ((rgb2 >>> 8) & 0xFF) * a2 + ((rgb3 >>> 8) & 0xFF) * a3 + ((rgb4 >>> 8) & 0xFF) * a4 + 0.5) << 8 | (int) (( rgb1 & 0xFF) * a1 + ( rgb2 & 0xFF) * a2 + ( rgb3 & 0xFF) * a3 + ( rgb4 & 0xFF) * a4 + 0.5); } TextureChooser(); int showDialog(); int showDialog(String texture); TexHexTriplet getTexture(); static final int CANCEL_OPTION; static final int APPROVE_OPTION; static final int ERROR_OPTION; }### Answer: @Test public void testPixelBlend() throws Exception { int red = 0xffff0000; int green = 0xff00ff00; int expected = 0xff808000; int actual = TextureChooser.pixelBlend(red, 0.5, green, 0.5, 0, 0, 0, 0); assertEquals(expected, actual); }
### Question: DefaultPluginPersistentState implements Serializable, PluginPersistentState { public PluginRestartState getPluginRestartState(final String pluginKey) { for (final PluginRestartState state : PluginRestartState.values()) { if (map.containsKey(buildStateKey(pluginKey, state))) { return state; } } return PluginRestartState.NONE; } @Deprecated DefaultPluginPersistentState(); @Deprecated DefaultPluginPersistentState(final Map<String, Boolean> map); DefaultPluginPersistentState(final Map<String, Boolean> map, final boolean ignore); @Deprecated DefaultPluginPersistentState(final PluginPersistentState state); Map<String, Boolean> getMap(); boolean isEnabled(final Plugin plugin); boolean isEnabled(final ModuleDescriptor<?> pluginModule); Map<String, Boolean> getPluginStateMap(final Plugin plugin); PluginRestartState getPluginRestartState(final String pluginKey); }### Answer: @Test public void testPluginRestartStateRemoveExisting() { final PluginPersistentState.Builder builder = PluginPersistentState.Builder.create(); builder.setPluginRestartState("foo", PluginRestartState.UPGRADE); assertEquals(PluginRestartState.UPGRADE, builder.toState().getPluginRestartState("foo")); builder.setPluginRestartState("foo", PluginRestartState.REMOVE); assertEquals(PluginRestartState.REMOVE, builder.toState().getPluginRestartState("foo")); }
### Question: DefaultPluginPersistentState implements Serializable, PluginPersistentState { public boolean isEnabled(final Plugin plugin) { final Boolean bool = map.get(plugin.getKey()); return (bool == null) ? plugin.isEnabledByDefault() : bool.booleanValue(); } @Deprecated DefaultPluginPersistentState(); @Deprecated DefaultPluginPersistentState(final Map<String, Boolean> map); DefaultPluginPersistentState(final Map<String, Boolean> map, final boolean ignore); @Deprecated DefaultPluginPersistentState(final PluginPersistentState state); Map<String, Boolean> getMap(); boolean isEnabled(final Plugin plugin); boolean isEnabled(final ModuleDescriptor<?> pluginModule); Map<String, Boolean> getPluginStateMap(final Plugin plugin); PluginRestartState getPluginRestartState(final String pluginKey); }### Answer: @Test public void testSetEnabledModuleDescriptor() { PluginPersistentState state = new DefaultPluginPersistentState(); final ModuleDescriptor<?> module = createModule("mock.plugin.key", "module.key"); state = PluginPersistentState.Builder.create(state).setEnabled(module, true).toState(); assertTrue(state.isEnabled(module)); state = PluginPersistentState.Builder.create(state).setEnabled(module, false).toState(); assertFalse(state.isEnabled(module)); } @Test public void testSetEnabledPlugin() { PluginPersistentState state = new DefaultPluginPersistentState(); final StaticPlugin plugin = createMockPlugin("mock.plugin.key", true); state = PluginPersistentState.Builder.create(state).setEnabled(plugin, true).toState(); assertTrue(state.isEnabled(plugin)); state = PluginPersistentState.Builder.create(state).setEnabled(plugin, false).toState(); assertFalse(state.isEnabled(plugin)); }
### Question: ContextClassLoaderSwitchingUtil { public static void runInContext(ClassLoader newClassLoader, Runnable runnable) { ClassLoaderStack.push(newClassLoader); try { runnable.run(); } finally { ClassLoaderStack.pop(); } } static void runInContext(ClassLoader newClassLoader, Runnable runnable); }### Answer: @Test public void testSwitchClassLoader() { ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); ContextClassLoaderSwitchingUtil.runInContext(newLoader, new Runnable() { public void run() { assertEquals(newLoader, Thread.currentThread().getContextClassLoader()); newLoader.getResource("test"); } }); assertEquals(currentLoader, Thread.currentThread().getContextClassLoader()); verify(newLoader).getResource("test"); } @Test public void testSwitchClassLoaderMultiple() { ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); ContextClassLoaderSwitchingUtil.runInContext(newLoader, new Runnable() { public void run() { assertEquals(newLoader, Thread.currentThread().getContextClassLoader()); newLoader.getResource("test"); final ClassLoader innerLoader = mock(ClassLoader.class); ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); ContextClassLoaderSwitchingUtil.runInContext(innerLoader, new Runnable() { public void run() { assertEquals(innerLoader, Thread.currentThread().getContextClassLoader()); innerLoader.getResource("test"); } }); assertEquals(currentLoader, Thread.currentThread().getContextClassLoader()); verify(newLoader).getResource("test"); } }); assertEquals(currentLoader, Thread.currentThread().getContextClassLoader()); verify(newLoader).getResource("test"); }
### Question: EfficientStringUtils { public static boolean endsWith(final String src, final String... suffixes) { int pos = src.length(); for (int i = suffixes.length - 1; i >= 0; i--) { final String suffix = suffixes[i]; pos -= suffix.length(); if (!src.startsWith(suffix, pos)) { return false; } } return true; } static boolean endsWith(final String src, final String... suffixes); }### Answer: @Test public void testEndsWith() { assertTrue(endsWith("abc", "c")); assertTrue(endsWith("foo.xml", ".", "xml")); assertTrue(endsWith("foo", "foo")); } @Test public void testEndsWithEmptySuffixes() { assertTrue(endsWith("foo", "")); assertTrue(endsWith("", "")); assertTrue(endsWith("foo")); assertTrue(endsWith("")); } @Test public void testEndsWithNoMatchingSuffix() { assertFalse(endsWith("foo", "ooo")); assertFalse(endsWith("foo.xml", ".")); }
### Question: ClassUtils { public static Set<Class> findAllTypes(Class cls) { Set<Class> types = new HashSet<Class>(); findAllTypes(cls, types); return types; } private ClassUtils(); static Set<Class> findAllTypes(Class cls); static void findAllTypes(Class cls, Set<Class> types); static List<Class<?>> getTypeArguments( Class<T> baseClass, Class<? extends T> childClass); }### Answer: @Test public void testFindAllTypes() { assertEquals(newHashSet( List.class, AbstractList.class, Cloneable.class, RandomAccess.class, AbstractCollection.class, Iterable.class, Collection.class, ArrayList.class, Object.class, Serializable.class ), ClassUtils.findAllTypes(ArrayList.class)); }
### Question: AlternativeDirectoryResourceLoader implements AlternativeResourceLoader { public InputStream getResourceAsStream(String name) { URL url = getResource(name); if (url != null) { try { return url.openStream(); } catch (IOException e) { log.error("Unable to open URL " + url, e); } } return null; } AlternativeDirectoryResourceLoader(); URL getResource(String path); InputStream getResourceAsStream(String name); List<File> getResourceDirectories(); static final String PLUGIN_RESOURCE_DIRECTORIES; }### Answer: @Test public void testGetResourceAsStream() throws MalformedURLException { InputStream in = null; try { System.setProperty(AlternativeDirectoryResourceLoader.PLUGIN_RESOURCE_DIRECTORIES, base.getAbsolutePath()); AlternativeResourceLoader loader = new AlternativeDirectoryResourceLoader(); in = loader.getResourceAsStream("kid.txt"); assertNotNull(in); assertNull(loader.getResource("asdfasdfasf")); } finally { System.getProperties().remove(AlternativeDirectoryResourceLoader.PLUGIN_RESOURCE_DIRECTORIES); IOUtils.closeQuietly(in); } }
### Question: ClassLoaderUtils { public static <T> Class<T> loadClass(final String className, final Class<?> callingClass) throws ClassNotFoundException { try { return coerce(Thread.currentThread().getContextClassLoader().loadClass(className)); } catch (final ClassNotFoundException e) { try { return coerce(Class.forName(className)); } catch (final ClassNotFoundException ex) { try { return coerce(ClassLoaderUtils.class.getClassLoader().loadClass(className)); } catch (final ClassNotFoundException exc) { if ((callingClass != null) && (callingClass.getClassLoader() != null)) { return coerce(callingClass.getClassLoader().loadClass(className)); } else { throw exc; } } } } } static Class<T> loadClass(final String className, final Class<?> callingClass); static URL getResource(final String resourceName, final Class<?> callingClass); static Enumeration<URL> getResources(final String resourceName, final Class<?> callingClass); static InputStream getResourceAsStream(final String resourceName, final Class<?> callingClass); static void printClassLoader(); static void printClassLoader(final ClassLoader cl); }### Answer: @Test public void testLoadClass() throws ClassNotFoundException { assertSame(ClassLoaderUtilsTest.class, ClassLoaderUtils.loadClass(ClassLoaderUtilsTest.class.getName(), this.getClass())); try { ClassLoaderUtils.loadClass("some.class", null); fail("Should have thrown a class not found exception"); } catch (ClassNotFoundException ignored) { } }
### Question: XmlDescriptorParser implements DescriptorParser { public PluginInformation getPluginInformation() { return createPluginInformation(getDocument().getRootElement().element("plugin-info")); } XmlDescriptorParser(final Document source, final String... applicationKeys); XmlDescriptorParser(final InputStream source, final String... applicationKeys); Plugin configurePlugin(final ModuleDescriptorFactory moduleDescriptorFactory, final Plugin plugin); String getKey(); int getPluginsVersion(); PluginInformation getPluginInformation(); boolean isSystemPlugin(); }### Answer: @Test public void testPluginsApplicationVersionMinMax() { XmlDescriptorParser parser = parse(null, "<maera-plugin key='foo'>", " <plugin-info>", " <application-version min='3' max='4' />", " </plugin-info>", "</maera-plugin>"); assertEquals(3, (int) parser.getPluginInformation().getMinVersion()); assertEquals(4, (int) parser.getPluginInformation().getMaxVersion()); } @Test public void testPluginsApplicationVersionMinMaxWithOnlyMax() { XmlDescriptorParser parser = parse(null, "<maera-plugin key='foo'>", " <plugin-info>", " <application-version max='3' />", " </plugin-info>", "</maera-plugin>"); assertEquals(3, (int) parser.getPluginInformation().getMaxVersion()); assertEquals(0, (int) parser.getPluginInformation().getMinVersion()); } @Test public void testPluginsApplicationVersionMinMaxWithOnlyMin() { XmlDescriptorParser parser = parse(null, "<maera-plugin key='foo'>", " <plugin-info>", " <application-version min='3' />", " </plugin-info>", "</maera-plugin>"); assertEquals(3, (int) parser.getPluginInformation().getMinVersion()); assertEquals(0, (int) parser.getPluginInformation().getMaxVersion()); }
### Question: XmlDescriptorParser implements DescriptorParser { public int getPluginsVersion() { String val = getPluginElement().attributeValue("pluginsVersion"); if (val == null) { val = getPluginElement().attributeValue("plugins-version"); } if (val != null) { try { return Integer.parseInt(val); } catch (final NumberFormatException e) { throw new RuntimeException("Could not parse pluginsVersion: " + e.getMessage(), e); } } else { return 1; } } XmlDescriptorParser(final Document source, final String... applicationKeys); XmlDescriptorParser(final InputStream source, final String... applicationKeys); Plugin configurePlugin(final ModuleDescriptorFactory moduleDescriptorFactory, final Plugin plugin); String getKey(); int getPluginsVersion(); PluginInformation getPluginInformation(); boolean isSystemPlugin(); }### Answer: @Test public void testPluginsVersion() { String xml = "<maera-plugin key=\"foo\" pluginsVersion=\"2\" />"; XmlDescriptorParser parser = new XmlDescriptorParser(new ByteArrayInputStream(xml.getBytes())); assertEquals(2, parser.getPluginsVersion()); } @Test public void testPluginsVersionMissing() { String xml = "<maera-plugin key=\"foo\" />"; XmlDescriptorParser parser = new XmlDescriptorParser(new ByteArrayInputStream(xml.getBytes())); assertEquals(1, parser.getPluginsVersion()); } @Test public void testPluginsVersionWithDash() { String xml = "<maera-plugin key=\"foo\" plugins-version=\"2\" />"; XmlDescriptorParser parser = new XmlDescriptorParser(new ByteArrayInputStream(xml.getBytes())); assertEquals(2, parser.getPluginsVersion()); }
### Question: JarPluginArtifact implements PluginArtifact { public InputStream getResourceAsStream(String fileName) throws PluginParseException { Validate.notNull(fileName, "The file name must not be null"); final JarFile jar; try { jar = new JarFile(jarFile); } catch (IOException e) { throw new PluginParseException("Cannot open JAR file for reading: " + jarFile, e); } ZipEntry entry = jar.getEntry(fileName); if (entry == null) { return null; } InputStream descriptorStream; try { descriptorStream = new BufferedInputStream(jar.getInputStream(entry)) { public void close() throws IOException { super.close(); jar.close(); } }; } catch (IOException e) { throw new PluginParseException("Cannot retrieve " + fileName + " from plugin JAR [" + jarFile + "]", e); } return descriptorStream; } JarPluginArtifact(File jarFile); boolean doesResourceExist(String name); InputStream getResourceAsStream(String fileName); String getName(); @Override String toString(); InputStream getInputStream(); File toFile(); }### Answer: @Test public void testGetResourceAsStream() throws IOException { File plugin = new PluginJarBuilder() .addResource("foo", "bar") .build(); JarPluginArtifact artifact = new JarPluginArtifact(plugin); assertNotNull(artifact.getResourceAsStream("foo")); assertNull(artifact.getResourceAsStream("bar")); }
### Question: ModuleOfClassPredicate implements ModuleDescriptorPredicate<T> { public boolean matches(final ModuleDescriptor<? extends T> moduleDescriptor) { if (moduleDescriptor != null) { final Class<? extends T> moduleClassInDescriptor = moduleDescriptor.getModuleClass(); return (moduleClassInDescriptor != null) && moduleClass.isAssignableFrom(moduleClassInDescriptor); } return false; } ModuleOfClassPredicate(final Class<T> moduleClass); boolean matches(final ModuleDescriptor<? extends T> moduleDescriptor); }### Answer: @Test public void testDoesNotMatchModuleNotExtendingClass() { mockModuleDescriptor.matchAndReturn("getModuleClass", int.class); assertFalse(moduleDescriptorPredicate.matches(moduleDescriptor)); } @Test public void testMatchesModuleExtendingClass() { mockModuleDescriptor.matchAndReturn("getModuleClass", this.getClass()); assertTrue(moduleDescriptorPredicate.matches(moduleDescriptor)); }
### Question: EnabledModulePredicate implements ModuleDescriptorPredicate<T> { public boolean matches(final ModuleDescriptor<? extends T> moduleDescriptor) { return (moduleDescriptor != null) && pluginAccessor.isPluginModuleEnabled(moduleDescriptor.getCompleteKey()); } EnabledModulePredicate(final PluginAccessor pluginAccessor); boolean matches(final ModuleDescriptor<? extends T> moduleDescriptor); }### Answer: @Test public void testDoesNotMatchDisabledModule() { mockPluginAccessor.matchAndReturn("isPluginModuleEnabled", C.eq(MODULE_TEST_KEY), false); assertFalse(moduleDescriptorPredicate.matches(moduleDescriptor)); } @Test public void testMatchesEnabledModule() { mockPluginAccessor.matchAndReturn("isPluginModuleEnabled", C.eq(MODULE_TEST_KEY), true); assertTrue(moduleDescriptorPredicate.matches(moduleDescriptor)); }
### Question: EnabledPluginPredicate implements PluginPredicate { public boolean matches(final Plugin plugin) { return plugin != null && pluginAccessor.isPluginEnabled(plugin.getKey()); } EnabledPluginPredicate(final PluginAccessor pluginAccessor); boolean matches(final Plugin plugin); }### Answer: @Test public void testDoesNotMatchDisabledPlugin() { mockPluginAccessor.matchAndReturn("isPluginEnabled", C.eq(TEST_PLUGIN_KEY), false); assertFalse(pluginPredicate.matches(plugin)); } @Test public void testMatchesEnabledPlugin() { mockPluginAccessor.matchAndReturn("isPluginEnabled", C.eq(TEST_PLUGIN_KEY), true); assertTrue(pluginPredicate.matches(plugin)); }
### Question: ModuleDescriptorOfClassPredicate implements ModuleDescriptorPredicate<T> { public boolean matches(final ModuleDescriptor<? extends T> moduleDescriptor) { return (moduleDescriptor != null) && CollectionUtils.exists(moduleDescriptorClasses, new Predicate() { public boolean evaluate(final Object object) { return (object != null) && ((Class<?>) object).isInstance(moduleDescriptor); } }); } ModuleDescriptorOfClassPredicate(final Class<? extends ModuleDescriptor<? extends T>> moduleDescriptorClass); ModuleDescriptorOfClassPredicate(final Class<? extends ModuleDescriptor<? extends T>>[] moduleDescriptorClasses); boolean matches(final ModuleDescriptor<? extends T> moduleDescriptor); }### Answer: @Test public void testDoesNotMatchModuleWithModuleDescriptorClassExtendingButNotExactlyMatchingClass() { assertTrue(moduleDescriptorPredicate.matches(new ModuleDescriptorStubB())); } @Test public void testDoesNotMatchModuleWithModuleDescriptorClassNotMatchingClass() { assertFalse(moduleDescriptorPredicate.matches(new MockUnusedModuleDescriptor())); } @Test public void testMatchesModuleWithModuleDescriptorClassExactlyMatchingClass() { assertTrue(moduleDescriptorPredicate.matches(new ModuleDescriptorStubA())); }
### Question: AbstractModuleDescriptor implements ModuleDescriptor<T>, StateAware { Class<?> getModuleReturnClass() { try { return getClass().getMethod("getModule").getReturnType(); } catch (NoSuchMethodException e) { throw new IllegalStateException("The getModule() method is missing (!) on " + getClass()); } } AbstractModuleDescriptor(final ModuleFactory moduleFactory); @Deprecated AbstractModuleDescriptor(); void init(@NotNull final Plugin plugin, @NotNull final Element element); void destroy(final Plugin plugin); boolean isEnabledByDefault(); boolean isSystemModule(); @Deprecated boolean isSingleton(); String getCompleteKey(); String getPluginKey(); String getKey(); String getName(); Class<T> getModuleClass(); abstract T getModule(); String getDescription(); Map<String, String> getParams(); String getI18nNameKey(); String getDescriptionKey(); List<ResourceDescriptor> getResourceDescriptors(); List<ResourceDescriptor> getResourceDescriptors(final String type); ResourceLocation getResourceLocation(final String type, final String name); ResourceDescriptor getResourceDescriptor(final String type, final String name); Float getMinJavaVersion(); boolean satisfiesMinJavaVersion(); void setPlugin(final Plugin plugin); Plugin getPlugin(); @Override String toString(); void enabled(); void disabled(); }### Answer: @Test public void testGetModuleReturnClass() { AbstractModuleDescriptor desc = new MockAnimalModuleDescriptor(); assertEquals(MockAnimal.class, desc.getModuleReturnClass()); } @Test public void testGetModuleReturnClassWithExtendsNumber() { ModuleFactory moduleFactory = mock(ModuleFactory.class); AbstractModuleDescriptor moduleDescriptor = new ExtendsNothingModuleDescriptor(moduleFactory, "foo"); assertEquals(Object.class, moduleDescriptor.getModuleReturnClass()); }
### Question: AbstractModuleDescriptor implements ModuleDescriptor<T>, StateAware { public ResourceDescriptor getResourceDescriptor(final String type, final String name) { return resources.getResourceDescriptor(type, name); } AbstractModuleDescriptor(final ModuleFactory moduleFactory); @Deprecated AbstractModuleDescriptor(); void init(@NotNull final Plugin plugin, @NotNull final Element element); void destroy(final Plugin plugin); boolean isEnabledByDefault(); boolean isSystemModule(); @Deprecated boolean isSingleton(); String getCompleteKey(); String getPluginKey(); String getKey(); String getName(); Class<T> getModuleClass(); abstract T getModule(); String getDescription(); Map<String, String> getParams(); String getI18nNameKey(); String getDescriptionKey(); List<ResourceDescriptor> getResourceDescriptors(); List<ResourceDescriptor> getResourceDescriptors(final String type); ResourceLocation getResourceLocation(final String type, final String name); ResourceDescriptor getResourceDescriptor(final String type, final String name); Float getMinJavaVersion(); boolean satisfiesMinJavaVersion(); void setPlugin(final Plugin plugin); Plugin getPlugin(); @Override String toString(); void enabled(); void disabled(); }### Answer: @Test public void testGetResourceDescriptor() throws DocumentException, PluginParseException { ModuleDescriptor descriptor = makeSingletonDescriptor(); descriptor.init(new StaticPlugin(), DocumentHelper.parseText("<animal key=\"key\" name=\"bear\" class=\"org.maera.plugin.mock.MockBear\">" + "<resource type='velocity' name='view' location='foo' />" + "</animal>").getRootElement()); assertNull(descriptor.getResourceLocation("foo", "bar")); assertNull(descriptor.getResourceLocation("velocity", "bar")); assertNull(descriptor.getResourceLocation("foo", "view")); assertEquals(new ResourceDescriptor(DocumentHelper.parseText("<resource type='velocity' name='view' location='foo' />").getRootElement()).getResourceLocationForName("view").getLocation(), descriptor.getResourceLocation("velocity", "view").getLocation()); }
### Question: AbstractModuleDescriptor implements ModuleDescriptor<T>, StateAware { @Deprecated protected void loadClass(final Plugin plugin, final Element element) throws PluginParseException { loadClass(plugin, element.attributeValue("class")); } AbstractModuleDescriptor(final ModuleFactory moduleFactory); @Deprecated AbstractModuleDescriptor(); void init(@NotNull final Plugin plugin, @NotNull final Element element); void destroy(final Plugin plugin); boolean isEnabledByDefault(); boolean isSystemModule(); @Deprecated boolean isSingleton(); String getCompleteKey(); String getPluginKey(); String getKey(); String getName(); Class<T> getModuleClass(); abstract T getModule(); String getDescription(); Map<String, String> getParams(); String getI18nNameKey(); String getDescriptionKey(); List<ResourceDescriptor> getResourceDescriptors(); List<ResourceDescriptor> getResourceDescriptors(final String type); ResourceLocation getResourceLocation(final String type, final String name); ResourceDescriptor getResourceDescriptor(final String type, final String name); Float getMinJavaVersion(); boolean satisfiesMinJavaVersion(); void setPlugin(final Plugin plugin); Plugin getPlugin(); @Override String toString(); void enabled(); void disabled(); }### Answer: @Test public void testLoadClassFromNewModuleFactoryWithExtendsNothingType() { ModuleFactory moduleFactory = mock(ModuleFactory.class); AbstractModuleDescriptor moduleDescriptor = new ExtendsNothingModuleDescriptor(moduleFactory, "foo"); Plugin plugin = mock(Plugin.class); try { moduleDescriptor.loadClass(plugin, "foo"); fail("Should have complained about extends type"); } catch (IllegalStateException ex) { } } @Test public void testLoadClassFromNewModuleFactoryWithExtendsNumberType() { ModuleFactory moduleFactory = mock(ModuleFactory.class); AbstractModuleDescriptor moduleDescriptor = new ExtendsNumberModuleDescriptor(moduleFactory, "foo"); Plugin plugin = mock(Plugin.class); try { moduleDescriptor.loadClass(plugin, "foo"); fail("Should have complained about extends type"); } catch (IllegalStateException ex) { } }
### Question: DefaultPluginArtifactFactory implements PluginArtifactFactory { public PluginArtifact create(URI artifactUri) { PluginArtifact artifact = null; String protocol = artifactUri.getScheme(); if ("file".equalsIgnoreCase(protocol)) { File artifactFile = new File(artifactUri); String file = artifactFile.getName(); if (file.endsWith(".jar")) artifact = new JarPluginArtifact(artifactFile); else if (file.endsWith(".xml")) artifact = new XmlPluginArtifact(artifactFile); } if (artifact == null) throw new IllegalArgumentException("The artifact URI " + artifactUri + " is not a valid plugin artifact"); return artifact; } PluginArtifact create(URI artifactUri); }### Answer: @Test public void testCreate() throws IOException { doCreationTestInDirectory(testDir); }
### Question: FilePluginInstaller implements RevertablePluginInstaller { public void clearBackups() { for (File file : directory.listFiles(new BackupNameFilter())) { file.delete(); } installedPlugins.clear(); } FilePluginInstaller(File directory); void installPlugin(String key, PluginArtifact pluginArtifact); void revertInstalledPlugin(String pluginKey); void clearBackups(); static final String ORIGINAL_PREFIX; }### Answer: @Test public void testClearBackups() throws IOException { FilePluginInstaller installer = new FilePluginInstaller(pluginDir); File pluginFile = File.createTempFile("plugin", ".jar", pluginDir); FileUtils.writeStringToFile(pluginFile, "foo"); File upgradedFile = new File(tmpDir, pluginFile.getName()); FileUtils.writeStringToFile(upgradedFile, "bar"); installer.installPlugin("foo", new XmlPluginArtifact(upgradedFile)); assertTrue(new File(pluginDir, FilePluginInstaller.ORIGINAL_PREFIX + pluginFile.getName()).exists()); installer.clearBackups(); assertTrue(pluginFile.exists()); assertFalse(new File(pluginDir, FilePluginInstaller.ORIGINAL_PREFIX + pluginFile.getName()).exists()); }
### Question: PluginResourceLocatorImpl implements PluginResourceLocator { public boolean matches(final String url) { return SuperBatchPluginResource.matches(url) || SuperBatchSubResource.matches(url) || SinglePluginResource.matches(url) || BatchPluginResource.matches(url); } PluginResourceLocatorImpl(final WebResourceIntegration webResourceIntegration, final ServletContextFactory servletContextFactory); PluginResourceLocatorImpl(final WebResourceIntegration webResourceIntegration, final ServletContextFactory servletContextFactory, final ResourceBatchingConfiguration resourceBatchingConfiguration); private PluginResourceLocatorImpl(final WebResourceIntegration webResourceIntegration, final ServletContextFactory servletContextFactory, final ResourceDependencyResolver dependencyResolver); boolean matches(final String url); DownloadableResource getDownloadableResource(final String url, final Map<String, String> queryParams); List<PluginResource> getPluginResources(final String moduleCompleteKey); String getResourceUrl(final String moduleCompleteKey, final String resourceName); static final String PLUGIN_WEBRESOURCE_BATCHING_OFF; }### Answer: @Test public void testMatches() { assertTrue(pluginResourceLocator.matches("/download/superbatch/css/batch.css")); assertTrue(pluginResourceLocator.matches("/download/superbatch/css/images/background/blah.gif")); assertTrue(pluginResourceLocator.matches("/download/batch/plugin.key:module-key/plugin.key.js")); assertTrue(pluginResourceLocator.matches("/download/resources/plugin.key:module-key/foo.png")); } @Test public void testNotMatches() { assertFalse(pluginResourceLocator.matches("/superbatch/batch.css")); assertFalse(pluginResourceLocator.matches("/download/blah.css")); }
### Question: FilePluginInstaller implements RevertablePluginInstaller { public void revertInstalledPlugin(String pluginKey) { OriginalFile orig = installedPlugins.get(pluginKey); if (orig != null) { File origFile = new File(orig.getBackupFile().getParent(), orig.getOriginalName()); if (origFile.exists()) { origFile.delete(); } if (orig.isUpgrade()) { try { FileUtils.moveFile(orig.getBackupFile(), origFile); } catch (IOException e) { log.warn("Unable to restore old plugin for " + pluginKey); } } } } FilePluginInstaller(File directory); void installPlugin(String key, PluginArtifact pluginArtifact); void revertInstalledPlugin(String pluginKey); void clearBackups(); static final String ORIGINAL_PREFIX; }### Answer: @Test public void testRevertInstalledPlugin() throws IOException { FilePluginInstaller installer = new FilePluginInstaller(pluginDir); File pluginFile = File.createTempFile("plugin", ".jar", tmpDir); installer.installPlugin("foo", new XmlPluginArtifact(pluginFile)); installer.revertInstalledPlugin("foo"); assertFalse(new File(pluginDir, pluginFile.getName()).exists()); }
### Question: PluginClassLoader extends ClassLoader { @Override public URL getResource(final String name) { if (isEntryInPlugin(name)) { return entryMappings.get(name); } else { return super.getResource(name); } } PluginClassLoader(final File pluginFile); PluginClassLoader(final File pluginFile, final ClassLoader parent); PluginClassLoader(final File pluginFile, final ClassLoader parent, final File tempDirectory); void close(); URL getLocalResource(final String name); @Override URL getResource(final String name); }### Answer: @Test public void testPluginClassLoaderDoesNotLockTheJarsPermanently() throws Exception { String fileLoc = getClass().getClassLoader().getResource(PluginTestUtils.SIMPLE_TEST_JAR).getFile(); File original = new File(fileLoc); File tmpFile = new File(fileLoc + ".tmp"); FileUtils.copyFile(original, tmpFile); PluginClassLoader pluginClassLoaderThatHasNotLockedFileYet = new PluginClassLoader(tmpFile, getClass().getClassLoader()); Class mockVersionedClass = Class.forName("org.maera.plugin.mock.MockVersionedClass", true, pluginClassLoader); assertTrue(tmpFile.delete()); } @Test public void testPluginClassLoaderLoadsResourceFromOuterJarFirst() throws Exception { URL resourceUrl = pluginClassLoader.getResource("testresource.txt"); assertNotNull(resourceUrl); assertEquals("outerjar", IOUtils.toString(resourceUrl.openStream())); }
### Question: PluginClassLoader extends ClassLoader { List<File> getPluginInnerJars() { return new ArrayList<File>(pluginInnerJars); } PluginClassLoader(final File pluginFile); PluginClassLoader(final File pluginFile, final ClassLoader parent); PluginClassLoader(final File pluginFile, final ClassLoader parent, final File tempDirectory); void close(); URL getLocalResource(final String name); @Override URL getResource(final String name); }### Answer: @Test public void testPluginClassLoaderExtractsInnerJarsToSpecifiedDirectory() throws Exception { final List<File> files = pluginClassLoader.getPluginInnerJars(); for (File file : files) { assertEquals(tmpDir, file.getParentFile()); } } @Test public void testPluginClassLoaderFindsInnerJars() throws Exception { List innerJars = pluginClassLoader.getPluginInnerJars(); assertEquals(2, innerJars.size()); }
### Question: PluginClassLoader extends ClassLoader { @Override protected synchronized Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException { final Class<?> c = findLoadedClass(name); if (c != null) { return c; } final String path = name.replace('.', '/').concat(".class"); if (isEntryInPlugin(path)) { try { return loadClassFromPlugin(name, path); } catch (final IOException e) { throw new ClassNotFoundException("Unable to load class [ " + name + " ] from PluginClassLoader", e); } } return super.loadClass(name, resolve); } PluginClassLoader(final File pluginFile); PluginClassLoader(final File pluginFile, final ClassLoader parent); PluginClassLoader(final File pluginFile, final ClassLoader parent, final File tempDirectory); void close(); URL getLocalResource(final String name); @Override URL getResource(final String name); }### Answer: @Test public void testPluginClassLoaderLoadsClassFromOuterJar() throws Exception { Class c = pluginClassLoader.loadClass("org.maera.plugin.simpletest.TestClassOne"); assertEquals("org.maera.plugin.simpletest", c.getPackage().getName()); assertEquals("org.maera.plugin.simpletest.TestClassOne", c.getName()); }
### Question: DelegationClassLoader extends ClassLoader { public void setDelegateClassLoader(ClassLoader delegateClassLoader) { Validate.notNull(delegateClassLoader, "Can't set the delegation target to null"); if (log.isDebugEnabled()) { log.debug("Update class loader delegation from [" + this.delegateClassLoader + "] to [" + delegateClassLoader + "]"); } this.delegateClassLoader = delegateClassLoader; } void setDelegateClassLoader(ClassLoader delegateClassLoader); Class loadClass(String name); URL getResource(String name); @Override Enumeration<URL> getResources(String name); InputStream getResourceAsStream(String name); synchronized void setDefaultAssertionStatus(boolean enabled); synchronized void setPackageAssertionStatus(String packageName, boolean enabled); synchronized void setClassAssertionStatus(String className, boolean enabled); synchronized void clearAssertionStatus(); }### Answer: @Test public void testCanSetDelegate() { DelegationClassLoader dcl = new DelegationClassLoader(); dcl.setDelegateClassLoader(getClass().getClassLoader()); } @Test(expected = IllegalArgumentException.class) public void testCantSetNullDelegate() { DelegationClassLoader dcl = new DelegationClassLoader(); dcl.setDelegateClassLoader(null); }
### Question: DelegationClassLoader extends ClassLoader { public Class loadClass(String name) throws ClassNotFoundException { return delegateClassLoader.loadClass(name); } void setDelegateClassLoader(ClassLoader delegateClassLoader); Class loadClass(String name); URL getResource(String name); @Override Enumeration<URL> getResources(String name); InputStream getResourceAsStream(String name); synchronized void setDefaultAssertionStatus(boolean enabled); synchronized void setPackageAssertionStatus(String packageName, boolean enabled); synchronized void setClassAssertionStatus(String className, boolean enabled); synchronized void clearAssertionStatus(); }### Answer: @Test(expected = ClassNotFoundException.class) public void testCantLoadUnknownClassWithOutDelegateSet() throws ClassNotFoundException { DelegationClassLoader classLoader = new DelegationClassLoader(); classLoader.loadClass("not.a.real.class.path.NotARealClass"); } @Test public void testLoadSystemClassWithOutDelegateSet() throws ClassNotFoundException { DelegationClassLoader classLoader = new DelegationClassLoader(); Class c = classLoader.loadClass("java.lang.String"); assertNotNull(c); }
### Question: PluginResourceLocatorImpl implements PluginResourceLocator { String[] splitLastPathPart(final String resourcePath) { int indexOfSlash = resourcePath.lastIndexOf('/'); if (resourcePath.endsWith("/")) { indexOfSlash = resourcePath.lastIndexOf('/', indexOfSlash - 1); } if (indexOfSlash < 0) { return null; } return new String[]{resourcePath.substring(0, indexOfSlash + 1), resourcePath.substring(indexOfSlash + 1)}; } PluginResourceLocatorImpl(final WebResourceIntegration webResourceIntegration, final ServletContextFactory servletContextFactory); PluginResourceLocatorImpl(final WebResourceIntegration webResourceIntegration, final ServletContextFactory servletContextFactory, final ResourceBatchingConfiguration resourceBatchingConfiguration); private PluginResourceLocatorImpl(final WebResourceIntegration webResourceIntegration, final ServletContextFactory servletContextFactory, final ResourceDependencyResolver dependencyResolver); boolean matches(final String url); DownloadableResource getDownloadableResource(final String url, final Map<String, String> queryParams); List<PluginResource> getPluginResources(final String moduleCompleteKey); String getResourceUrl(final String moduleCompleteKey, final String resourceName); static final String PLUGIN_WEBRESOURCE_BATCHING_OFF; }### Answer: @Test public void testSplitLastPathPart() { final String[] parts = pluginResourceLocator.splitLastPathPart("http: assertEquals(2, parts.length); assertEquals("http: assertEquals("baz", parts[1]); final String[] anotherParts = pluginResourceLocator.splitLastPathPart(parts[0]); assertEquals(2, anotherParts.length); assertEquals("http: assertEquals("bar/", anotherParts[1]); assertNull(pluginResourceLocator.splitLastPathPart("noslashes")); }
### Question: ResourceDescriptor { @Override public int hashCode() { int result = 0; if (type != null) { result = type.hashCode(); } if (name != null) { result = 29 * result + name.hashCode(); } else if (pattern != null) { result = 29 * result + pattern.hashCode(); } return result; } ResourceDescriptor(final Element element); String getType(); String getName(); String getLocation(); String getContent(); boolean doesTypeAndNameMatch(final String type, final String name); Map<String, String> getParameters(); String getParameter(final String key); @Override boolean equals(final Object o); @Override int hashCode(); ResourceLocation getResourceLocationForName(final String name); }### Answer: @Test public void testHashcode() { Element desc = DocumentHelper.createElement("foo"); desc.addAttribute("name", "foo"); desc.addAttribute("type", "bar"); assertNotNull(new ResourceDescriptor(desc).hashCode()); desc.addAttribute("type", null); assertNotNull(new ResourceDescriptor(desc).hashCode()); desc.addAttribute("name", null); desc.addAttribute("namePattern", "foo"); desc.addAttribute("location", "bar"); }
### Question: DefaultModuleDescriptorFactory implements ModuleDescriptorFactory { public ModuleDescriptor<?> getModuleDescriptor(final String type) throws PluginParseException, IllegalAccessException, InstantiationException, ClassNotFoundException { if (shouldSkipModuleOfType(type)) { return null; } @SuppressWarnings("unchecked") final Class<? extends ModuleDescriptor> moduleDescriptorClazz = getModuleDescriptorClass(type); if (moduleDescriptorClazz == null) { throw new PluginParseException("Cannot find ModuleDescriptor class for plugin of type '" + type + "'."); } return hostContainer.create(moduleDescriptorClazz); } @Deprecated DefaultModuleDescriptorFactory(); DefaultModuleDescriptorFactory(final HostContainer hostContainer); @SuppressWarnings("unchecked") Class<? extends ModuleDescriptor> getModuleDescriptorClass(final String type); ModuleDescriptor<?> getModuleDescriptor(final String type); void setModuleDescriptors(final Map<String, String> moduleDescriptorClassNames); boolean hasModuleDescriptor(final String type); void addModuleDescriptor(final String type, final Class<? extends ModuleDescriptor> moduleDescriptorClass); void removeModuleDescriptorForType(final String type); void setPermittedModuleKeys(List<String> permittedModuleKeys); }### Answer: @Test public void testInvalidModuleDescriptorType() { try { moduleDescriptorFactory.getModuleDescriptor("foobar"); fail("Should have thrown exception"); } catch (final IllegalAccessException e) { e.printStackTrace(); } catch (final PluginParseException e) { return; } catch (final ClassNotFoundException e) { e.printStackTrace(); } catch (final InstantiationException e) { e.printStackTrace(); } fail("Threw the wrong exception"); }
### Question: Resources implements Resourced { public ResourceDescriptor getResourceDescriptor(final String type, final String name) { for (final ResourceDescriptor resourceDescriptor : resourceDescriptors) { if (resourceDescriptor.getType().equalsIgnoreCase(type) && resourceDescriptor.getName().equalsIgnoreCase(name)) { return resourceDescriptor; } } return null; } Resources(final Iterable<ResourceDescriptor> resourceDescriptors); static Resources fromXml(final Element element); List<ResourceDescriptor> getResourceDescriptors(); @Deprecated List<ResourceDescriptor> getResourceDescriptors(final String type); ResourceLocation getResourceLocation(final String type, final String name); ResourceDescriptor getResourceDescriptor(final String type, final String name); static final Resources EMPTY_RESOURCES; }### Answer: @Test public void testGetResourceDescriptor() throws DocumentException, PluginParseException { final Resources resources = makeTestResources(); assertNull(resources.getResourceLocation("image", "edit")); assertNull(resources.getResourceLocation("fish", "view")); assertNull(resources.getResourceLocation(null, "view")); assertNull(resources.getResourceLocation("image", null)); assertLocationMatches(resources.getResourceLocation("image", "view"), "image", "view"); }
### Question: Resources implements Resourced { public List<ResourceDescriptor> getResourceDescriptors() { return resourceDescriptors; } Resources(final Iterable<ResourceDescriptor> resourceDescriptors); static Resources fromXml(final Element element); List<ResourceDescriptor> getResourceDescriptors(); @Deprecated List<ResourceDescriptor> getResourceDescriptors(final String type); ResourceLocation getResourceLocation(final String type, final String name); ResourceDescriptor getResourceDescriptor(final String type, final String name); static final Resources EMPTY_RESOURCES; }### Answer: @Test public void testGetResourceDescriptorsByType() throws DocumentException, PluginParseException { final Resources resources = makeTestResources(); assertEquals(0, resources.getResourceDescriptors("blah").size()); final List velocityResources = resources.getResourceDescriptors("velocity"); assertEquals(2, velocityResources.size()); assertDescriptorMatches((ResourceDescriptor) velocityResources.get(0), "velocity", "view"); assertDescriptorMatches((ResourceDescriptor) velocityResources.get(1), "velocity", "edit"); } @Test public void testMultipleResources() throws DocumentException, PluginParseException { final Resources resources = makeTestResources(); final List descriptors = resources.getResourceDescriptors(); assertEquals(3, descriptors.size()); assertDescriptorMatches((ResourceDescriptor) descriptors.get(0), "velocity", "view"); assertDescriptorMatches((ResourceDescriptor) descriptors.get(1), "velocity", "edit"); assertDescriptorMatches((ResourceDescriptor) descriptors.get(2), "image", "view"); } @Test(expected = IllegalArgumentException.class) public void testNullTypeThrows() throws PluginParseException, DocumentException { final Resources resources = makeTestResources(); resources.getResourceDescriptors(null); }
### Question: Resources implements Resourced { public static Resources fromXml(final Element element) throws PluginParseException, IllegalArgumentException { if (element == null) { throw new IllegalArgumentException("Cannot parse resources from null XML element"); } @SuppressWarnings("unchecked") final List<Element> elements = element.elements("resource"); final List<ResourceDescriptor> templates = new ArrayList<ResourceDescriptor>(elements.size()); for (final Element e : elements) { final ResourceDescriptor resourceDescriptor = new ResourceDescriptor(e); if (templates.contains(resourceDescriptor)) { throw new PluginParseException("Duplicate resource with type '" + resourceDescriptor.getType() + "' and name '" + resourceDescriptor.getName() + "' found"); } templates.add(resourceDescriptor); } return new Resources(templates); } Resources(final Iterable<ResourceDescriptor> resourceDescriptors); static Resources fromXml(final Element element); List<ResourceDescriptor> getResourceDescriptors(); @Deprecated List<ResourceDescriptor> getResourceDescriptors(final String type); ResourceLocation getResourceLocation(final String type, final String name); ResourceDescriptor getResourceDescriptor(final String type, final String name); static final Resources EMPTY_RESOURCES; }### Answer: @Test public void testMultipleResourceWithClashingKeysFail() throws DocumentException { final Document document = DocumentHelper.parseText("<foo>" + "<resource type=\"velocity\" name=\"view\">the content</resource>" + "<resource type=\"velocity\" name=\"view\" />" + "</foo>"); try { Resources.fromXml(document.getRootElement()); fail("Should have thrown exception about duplicate resources."); } catch (final PluginParseException e) { assertEquals("Duplicate resource with type 'velocity' and name 'view' found", e.getMessage()); } } @Test(expected = IllegalArgumentException.class) public void testParsingNullElementThrowsException() throws Exception { Resources.fromXml(null); }
### Question: XmlDynamicPluginFactory implements PluginFactory { @Deprecated public Plugin create(final DeploymentUnit deploymentUnit, final ModuleDescriptorFactory moduleDescriptorFactory) throws PluginParseException { return create(new XmlPluginArtifact(deploymentUnit.getPath()), moduleDescriptorFactory); } @Deprecated XmlDynamicPluginFactory(); XmlDynamicPluginFactory(final String applicationKey); XmlDynamicPluginFactory(final Set<String> applicationKeys); @Deprecated Plugin create(final DeploymentUnit deploymentUnit, final ModuleDescriptorFactory moduleDescriptorFactory); Plugin create(final PluginArtifact pluginArtifact, final ModuleDescriptorFactory moduleDescriptorFactory); String canCreate(final PluginArtifact pluginArtifact); }### Answer: @Test(expected = PluginParseException.class) public void testCreateBadXml() { XmlDynamicPluginFactory factory = new XmlDynamicPluginFactory("foo"); Mock mockModuleDescriptorFactory = new Mock(ModuleDescriptorFactory.class); Mock mockArtifact = new Mock(PluginArtifact.class); mockArtifact.expectAndReturn("toFile", new File("sadfasdf")); factory.create((PluginArtifact) mockArtifact.proxy(), (ModuleDescriptorFactory) mockModuleDescriptorFactory.proxy()); }
### Question: LegacyDynamicPluginFactory implements PluginFactory { public Plugin create(DeploymentUnit deploymentUnit, ModuleDescriptorFactory moduleDescriptorFactory) throws PluginParseException { return create(new JarPluginArtifact(deploymentUnit.getPath()), moduleDescriptorFactory); } LegacyDynamicPluginFactory(String pluginDescriptorFileName); LegacyDynamicPluginFactory(String pluginDescriptorFileName, File tempDirectory); Plugin create(DeploymentUnit deploymentUnit, ModuleDescriptorFactory moduleDescriptorFactory); Plugin create(PluginArtifact pluginArtifact, ModuleDescriptorFactory moduleDescriptorFactory); String canCreate(PluginArtifact pluginArtifact); }### Answer: @Test(expected = PluginParseException.class) public void testCreateCorruptJar() { final LegacyDynamicPluginFactory factory = new LegacyDynamicPluginFactory(PluginAccessor.Descriptor.FILENAME); final Mock mockModuleDescriptorFactory = new Mock(ModuleDescriptorFactory.class); Mock mockArtifact = new Mock(PluginArtifact.class); mockArtifact.expectAndReturn("getResourceAsStream", C.ANY_ARGS, null); mockArtifact.expectAndReturn("toFile", new File("sadfasdf")); factory.create((PluginArtifact) mockArtifact.proxy(), (ModuleDescriptorFactory) mockModuleDescriptorFactory.proxy()); }
### Question: LoaderUtils { public static Map<String, String> getParams(final Element element) { @SuppressWarnings("unchecked") final List<Element> elements = element.elements("param"); final Map<String, String> params = new HashMap<String, String>(elements.size()); for (final Element paramEl : elements) { final String name = paramEl.attributeValue("name"); String value = paramEl.attributeValue("value"); if ((value == null) && (paramEl.getTextTrim() != null) && !"".equals(paramEl.getTextTrim())) { value = paramEl.getTextTrim(); } params.put(name, value); } return params; } @Deprecated static List<ResourceDescriptor> getResourceDescriptors(final Element element); static Map<String, String> getParams(final Element element); }### Answer: @Test public void testMultipleParameters() throws DocumentException { Document document = DocumentHelper.parseText("<foo>" + "<param name=\"colour\">green</param>" + "<param name=\"size\" value=\"large\" />" + "</foo>"); Map params = LoaderUtils.getParams(document.getRootElement()); assertEquals(2, params.size()); assertEquals("green", params.get("colour")); assertEquals("large", params.get("size")); }
### Question: DirectoryScanner implements org.maera.plugin.loaders.classloading.Scanner { public void remove(DeploymentUnit unit) throws PluginException { if (unit.getPath().exists()) { if (!unit.getPath().delete()) { throw new PluginException("Unable to delete file: " + unit.getPath()); } } else { log.debug("Plugin file <" + unit.getPath().getPath() + "> doesn't exist to delete. Ignoring."); } clear(unit.getPath()); } DirectoryScanner(File pluginsDirectory); DeploymentUnit locateDeploymentUnit(File file); void clear(File file); Collection<DeploymentUnit> scan(); Collection<DeploymentUnit> getDeploymentUnits(); void reset(); void remove(DeploymentUnit unit); }### Answer: @Test public void testRemove() { File pluginsDirectory = pluginsTestDir; File paddington = new File(pluginsDirectory, "paddington-test-plugin.jar"); assertTrue(paddington.exists()); DirectoryScanner scanner = new DirectoryScanner(pluginsDirectory); scanner.scan(); assertEquals(2, scanner.getDeploymentUnits().size()); DeploymentUnit paddingtonUnit = scanner.locateDeploymentUnit(paddington); scanner.remove(paddingtonUnit); assertFalse(paddington.exists()); assertEquals(1, scanner.getDeploymentUnits().size()); }
### Question: SinglePluginLoader implements PluginLoader { protected InputStream getSource() { if (resource != null) { return ClassLoaderUtils.getResourceAsStream(resource, this.getClass()); } if (url != null) { try { return url.openConnection().getInputStream(); } catch (IOException e) { throw new PluginParseException(e); } } final InputStream inputStream = inputStreamRef.getAndSet(null); if (inputStream != null) { return inputStream; } throw new IllegalStateException("No defined method for getting an input stream."); } SinglePluginLoader(final String resource); SinglePluginLoader(final URL url); SinglePluginLoader(final InputStream is); Collection<Plugin> loadAllPlugins(final ModuleDescriptorFactory moduleDescriptorFactory); boolean supportsRemoval(); boolean supportsAddition(); Collection<Plugin> addFoundPlugins(final ModuleDescriptorFactory moduleDescriptorFactory); void removePlugin(final Plugin plugin); }### Answer: @Deprecated @Test(expected = IllegalStateException.class) public void testPluginByInputStreamNotReentrant() { final SinglePluginLoader loader = new SinglePluginLoader(ClassLoaderUtils.getResourceAsStream("test-disabled-plugin.xml", SinglePluginLoader.class)); loader.getSource(); loader.getSource(); }
### Question: SinglePluginLoader implements PluginLoader { public SinglePluginLoader(final String resource) { this.resource = notNull("resource", resource); url = null; inputStreamRef = new AtomicReference<InputStream>(null); } SinglePluginLoader(final String resource); SinglePluginLoader(final URL url); SinglePluginLoader(final InputStream is); Collection<Plugin> loadAllPlugins(final ModuleDescriptorFactory moduleDescriptorFactory); boolean supportsRemoval(); boolean supportsAddition(); Collection<Plugin> addFoundPlugins(final ModuleDescriptorFactory moduleDescriptorFactory); void removePlugin(final Plugin plugin); }### Answer: @Test public void testSinglePluginLoader() throws Exception { final SinglePluginLoader loader = new SinglePluginLoader("test-system-plugin.xml"); final DefaultModuleDescriptorFactory moduleDescriptorFactory = new DefaultModuleDescriptorFactory(new DefaultHostContainer()); moduleDescriptorFactory.addModuleDescriptor("animal", MockAnimalModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("mineral", MockMineralModuleDescriptor.class); final Collection plugins = loader.loadAllPlugins(moduleDescriptorFactory); assertEquals(1, plugins.size()); final Plugin plugin = (Plugin) plugins.iterator().next(); assertTrue(plugin.isSystemPlugin()); }
### Question: DeploymentUnit implements Comparable<DeploymentUnit> { public int compareTo(DeploymentUnit target) { int result = path.compareTo(target.getPath()); if (result == 0) result = (lastModifiedAtTimeOfDeployment > target.lastModified() ? 1 : lastModifiedAtTimeOfDeployment < target.lastModified() ? -1 : 0); return result; } DeploymentUnit(File path); long lastModified(); File getPath(); int compareTo(DeploymentUnit target); boolean equals(Object deploymentUnit); boolean equals(DeploymentUnit deploymentUnit); int hashCode(); String toString(); }### Answer: @Test public void testCompareTo() throws IOException { File tmp = File.createTempFile("testDeploymentUnit", ".txt"); DeploymentUnit unit1 = new DeploymentUnit(tmp); DeploymentUnit unit2 = new DeploymentUnit(tmp); assertEquals(0, unit1.compareTo(unit2)); tmp.setLastModified(System.currentTimeMillis() + 1000); unit2 = new DeploymentUnit(tmp); assertEquals(-1, unit1.compareTo(unit2)); }
### Question: ClassPathPluginLoader implements PluginLoader { public Collection<Plugin> loadAllPlugins(final ModuleDescriptorFactory moduleDescriptorFactory) throws PluginParseException { if (plugins == null) { loadClassPathPlugins(moduleDescriptorFactory); } return plugins; } ClassPathPluginLoader(); ClassPathPluginLoader(final String fileNameToLoad); Collection<Plugin> loadAllPlugins(final ModuleDescriptorFactory moduleDescriptorFactory); boolean supportsRemoval(); boolean supportsAddition(); Collection<Plugin> addFoundPlugins(final ModuleDescriptorFactory moduleDescriptorFactory); void removePlugin(final Plugin plugin); }### Answer: @Test public void testAtlassianPlugin() throws Exception { ClassPathPluginLoader loader = new ClassPathPluginLoader("test-maera-plugin.xml"); DefaultModuleDescriptorFactory moduleDescriptorFactory = new DefaultModuleDescriptorFactory(new DefaultHostContainer()); moduleDescriptorFactory.addModuleDescriptor("animal", MockAnimalModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("mineral", MockMineralModuleDescriptor.class); moduleDescriptorFactory.addModuleDescriptor("vegetable", MockMineralModuleDescriptor.class); Collection plugins = loader.loadAllPlugins(moduleDescriptorFactory); Plugin plugin = (Plugin) plugins.iterator().next(); assertEquals("Test Plugin", plugin.getName()); assertEquals("test.maera.plugin", plugin.getKey()); assertEquals("This plugin descriptor is just used for test purposes!", plugin.getPluginInformation().getDescription()); assertEquals(4, plugin.getModuleDescriptors().size()); assertEquals("Bear Animal", plugin.getModuleDescriptor("bear").getName()); }
### Question: NotificationException extends PluginException { public List<Throwable> getAllCauses() { return allCauses; } NotificationException(final Throwable cause); NotificationException(final List<Throwable> causes); List<Throwable> getAllCauses(); }### Answer: @Test public void testListConstructor() throws Exception { Exception cause1 = new Exception("I don't like it"); Exception cause2 = new Exception("Me neither"); final List<Throwable> causes = new ArrayList<Throwable>(); causes.add(cause1); causes.add(cause2); NotificationException notificationException = new NotificationException(causes); assertEquals(cause1, notificationException.getCause()); assertEquals(2, notificationException.getAllCauses().size()); assertEquals(cause1, notificationException.getAllCauses().get(0)); assertEquals(cause2, notificationException.getAllCauses().get(1)); } @Test public void testSingletonConstructor() throws Exception { Exception cause = new Exception("I don't like it"); NotificationException notificationException = new NotificationException(cause); assertEquals(cause, notificationException.getCause()); assertEquals(1, notificationException.getAllCauses().size()); assertEquals(cause, notificationException.getAllCauses().get(0)); }
### Question: ServletFilterModuleContainerFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); } void init(FilterConfig filterConfig); void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); void destroy(); }### Answer: @Test public void testFilter() throws IOException, ServletException { when(moduleManager.getFilters(any(FilterLocation.class), eq("/myfilter"), any(FilterConfig.class), eq(FilterDispatcherCondition.REQUEST))).thenReturn(Collections.<Filter>emptyList()); MyFilter filter = new MyFilter(moduleManager); when(request.getContextPath()).thenReturn("/myapp"); when(request.getRequestURI()).thenReturn("/myapp/myfilter"); filter.doFilter(request, response, filterChain); verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); } @Test public void testNoServletModuleManager() throws IOException, ServletException { MyFilter filter = new MyFilter(null); filter.doFilter(request, response, filterChain); verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); }
### Question: PluginServletContextWrapper implements ServletContext { public Object getAttribute(String name) { Object attr = attributes.get(name); if (attr == null) attr = context.getAttribute(name); return attr; } PluginServletContextWrapper(Plugin plugin, ServletContext context, ConcurrentMap<String, Object> attributes, Map<String, String> initParams); Object getAttribute(String name); Enumeration getAttributeNames(); void removeAttribute(String name); void setAttribute(String name, Object object); String getInitParameter(String name); Enumeration getInitParameterNames(); URL getResource(String path); InputStream getResourceAsStream(String path); ServletContext getContext(String uripath); String getContextPath(); int getMajorVersion(); String getMimeType(String file); int getMinorVersion(); RequestDispatcher getNamedDispatcher(String name); String getRealPath(String path); RequestDispatcher getRequestDispatcher(String path); Set getResourcePaths(String arg0); String getServerInfo(); Servlet getServlet(String name); String getServletContextName(); Enumeration getServletNames(); Enumeration getServlets(); void log(Exception exception, String msg); void log(String message, Throwable throwable); void log(String msg); }### Answer: @Test public void testGetAttributeDelegatesToWrappedContext() { assertEquals("wrapped value", contextWrapper.getAttribute("wrapped")); }
### Question: PluginHttpRequestWrapper extends HttpServletRequestWrapper { @Override public HttpSession getSession() { return this.getSession(true); } PluginHttpRequestWrapper(HttpServletRequest request, BaseServletModuleDescriptor<?> descriptor); String getServletPath(); String getPathInfo(); @Override HttpSession getSession(); @Override HttpSession getSession(final boolean create); }### Answer: @Test public void testGetSession() throws Exception { Mock mockSession = new Mock(HttpSession.class); mockSession.matchAndReturn("getAttribute", "foo", "bar"); HttpSession realSession = (HttpSession) mockSession.proxy(); Mock mockWrappedRequest = new Mock(HttpServletRequest.class); mockWrappedRequest.matchAndReturn("getPathInfo", null); mockWrappedRequest.matchAndReturn("getSession", true, realSession); PluginHttpRequestWrapper request = new PluginHttpRequestWrapper((HttpServletRequest) mockWrappedRequest.proxy(), null); HttpSession wrappedSession = request.getSession(); assertTrue(wrappedSession instanceof PluginHttpSessionWrapper); assertEquals("bar", wrappedSession.getAttribute("foo")); } @Test public void testGetSessionFalse() throws Exception { Mock mockWrappedRequest = new Mock(HttpServletRequest.class); mockWrappedRequest.matchAndReturn("getPathInfo", null); mockWrappedRequest.matchAndReturn("getSession", false, null); PluginHttpRequestWrapper request = new PluginHttpRequestWrapper((HttpServletRequest) mockWrappedRequest.proxy(), null); assertNull(request.getSession(false)); } @Test public void testGetSessionTrue() throws Exception { Mock mockSession = new Mock(HttpSession.class); mockSession.matchAndReturn("getAttribute", "foo", "bar"); HttpSession realSession = (HttpSession) mockSession.proxy(); Mock mockWrappedRequest = new Mock(HttpServletRequest.class); mockWrappedRequest.matchAndReturn("getPathInfo", null); mockWrappedRequest.matchAndReturn("getSession", true, realSession); PluginHttpRequestWrapper request = new PluginHttpRequestWrapper((HttpServletRequest) mockWrappedRequest.proxy(), null); HttpSession wrappedSession = request.getSession(true); assertTrue(wrappedSession instanceof PluginHttpSessionWrapper); assertEquals("bar", wrappedSession.getAttribute("foo")); }
### Question: PluginHttpSessionWrapper implements HttpSession { public Object getAttribute(final String name) { ClassLoader classLoader = ClassLoaderStack.pop(); try { if (log.isDebugEnabled()) { log.debug("getAttribute('" + name + "') Popping ClassLoader: " + classLoader + " .New ContextClassLoader: " + Thread.currentThread().getContextClassLoader()); } return delegate.getAttribute(name); } finally { ClassLoaderStack.push(classLoader); } } PluginHttpSessionWrapper(final HttpSession session); Object getAttribute(final String name); void setAttribute(final String name, final Object value); Object getValue(final String name); void putValue(final String name, final Object value); long getCreationTime(); String getId(); long getLastAccessedTime(); ServletContext getServletContext(); void setMaxInactiveInterval(final int interval); int getMaxInactiveInterval(); @SuppressWarnings({"deprecation"}) javax.servlet.http.HttpSessionContext getSessionContext(); Enumeration getAttributeNames(); @SuppressWarnings({"deprecation"}) String[] getValueNames(); void removeAttribute(final String name); @SuppressWarnings({"deprecation"}) void removeValue(final String name); void invalidate(); boolean isNew(); }### Answer: @Test public void testGetAttribute() throws Exception { MockSession mockSession = new MockSession(Thread.currentThread().getContextClassLoader()); PluginHttpSessionWrapper sessionWrapper = new PluginHttpSessionWrapper(mockSession); sessionWrapper.getAttribute("foo"); ClassLoader pluginClassLoader = new ClassLoader() { }; ClassLoaderStack.push(pluginClassLoader); try { sessionWrapper.getAttribute("foo"); assertSame(pluginClassLoader, Thread.currentThread().getContextClassLoader()); } finally { ClassLoaderStack.pop(); } }
### Question: ResourceTemplateWebPanel extends AbstractWebPanel { public String getHtml(Map<String, Object> context) { try { final StringWriter sink = new StringWriter(); getRenderer().render(resourceFilename, plugin, context, sink); return sink.toString(); } catch (Exception e) { final String message = String.format("Error rendering WebPanel (%s): %s", resourceFilename, e.getMessage()); logger.warn(message, e); return message; } } ResourceTemplateWebPanel(PluginAccessor pluginAccessor); void setResourceFilename(String resourceFilename); String getHtml(Map<String, Object> context); }### Answer: @Test public void testGetHtml() { final PluginAccessor accessorMock = mock(PluginAccessor.class); when(accessorMock.getEnabledModulesByClass(WebPanelRenderer.class)).thenReturn(Collections.<WebPanelRenderer>emptyList()); final Plugin plugin = mock(Plugin.class); when(plugin.getClassLoader()).thenReturn(this.getClass().getClassLoader()); final ResourceTemplateWebPanel resourceTemplateWebPanel = new ResourceTemplateWebPanel(accessorMock); resourceTemplateWebPanel.setPlugin(plugin); resourceTemplateWebPanel.setResourceType("static"); resourceTemplateWebPanel.setResourceFilename("ResourceTemplateWebPanelTest.txt"); assertTrue(resourceTemplateWebPanel.getHtml(Collections.<String, Object>emptyMap()) .contains("This file is used as web panel contents in unit tests.")); }
### Question: EmbeddedTemplateWebPanel extends AbstractWebPanel { public String getHtml(Map<String, Object> context) { try { return getRenderer().renderFragment(templateBody, plugin, context); } catch (RendererException e) { final String message = String.format("Error rendering WebPanel: %s\n" + "Template contents: %s", e.getMessage(), templateBody); logger.warn(message, e); return message; } } EmbeddedTemplateWebPanel(PluginAccessor pluginAccessor); void setTemplateBody(String templateBody); String getHtml(Map<String, Object> context); }### Answer: @Test public void testGetHtml() { final PluginAccessor accessorMock = mock(PluginAccessor.class); when(accessorMock.getEnabledModulesByClass(WebPanelRenderer.class)).thenReturn(Collections.<WebPanelRenderer>emptyList()); final EmbeddedTemplateWebPanel embeddedTemplateWebPanel = new EmbeddedTemplateWebPanel(accessorMock); embeddedTemplateWebPanel.setResourceType("static"); embeddedTemplateWebPanel.setTemplateBody("body"); assertEquals("body", embeddedTemplateWebPanel.getHtml(Collections.<String, Object>emptyMap())); }
### Question: DefaultWebItemModuleDescriptor extends AbstractWebFragmentModuleDescriptor implements WebItemModuleDescriptor { public String getStyleClass() { return styleClass; } DefaultWebItemModuleDescriptor(final WebInterfaceManager webInterfaceManager); DefaultWebItemModuleDescriptor(); @Override void init(final Plugin plugin, final Element element); String getSection(); WebLink getLink(); WebIcon getIcon(); String getStyleClass(); @Override void enabled(); @Override Void getModule(); }### Answer: @Test public void testGetStyleClass() throws DocumentException, PluginParseException { final String className = "testClass"; final String styleClass = "<styleClass>" + className + "</styleClass>"; final Element element = createElement(styleClass); descriptor.init(plugin, element); assertEquals(className, descriptor.getStyleClass()); }
### Question: MaeraPlugins { public void start() throws PluginParseException { pluginManager.init(); if (hotDeployer != null && !hotDeployer.isRunning()) { hotDeployer.start(); } } MaeraPlugins(PluginsConfiguration config); void start(); void stop(); OsgiContainerManager getOsgiContainerManager(); PluginEventManager getPluginEventManager(); PluginController getPluginController(); PluginAccessor getPluginAccessor(); static final String TEMP_DIRECTORY_SUFFIX; }### Answer: @Test public void testStart() throws Exception { new PluginJarBuilder().addPluginInformation("mykey", "mykey", "1.0").build(pluginDir); final PluginsConfiguration config = pluginsConfiguration() .pluginDirectory(pluginDir) .packageScannerConfiguration( new PackageScannerConfigurationBuilder() .packagesToInclude("org.apache.*", "org.maera.*", "org.dom4j*") .packagesVersions(Collections.singletonMap("org.apache.commons.logging", "1.1.1")) .build()) .build(); plugins = new MaeraPlugins(config); plugins.start(); assertEquals(1, plugins.getPluginAccessor().getPlugins().size()); }
### Question: SimpleContentTypeResolver implements ContentTypeResolver { public String getContentType(final String requestUrl) { final String extension = requestUrl.substring(requestUrl.lastIndexOf('.')); return mimeTypes.get(extension); } SimpleContentTypeResolver(); String getContentType(final String requestUrl); }### Answer: @Test public void testGetContentTypeOfCssUrlReturnsTextCss() { assertEquals("text/css", resolver.getContentType(CSS_URL)); } @Test public void testGetContentTypeOfJsUrlReturnsApplicationXJavaScript() { assertEquals("application/x-javascript", resolver.getContentType(JS_URL)); }
### Question: ParameterUtils { public static String getBaseUrl(UrlMode urlMode) { String port = System.getProperty("http.port", "8080"); String baseUrl = System.getProperty("baseurl", "http: if (urlMode == UrlMode.ABSOLUTE) { return baseUrl; } return URI.create(baseUrl).getPath(); } static String getBaseUrl(UrlMode urlMode); }### Answer: @Test public void testBaseUrlWithAbsoluteUrlMode() { assertEquals(BASE_URL, ParameterUtils.getBaseUrl(UrlMode.ABSOLUTE)); } @Test public void testBaseUrlWithAutoUrlMode() { assertEquals(CONTEXT_PATH, ParameterUtils.getBaseUrl(UrlMode.AUTO)); } @Test public void testBaseUrlWithRelativeUrlMode() { assertEquals(CONTEXT_PATH, ParameterUtils.getBaseUrl(UrlMode.RELATIVE)); }
### Question: FelixContainer extends DefaultContainer { public void setCacheDirectory(File cacheDirectory) { this.cacheDirectory = cacheDirectory; } FelixContainer(); File getCacheDirectory(); void setCacheDirectory(File cacheDirectory); List<BundleActivator> getExtraActivators(); void setExtraActivators(List<BundleActivator> extraActivators); }### Answer: @Test public void testDefault() throws Exception { DefaultHostActivator activator = new DefaultHostActivator(); activator.setInitialBundlesLocation(new FileSystemResource(System.getProperty("seedBundlesZip"))); activator.setInitialBundlesExtractionDirectory(new FileSystemResource(System.getProperty("seedBundlesDir") + "/unzipped")); FelixContainer container = new FelixContainer(); Map<String,String> extras = new HashMap<String,String>(); extras.put("org.slf4j", "1.5.6"); extras.put("org.apache.commons.logging", "1.1.1"); container.setExtraSystemPackages(extras); container.setHostActivator(activator); container.setCacheDirectory(new FileSystemResource(System.getProperty("project.build.directory")).getFile()); container.init(); container.start(); container.stop(); container.destroy(); }
### Question: BundleClassLoaderAccessor { public static ClassLoader getClassLoader(final Bundle bundle, final AlternativeResourceLoader alternativeResourceLoader) { return new BundleClassLoader(bundle, alternativeResourceLoader); } static ClassLoader getClassLoader(final Bundle bundle, final AlternativeResourceLoader alternativeResourceLoader); static Class<T> loadClass(final Bundle bundle, final String name); }### Answer: @Test public void testGetResource() throws IOException { Bundle bundle = mock(Bundle.class); when(bundle.getResource("foo.txt")).thenReturn(getClass().getClassLoader().getResource("foo.txt")); URL url = BundleClassLoaderAccessor.getClassLoader(bundle, null).getResource("foo.txt"); assertNotNull(url); } @Test public void testGetResourceAsStream() throws IOException { Bundle bundle = mock(Bundle.class); when(bundle.getResource("foo.txt")).thenReturn(getClass().getClassLoader().getResource("foo.txt")); InputStream in = BundleClassLoaderAccessor.getClassLoader(bundle, null).getResourceAsStream("foo.txt"); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); assertTrue(out.toByteArray().length > 0); } @Test public void testGetResources() throws IOException { Bundle bundle = mock(Bundle.class); when(bundle.getResources("foo.txt")).thenReturn(getClass().getClassLoader().getResources("foo.txt")); Enumeration<URL> e = BundleClassLoaderAccessor.getClassLoader(bundle, null).getResources("foo.txt"); assertNotNull(e); assertTrue(e.hasMoreElements()); } @Test public void testGetResourcesIfNull() throws IOException { Bundle bundle = mock(Bundle.class); when(bundle.getResources("foo.txt")).thenReturn(null); Enumeration<URL> e = BundleClassLoaderAccessor.getClassLoader(bundle, null).getResources("foo.txt"); assertNotNull(e); assertFalse(e.hasMoreElements()); }
### Question: OsgiHeaderUtil { public static String findReferredPackages(List<HostComponentRegistration> registrations) throws IOException { return findReferredPackages(registrations, Collections.<String, String>emptyMap()); } static String findReferredPackages(List<HostComponentRegistration> registrations); static String findReferredPackages(List<HostComponentRegistration> registrations, Map<String, String> packageVersions); static Map<String, Map<String, String>> parseHeader(String header); static String buildHeader(String key, Map<String, String> attrs); static String getPluginKey(Bundle bundle); static String getPluginKey(Manifest mf); }### Answer: @Test public void testFindReferredPackages() throws IOException { String foundPackages = OsgiHeaderUtil.findReferredPackages(new ArrayList<HostComponentRegistration>() {{ add(new StubHostComponentRegistration(OsgiHeaderUtil.class)); }}); assertTrue(foundPackages.contains(HostComponentRegistration.class.getPackage().getName())); } @Test public void testFindReferredPackagesWithVersion() throws IOException { String foundPackages = OsgiHeaderUtil.findReferredPackages(new ArrayList<HostComponentRegistration>() {{ add(new StubHostComponentRegistration(OsgiHeaderUtil.class)); }}, Collections.singletonMap(HostComponentRegistration.class.getPackage().getName(), "1.0")); assertTrue(foundPackages.contains(HostComponentRegistration.class.getPackage().getName() + ";version=1.0")); }
### Question: OsgiHeaderUtil { public static String getPluginKey(Bundle bundle) { return getPluginKey( bundle.getSymbolicName(), bundle.getHeaders().get(OsgiPlugin.MAERA_PLUGIN_KEY), bundle.getHeaders().get(Constants.BUNDLE_VERSION) ); } static String findReferredPackages(List<HostComponentRegistration> registrations); static String findReferredPackages(List<HostComponentRegistration> registrations, Map<String, String> packageVersions); static Map<String, Map<String, String>> parseHeader(String header); static String buildHeader(String key, Map<String, String> attrs); static String getPluginKey(Bundle bundle); static String getPluginKey(Manifest mf); }### Answer: @Test public void testGetPluginKeyBundle() { Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(Constants.BUNDLE_VERSION, "1.0"); headers.put(Constants.BUNDLE_SYMBOLICNAME, "foo"); Bundle bundle = mock(Bundle.class); when(bundle.getSymbolicName()).thenReturn("foo"); when(bundle.getHeaders()).thenReturn(headers); assertEquals("foo-1.0", OsgiHeaderUtil.getPluginKey(bundle)); headers.put(OsgiPlugin.MAERA_PLUGIN_KEY, "bar"); assertEquals("bar", OsgiHeaderUtil.getPluginKey(bundle)); } @Test public void testGetPluginKeyManifest() { Manifest mf = new Manifest(); mf.getMainAttributes().putValue(Constants.BUNDLE_VERSION, "1.0"); mf.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, "foo"); assertEquals("foo-1.0", OsgiHeaderUtil.getPluginKey(mf)); mf.getMainAttributes().putValue(OsgiPlugin.MAERA_PLUGIN_KEY, "bar"); assertEquals("bar", OsgiHeaderUtil.getPluginKey(mf)); }
### Question: OsgiPluginInstalledHelper implements OsgiPluginHelper { public <T> T autowire(final Class<T> clazz, final AutowireCapablePlugin.AutowireStrategy autowireStrategy) throws IllegalPluginStateException { assertSpringContextAvailable(); return containerAccessor.createBean(clazz); } OsgiPluginInstalledHelper(final Bundle bundle, final PackageAdmin packageAdmin); Bundle getBundle(); Class<T> loadClass(final String clazz, final Class<?> callingClass); URL getResource(final String name); InputStream getResourceAsStream(final String name); ClassLoader getClassLoader(); Bundle install(); void onEnable(final ServiceTracker... serviceTrackers); void onDisable(); void onUninstall(); T autowire(final Class<T> clazz, final AutowireCapablePlugin.AutowireStrategy autowireStrategy); void autowire(final Object instance, final AutowireCapablePlugin.AutowireStrategy autowireStrategy); Set<String> getRequiredPlugins(); void setPluginContainer(final Object container); ContainerAccessor getContainerAccessor(); }### Answer: @Test public void testAutowireNoSpringButThereShouldBe() { Object obj = new Object(); try { helper.autowire(obj, AutowireCapablePlugin.AutowireStrategy.AUTOWIRE_AUTODETECT); fail("Should throw exception"); } catch (RuntimeException ignored) { } }
### Question: OsgiPluginInstalledHelper implements OsgiPluginHelper { public void onDisable() throws OsgiContainerException { final ServiceTracker[] serviceTrackers = this.serviceTrackers; if (serviceTrackers != null) { for (final ServiceTracker svc : serviceTrackers) { svc.close(); } this.serviceTrackers = null; } setPluginContainer(null); } OsgiPluginInstalledHelper(final Bundle bundle, final PackageAdmin packageAdmin); Bundle getBundle(); Class<T> loadClass(final String clazz, final Class<?> callingClass); URL getResource(final String name); InputStream getResourceAsStream(final String name); ClassLoader getClassLoader(); Bundle install(); void onEnable(final ServiceTracker... serviceTrackers); void onDisable(); void onUninstall(); T autowire(final Class<T> clazz, final AutowireCapablePlugin.AutowireStrategy autowireStrategy); void autowire(final Object instance, final AutowireCapablePlugin.AutowireStrategy autowireStrategy); Set<String> getRequiredPlugins(); void setPluginContainer(final Object container); ContainerAccessor getContainerAccessor(); }### Answer: @Test public void testOnDisableWithoutEnabling() { helper.onDisable(); }
### Question: OsgiPluginXmlDescriptorParser extends XmlDescriptorParser { @Override protected ModuleDescriptor<?> createModuleDescriptor(final Plugin plugin, final Element element, final ModuleDescriptorFactory moduleDescriptorFactory) throws PluginParseException { final ModuleDescriptor<?> descriptor = super.createModuleDescriptor(plugin, element, moduleDescriptorFactory); final String key = (descriptor != null ? descriptor.getKey() : element.attributeValue("key")); ((OsgiPlugin) plugin).addModuleDescriptorElement(key, element); return descriptor; } OsgiPluginXmlDescriptorParser(final InputStream source, final String... applicationKeys); }### Answer: @Test public void testCreateModuleDescriptor() throws PluginParseException, IllegalAccessException, ClassNotFoundException, InstantiationException { OsgiPluginXmlDescriptorParser parser = new OsgiPluginXmlDescriptorParser(new ByteArrayInputStream("<foo/>".getBytes())); ModuleDescriptor desc = mock(ModuleDescriptor.class); when(desc.getKey()).thenReturn("foo"); ModuleDescriptorFactory factory = mock(ModuleDescriptorFactory.class); when(factory.getModuleDescriptor("foo")).thenReturn(desc); OsgiPlugin plugin = mock(OsgiPlugin.class); Element fooElement = new DefaultElement("foo"); fooElement.addAttribute("key", "bob"); assertNotNull(parser.createModuleDescriptor(plugin, fooElement, factory)); verify(plugin).addModuleDescriptorElement("foo", fooElement); }
### Question: AddBundleOverridesStage implements TransformStage { public void execute(TransformContext context) throws PluginTransformationException { Element pluginInfo = context.getDescriptorDocument().getRootElement().element("plugin-info"); if (pluginInfo != null) { Element instructionRoot = pluginInfo.element("bundle-instructions"); if (instructionRoot != null) { List<Element> instructionsElement = instructionRoot.elements(); for (Element instructionElement : instructionsElement) { String name = instructionElement.getName(); String value = instructionElement.getTextTrim(); context.getBndInstructions().put(name, value); } } } } void execute(TransformContext context); }### Answer: @Test public void testTransform() throws Exception { final File plugin = new PluginJarBuilder("plugin").addFormattedResource("maera-plugin.xml", "<maera-plugin name='Test Bundle instruction plugin 2' key='test.plugin'>", " <plugin-info>", " <version>1.0</version>", " <bundle-instructions>", " <Export-Package>!*.internal.*,*</Export-Package>", " </bundle-instructions>", " </plugin-info>", "</maera-plugin>").build(); final AddBundleOverridesStage stage = new AddBundleOverridesStage(); OsgiContainerManager osgiContainerManager = mock(OsgiContainerManager.class); when(osgiContainerManager.getRegisteredServices()).thenReturn(new ServiceReference[0]); final TransformContext context = new TransformContext(Collections.<HostComponentRegistration>emptyList(), SystemExports.NONE, new JarPluginArtifact(plugin), null, PluginAccessor.Descriptor.FILENAME, osgiContainerManager); stage.execute(context); assertEquals("!*.internal.*,*", context.getBndInstructions().get("Export-Package")); }
### Question: SystemExports { public String getFullExport(String pkg) { if (exports.containsKey(pkg)) { Map<String, String> attrs = new HashMap<String, String>(exports.get(pkg)); if (attrs.containsKey("version")) { final String version = attrs.get("version"); attrs.put("version", "[" + version + "," + version + "]"); } return OsgiHeaderUtil.buildHeader(pkg, attrs); } return pkg; } SystemExports(String exportsLine); String getFullExport(String pkg); boolean isExported(String pkg); static final SystemExports NONE; }### Answer: @Test public void testExportPackageWithVersion() { SystemExports exports = new SystemExports("foo.bar;version=\"4.0\""); assertEquals("foo.bar;version=\"[4.0,4.0]\"", exports.getFullExport("foo.bar")); assertEquals("foo.baz", exports.getFullExport("foo.baz")); }
### Question: DefaultPluginTransformer implements PluginTransformer { static String generateCacheName(File file) { int dotPos = file.getName().lastIndexOf('.'); if (dotPos > 0 && file.getName().length() - 1 > dotPos) { return file.getName().substring(0, dotPos) + "_" + file.lastModified() + file.getName().substring(dotPos); } else { return file.getName() + "_" + file.lastModified(); } } DefaultPluginTransformer(OsgiPersistentCache cache, SystemExports systemExports, Set<String> applicationKeys, String pluginDescriptorPath, OsgiContainerManager osgiContainerManager); DefaultPluginTransformer(OsgiPersistentCache cache, SystemExports systemExports, Set<String> applicationKeys, String pluginDescriptorPath, OsgiContainerManager osgiContainerManager, List<TransformStage> stages); File transform(File pluginJar, List<HostComponentRegistration> regs); File transform(PluginArtifact pluginArtifact, List<HostComponentRegistration> regs); }### Answer: @Test public void testGenerateCacheName() throws IOException { File tmp = File.createTempFile("asdf", ".jar", tmpDir); assertTrue(DefaultPluginTransformer.generateCacheName(tmp).endsWith(".jar")); tmp = File.createTempFile("asdf", "asdf", tmpDir); assertTrue(DefaultPluginTransformer.generateCacheName(tmp).endsWith(String.valueOf(tmp.lastModified()))); tmp = File.createTempFile("asdf", "asdf.", tmpDir); assertTrue(DefaultPluginTransformer.generateCacheName(tmp).endsWith(String.valueOf(tmp.lastModified()))); tmp = File.createTempFile("asdf", "asdf.s", tmpDir); assertTrue(DefaultPluginTransformer.generateCacheName(tmp).endsWith(String.valueOf(".s"))); }
### Question: DefaultPluginTransformer implements PluginTransformer { public File transform(File pluginJar, List<HostComponentRegistration> regs) throws PluginTransformationException { return transform(new JarPluginArtifact(pluginJar), regs); } DefaultPluginTransformer(OsgiPersistentCache cache, SystemExports systemExports, Set<String> applicationKeys, String pluginDescriptorPath, OsgiContainerManager osgiContainerManager); DefaultPluginTransformer(OsgiPersistentCache cache, SystemExports systemExports, Set<String> applicationKeys, String pluginDescriptorPath, OsgiContainerManager osgiContainerManager, List<TransformStage> stages); File transform(File pluginJar, List<HostComponentRegistration> regs); File transform(PluginArtifact pluginArtifact, List<HostComponentRegistration> regs); }### Answer: @Test public void testTransform() throws Exception { final File file = new PluginJarBuilder() .addFormattedJava("my.Foo", "package my;", "public class Foo {", " org.maera.plugin.osgi.factory.transform.Fooable bar;", "}") .addPluginInformation("foo", "foo", "1.1") .build(); final File copy = transformer.transform(new JarPluginArtifact(file), new ArrayList<HostComponentRegistration>() { { add(new StubHostComponentRegistration(Fooable.class)); } }); assertNotNull(copy); assertTrue(copy.getName().contains(String.valueOf(file.lastModified()))); assertTrue(copy.getName().endsWith(".jar")); assertEquals(tmpDir.getAbsolutePath(), copy.getParentFile().getParentFile().getAbsolutePath()); final JarFile jar = new JarFile(copy); final Attributes attrs = jar.getManifest().getMainAttributes(); assertEquals("1.1", attrs.getValue(Constants.BUNDLE_VERSION)); assertNotNull(jar.getEntry("META-INF/spring/maera-plugins-host-components.xml")); }
### Question: OsgiPluginFactory implements PluginFactory { public String canCreate(PluginArtifact pluginArtifact) throws PluginParseException { Validate.notNull(pluginArtifact, "The plugin artifact is required"); String pluginKey = null; InputStream descriptorStream = null; try { descriptorStream = pluginArtifact.getResourceAsStream(pluginDescriptorFileName); if (descriptorStream != null) { final DescriptorParser descriptorParser = descriptorParserFactory.getInstance(descriptorStream, applicationKeys.toArray(new String[applicationKeys.size()])); if (descriptorParser.getPluginsVersion() == 2) { pluginKey = descriptorParser.getKey(); } } } finally { IOUtils.closeQuietly(descriptorStream); } return pluginKey; } OsgiPluginFactory(String pluginDescriptorFileName, String applicationKey, OsgiPersistentCache persistentCache, OsgiContainerManager osgi, PluginEventManager pluginEventManager); OsgiPluginFactory(String pluginDescriptorFileName, Set<String> applicationKeys, OsgiPersistentCache persistentCache, OsgiContainerManager osgi, PluginEventManager pluginEventManager); String canCreate(PluginArtifact pluginArtifact); Plugin create(DeploymentUnit deploymentUnit, ModuleDescriptorFactory moduleDescriptorFactory); Plugin create(PluginArtifact pluginArtifact, ModuleDescriptorFactory moduleDescriptorFactory); }### Answer: @Test public void testCanLoadNoXml() throws PluginParseException, IOException { final File plugin = new PluginJarBuilder("loadwithxml").build(); final String key = factory.canCreate(new JarPluginArtifact(plugin)); assertNull(key); } @Test public void testCanLoadWithXml() throws PluginParseException, IOException { final File plugin = new PluginJarBuilder("loadwithxml").addPluginInformation("foo.bar", "", "1.0").build(); final String key = factory.canCreate(new JarPluginArtifact(plugin)); assertEquals("foo.bar", key); }
### Question: ComponentModuleDescriptor extends AbstractModuleDescriptor { @Override protected void loadClass(Plugin plugin, String clazz) throws PluginParseException { } ComponentModuleDescriptor(); @Override Object getModule(); String getModuleClassName(); }### Answer: @Test public void testEnableDoesNotLoadClass() throws ClassNotFoundException { ComponentModuleDescriptor desc = new ComponentModuleDescriptor(); Element e = DocumentHelper.createElement("foo"); e.addAttribute("key", "foo"); e.addAttribute("class", Foo.class.getName()); Plugin plugin = mock(Plugin.class); when(plugin.<Foo>loadClass((String) anyObject(), (Class<?>) anyObject())).thenReturn(Foo.class); desc.init(plugin, e); Foo.called = false; desc.enabled(); assertFalse(Foo.called); }
### Question: UnloadableStaticPluginFactory implements PluginFactory { public String canCreate(PluginArtifact pluginArtifact) throws PluginParseException { Validate.notNull(pluginArtifact, "The plugin artifact is required"); InputStream descriptorStream = null; try { descriptorStream = pluginArtifact.getResourceAsStream(pluginDescriptorFileName); if (descriptorStream != null) { final DescriptorParser descriptorParser = descriptorParserFactory.getInstance(descriptorStream); if (descriptorParser.getPluginsVersion() == 1) { return descriptorParser.getKey(); } } } finally { IOUtils.closeQuietly(descriptorStream); } return null; } UnloadableStaticPluginFactory(String pluginDescriptorFileName); String canCreate(PluginArtifact pluginArtifact); Plugin create(DeploymentUnit deploymentUnit, ModuleDescriptorFactory moduleDescriptorFactory); Plugin create(PluginArtifact pluginArtifact, ModuleDescriptorFactory moduleDescriptorFactory); }### Answer: @Test public void testCanCreate() { UnloadableStaticPluginFactory factory = new UnloadableStaticPluginFactory("foo.xml"); PluginArtifact artifact = mock(PluginArtifact.class); when(artifact.getResourceAsStream("foo.xml")).thenReturn(new ByteArrayInputStream( "<maera-plugin key=\"foo\" />".getBytes() )); assertEquals("foo", factory.canCreate(artifact)); } @Test public void testCanCreateWithNoDescriptor() { UnloadableStaticPluginFactory factory = new UnloadableStaticPluginFactory("foo.xml"); PluginArtifact artifact = mock(PluginArtifact.class); when(artifact.getResourceAsStream("foo.xml")).thenReturn(null); assertEquals(null, factory.canCreate(artifact)); } @Test public void testCanCreateWithOsgi() { UnloadableStaticPluginFactory factory = new UnloadableStaticPluginFactory("foo.xml"); PluginArtifact artifact = mock(PluginArtifact.class); when(artifact.getResourceAsStream("foo.xml")).thenReturn(new ByteArrayInputStream( "<maera-plugin key=\"foo\" plugins-version=\"2\"/>".getBytes() )); assertEquals(null, factory.canCreate(artifact)); }
### Question: UnloadableStaticPluginFactory implements PluginFactory { public Plugin create(DeploymentUnit deploymentUnit, ModuleDescriptorFactory moduleDescriptorFactory) throws PluginParseException { Validate.notNull(deploymentUnit, "The deployment unit is required"); return create(new JarPluginArtifact(deploymentUnit.getPath()), moduleDescriptorFactory); } UnloadableStaticPluginFactory(String pluginDescriptorFileName); String canCreate(PluginArtifact pluginArtifact); Plugin create(DeploymentUnit deploymentUnit, ModuleDescriptorFactory moduleDescriptorFactory); Plugin create(PluginArtifact pluginArtifact, ModuleDescriptorFactory moduleDescriptorFactory); }### Answer: @Test public void testCreate() { UnloadableStaticPluginFactory factory = new UnloadableStaticPluginFactory("foo.xml"); PluginArtifact artifact = mock(PluginArtifact.class); when(artifact.getResourceAsStream("foo.xml")).thenReturn(new ByteArrayInputStream( "<maera-plugin key=\"foo\" />".getBytes() )); when(artifact.toString()).thenReturn("plugin.jar"); UnloadablePlugin plugin = (UnloadablePlugin) factory.create(artifact, new DefaultModuleDescriptorFactory(new DefaultHostContainer())); assertNotNull(plugin); assertEquals("foo", plugin.getKey()); assertTrue(plugin.getErrorText().contains("plugin.jar")); } @Test public void testCreateWithNoKey() { UnloadableStaticPluginFactory factory = new UnloadableStaticPluginFactory("foo.xml"); PluginArtifact artifact = mock(PluginArtifact.class); when(artifact.getResourceAsStream("foo.xml")).thenReturn(new ByteArrayInputStream( "<maera-plugin />".getBytes() )); when(artifact.toString()).thenReturn("plugin.jar"); UnloadablePlugin plugin = (UnloadablePlugin) factory.create(artifact, new DefaultModuleDescriptorFactory(new DefaultHostContainer())); assertNotNull(plugin); assertEquals(null, plugin.getKey()); assertTrue(plugin.getErrorText().contains("plugin.jar")); }
### Question: DefaultComponentRegistrar implements ComponentRegistrar { public InstanceBuilder register(final Class<?>... mainInterfaces) { final Registration reg = new Registration(mainInterfaces); registry.add(reg); return new DefaultInstanceBuilder(reg); } InstanceBuilder register(final Class<?>... mainInterfaces); List<ServiceRegistration> writeRegistry(final BundleContext ctx); List<HostComponentRegistration> getRegistry(); }### Answer: @Test public void testRegister() { DefaultComponentRegistrar registrar = new DefaultComponentRegistrar(); Class[] ifs = new Class[]{Serializable.class}; registrar.register(ifs).forInstance("Foo").withName("foo").withProperty("jim", "bar"); HostComponentRegistration reg = registrar.getRegistry().get(0); assertNotNull(reg); assertEquals("Foo", reg.getInstance()); assertEquals(Serializable.class.getName(), reg.getMainInterfaces()[0]); assertEquals("foo", reg.getProperties().get(DefaultPropertyBuilder.BEAN_NAME)); assertEquals("bar", reg.getProperties().get("jim")); } @Test public void testRegisterOnlyInterfaces() { DefaultComponentRegistrar registrar = new DefaultComponentRegistrar(); Class[] ifs = new Class[]{Object.class}; try { registrar.register(ifs).forInstance("Foo").withName("foo").withProperty("jim", "bar"); fail("Should have failed"); } catch (IllegalArgumentException ignored) { } }
### Question: ExportsBuilder { void constructAutoExports(StringBuilder sb, Collection<ExportPackage> packageExports) { for (ExportPackage pkg : packageExports) { sb.append(pkg.getPackageName()); if (pkg.getVersion() != null) { try { Version.parseVersion(pkg.getVersion()); sb.append(";version=").append(pkg.getVersion()); } catch (IllegalArgumentException ex) { log.info("Unable to parse version: " + pkg.getVersion()); } } sb.append(","); } } String getExports(List<HostComponentRegistration> regs, PackageScannerConfiguration packageScannerConfig); @SuppressWarnings({"UnusedDeclaration"}) String determineExports(List<HostComponentRegistration> regs, PackageScannerConfiguration packageScannerConfig, File cacheDir); }### Answer: @Test public void testConstructAutoExports() { List<ExportPackage> exports = new ArrayList<ExportPackage>(); exports.add(new ExportPackage("foo.bar", "1.0", new File("/whatever/foobar-1.0.jar"))); exports.add(new ExportPackage("foo.bar", "1.0-asdf-asdf", new File("/whatever/foobar-1.0-asdf-asdf.jar"))); StringBuilder sb = new StringBuilder(); builder.constructAutoExports(sb, exports); assertEquals("foo.bar;version=1.0,foo.bar,", sb.toString()); }
### Question: ExportsBuilder { void constructJdkExports(StringBuilder sb, String packageListPath) { InputStream in = null; try { in = ClassLoaderUtils.getResourceAsStream(packageListPath, ExportsBuilder.class); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { if (line.charAt(0) != '#') { if (sb.length() > 0) sb.append(','); sb.append(line); } } } } catch (IOException e) { IOUtils.closeQuietly(in); } } String getExports(List<HostComponentRegistration> regs, PackageScannerConfiguration packageScannerConfig); @SuppressWarnings({"UnusedDeclaration"}) String determineExports(List<HostComponentRegistration> regs, PackageScannerConfiguration packageScannerConfig, File cacheDir); }### Answer: @Test public void testConstructJdkExports() { StringBuilder sb = new StringBuilder(); builder.constructJdkExports(sb, "jdk-packages.test.txt"); assertEquals("foo.bar,foo.baz", sb.toString()); sb = new StringBuilder(); builder.constructJdkExports(sb, ExportsBuilder.JDK_PACKAGES_PATH); assertTrue(sb.toString().contains("org.xml.sax")); }
### Question: ExportsBuilder { @SuppressWarnings({"UnusedDeclaration"}) public String determineExports(List<HostComponentRegistration> regs, PackageScannerConfiguration packageScannerConfig, File cacheDir) { return determineExports(regs, packageScannerConfig); } String getExports(List<HostComponentRegistration> regs, PackageScannerConfiguration packageScannerConfig); @SuppressWarnings({"UnusedDeclaration"}) String determineExports(List<HostComponentRegistration> regs, PackageScannerConfiguration packageScannerConfig, File cacheDir); }### Answer: @Test public void testConstructJdkExportsWithJdk5And6() { String jdkVersion = System.getProperty("java.specification.version"); try { System.setProperty("java.specification.version", "1.5"); String exports = builder.determineExports(new ArrayList<HostComponentRegistration>(), new DefaultPackageScannerConfiguration()); assertFalse(exports.contains("javax.script")); System.setProperty("java.specification.version", "1.6"); exports = builder.determineExports(new ArrayList<HostComponentRegistration>(), new DefaultPackageScannerConfiguration()); assertTrue(exports.contains("javax.script")); } finally { System.setProperty("java.specification.version", jdkVersion); } } @Test public void testDetermineExports() { DefaultPackageScannerConfiguration config = new DefaultPackageScannerConfiguration("0.0"); String exports = builder.determineExports(new ArrayList<HostComponentRegistration>(), config); assertFalse(exports.contains(",,")); } @Test public void testDetermineExportsIncludeServiceInterfaces() { List<HostComponentRegistration> regs = new ArrayList<HostComponentRegistration>() {{ add(new MockRegistration(new HashAttributeSet(), AttributeSet.class)); add(new MockRegistration(new DefaultTableModel(), TableModel.class)); }}; String imports = builder.determineExports(regs, new DefaultPackageScannerConfiguration()); assertNotNull(imports); System.out.println(imports.replace(',', '\n')); assertTrue(imports.contains(AttributeSet.class.getPackage().getName())); assertTrue(imports.contains("javax.swing.event")); }
### Question: OsgiHeaderUtils { public static String getPluginKey(Bundle bundle) { return getPluginKey( bundle.getSymbolicName(), bundle.getHeaders().get(MAERA_PLUGIN_KEY), bundle.getHeaders().get(Constants.BUNDLE_VERSION) ); } static Map<String, Map<String, String>> parseHeader(String header); static String buildHeader(String key, Map<String, String> attrs); static String getPluginKey(Bundle bundle); static String getPluginKey(Manifest mf); static final String JDK_PACKAGES_PATH; static final String JDK6_PACKAGES_PATH; static final String MAERA_PLUGIN_KEY; }### Answer: @Test public void testGetPluginKeyBundle() { Dictionary<String, String> headers = new Hashtable<String, String>(); headers.put(Constants.BUNDLE_VERSION, "1.0"); headers.put(Constants.BUNDLE_SYMBOLICNAME, "foo"); Bundle bundle = mock(Bundle.class); when(bundle.getSymbolicName()).thenReturn("foo"); when(bundle.getHeaders()).thenReturn(headers); assertEquals("foo-1.0", OsgiHeaderUtils.getPluginKey(bundle)); headers.put(OsgiHeaderUtils.MAERA_PLUGIN_KEY, "bar"); assertEquals("bar", OsgiHeaderUtils.getPluginKey(bundle)); } @Test public void testGetPluginKeyManifest() { Manifest mf = new Manifest(); mf.getMainAttributes().putValue(Constants.BUNDLE_VERSION, "1.0"); mf.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, "foo"); assertEquals("foo-1.0", OsgiHeaderUtils.getPluginKey(mf)); mf.getMainAttributes().putValue(OsgiHeaderUtils.MAERA_PLUGIN_KEY, "bar"); assertEquals("bar", OsgiHeaderUtils.getPluginKey(mf)); }
### Question: DefaultWebResourceFilter implements WebResourceFilter { public boolean matches(String resourceName) { return JavascriptWebResource.FORMATTER.matches(resourceName) || CssWebResource.FORMATTER.matches(resourceName); } boolean matches(String resourceName); static final DefaultWebResourceFilter INSTANCE; }### Answer: @Test public void testMatches() { assertTrue(DefaultWebResourceFilter.INSTANCE.matches("foo.css")); assertTrue(DefaultWebResourceFilter.INSTANCE.matches("foo.js")); assertFalse(DefaultWebResourceFilter.INSTANCE.matches("foo.html")); }
### Question: BatchPluginResource implements DownloadableResource, PluginResource, BatchResource { public String getUrl() { final StringBuilder sb = new StringBuilder(); sb.append(URL_PREFIX).append(PATH_SEPARATOR).append(moduleCompleteKey).append(PATH_SEPARATOR).append(resourceName); addParamsToUrl(sb, params); return sb.toString(); } BatchPluginResource(final String moduleCompleteKey, final String type, final Map<String, String> params); private BatchPluginResource(final String resourceName, final String moduleCompleteKey, final String type, final Map<String, String> params); boolean isEmpty(); void add(final DownloadableResource resource); boolean isResourceModified(final HttpServletRequest request, final HttpServletResponse response); void serveResource(final HttpServletRequest request, final HttpServletResponse response); void streamResource(final OutputStream out); String getContentType(); static BatchPluginResource parse(String url, final Map<String, String> queryParams); static boolean matches(final String url); String getUrl(); String getResourceName(); Map<String, String> getParams(); String getVersion(WebResourceIntegration integration); String getModuleCompleteKey(); boolean isCacheSupported(); String getType(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testGetUrl() { final BatchPluginResource resource = new BatchPluginResource("test.plugin:webresources", "js", Collections.<String, String>emptyMap()); assertEquals("/download/batch/test.plugin:webresources/test.plugin:webresources.js", resource.getUrl()); } @Test public void testGetUrlWithParams() { final Map<String, String> params = new TreeMap<String, String>(); params.put("foo", "bar"); params.put("moo", "cow"); final BatchPluginResource resource = new BatchPluginResource("test.plugin:webresources", "js", params); assertEquals("/download/batch/test.plugin:webresources/test.plugin:webresources.js?foo=bar&moo=cow", resource.getUrl()); }
### Question: BatchPluginResource implements DownloadableResource, PluginResource, BatchResource { public boolean isCacheSupported() { return !"false".equals(params.get("cache")); } BatchPluginResource(final String moduleCompleteKey, final String type, final Map<String, String> params); private BatchPluginResource(final String resourceName, final String moduleCompleteKey, final String type, final Map<String, String> params); boolean isEmpty(); void add(final DownloadableResource resource); boolean isResourceModified(final HttpServletRequest request, final HttpServletResponse response); void serveResource(final HttpServletRequest request, final HttpServletResponse response); void streamResource(final OutputStream out); String getContentType(); static BatchPluginResource parse(String url, final Map<String, String> queryParams); static boolean matches(final String url); String getUrl(); String getResourceName(); Map<String, String> getParams(); String getVersion(WebResourceIntegration integration); String getModuleCompleteKey(); boolean isCacheSupported(); String getType(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testIsCacheSupported() throws Exception { final BatchPluginResource resource = BatchPluginResource.parse("/download/batch/test.plugin:webresources/test.plugin:webresources.css", Collections.<String, String>emptyMap()); assertTrue(resource.isCacheSupported()); final Map<String, String> queryParams = new TreeMap<String, String>(); queryParams.put("cache", "false"); final BatchPluginResource resource2 = BatchPluginResource.parse("/download/batch/test.plugin:webresources/test.plugin:webresources.css", queryParams); assertFalse(resource2.isCacheSupported()); }
### Question: WebResourceTransformation { boolean matches(ResourceLocation location) { String loc = location.getLocation(); if (loc == null || "".equals(loc.trim())) { loc = location.getName(); } return loc.endsWith(extension); } WebResourceTransformation(Element element); }### Answer: @Test public void testMatches() throws DocumentException { WebResourceTransformation trans = new WebResourceTransformation(DocumentHelper.parseText( "<transformation extension=\"js\">\n" + "<transformer key=\"foo\" />\n" + "</transformation>").getRootElement()); ResourceLocation loc = mock(ResourceLocation.class); when(loc.getName()).thenReturn("foo.js"); assertTrue(trans.matches(loc)); } @Test public void testNotMatches() throws DocumentException { WebResourceTransformation trans = new WebResourceTransformation(DocumentHelper.parseText( "<transformation extension=\"js\">\n" + "<transformer key=\"foo\" />\n" + "</transformation>").getRootElement()); ResourceLocation loc = mock(ResourceLocation.class); when(loc.getName()).thenReturn("foo.cs"); assertFalse(trans.matches(loc)); }
### Question: JavascriptWebResource extends AbstractWebResourceFormatter { public String formatResource(String url, Map<String, String> params) { StringBuffer buffer = new StringBuffer("<script type=\"text/javascript\" "); buffer.append("src=\"").append(url).append("\" "); buffer.append(StringUtils.join(getParametersAsAttributes(params).iterator(), " ")); buffer.append("></script>\n"); return buffer.toString(); } boolean matches(String name); String formatResource(String url, Map<String, String> params); }### Answer: @Test public void testFormatResource() { final String url = "/confluence/download/resources/confluence.web.resources:ajs/atlassian.js"; assertEquals("<script type=\"text/javascript\" src=\"" + url + "\" ></script>\n", javascriptWebResource.formatResource(url, new HashMap<String, String>())); }
### Question: JavascriptWebResource extends AbstractWebResourceFormatter { public boolean matches(String name) { return name != null && name.endsWith(JAVA_SCRIPT_EXTENSION); } boolean matches(String name); String formatResource(String url, Map<String, String> params); }### Answer: @Test public void testMatches() { assertTrue(javascriptWebResource.matches("blah.js")); assertFalse(javascriptWebResource.matches("blah.css")); }
### Question: CssWebResource extends AbstractWebResourceFormatter { public boolean matches(String name) { return name != null && name.endsWith(CSS_EXTENSION); } boolean matches(String name); String formatResource(String url, Map<String, String> params); }### Answer: @Test public void testMatches() { assertTrue(cssWebResource.matches("blah.css")); assertFalse(cssWebResource.matches("blah.js")); }
### Question: SuperBatchPluginResource implements DownloadableResource, BatchResource, PluginResource { protected static String getType(String path) { int index = path.lastIndexOf('.'); if (index > -1 && index < path.length()) return path.substring(index + 1); return ""; } SuperBatchPluginResource(String type, Map<String, String> params); protected SuperBatchPluginResource(String resourceName, String type, Map<String, String> params); static boolean matches(String path); static SuperBatchPluginResource createBatchFor(PluginResource pluginResource); static SuperBatchPluginResource parse(String path, Map<String, String> params); boolean isResourceModified(HttpServletRequest request, HttpServletResponse response); void serveResource(HttpServletRequest request, HttpServletResponse response); void streamResource(OutputStream out); String getContentType(); void add(DownloadableResource downloadableResource); boolean isEmpty(); String getUrl(); Map<String, String> getParams(); String getVersion(WebResourceIntegration integration); String getType(); boolean isCacheSupported(); String getResourceName(); String getModuleCompleteKey(); @Override String toString(); }### Answer: @Test public void testGetType() { assertEquals("css", SuperBatchPluginResource.getType("/foo.css")); assertEquals("js", SuperBatchPluginResource.getType("/superbatch/js/foo.js")); assertEquals("", SuperBatchPluginResource.getType("/superbatch/js/foo.")); assertEquals("", SuperBatchPluginResource.getType("/superbatch/js/foo")); }
### Question: SuperBatchPluginResource implements DownloadableResource, BatchResource, PluginResource { public static boolean matches(String path) { String type = getType(path); return path.indexOf(URL_PREFIX) != -1 && endsWith(path, DEFAULT_RESOURCE_NAME_PREFIX, ".", type); } SuperBatchPluginResource(String type, Map<String, String> params); protected SuperBatchPluginResource(String resourceName, String type, Map<String, String> params); static boolean matches(String path); static SuperBatchPluginResource createBatchFor(PluginResource pluginResource); static SuperBatchPluginResource parse(String path, Map<String, String> params); boolean isResourceModified(HttpServletRequest request, HttpServletResponse response); void serveResource(HttpServletRequest request, HttpServletResponse response); void streamResource(OutputStream out); String getContentType(); void add(DownloadableResource downloadableResource); boolean isEmpty(); String getUrl(); Map<String, String> getParams(); String getVersion(WebResourceIntegration integration); String getType(); boolean isCacheSupported(); String getResourceName(); String getModuleCompleteKey(); @Override String toString(); }### Answer: @Test public void testNotSuperbatches() { assertFalse("wrong path", SuperBatchPluginResource.matches("/download/superbitch/css/batch.css")); assertFalse("wrong path", SuperBatchPluginResource.matches("/download/superbatch/css/images/foo.png")); } @Test public void testParseWithContextPath() { assertTrue(SuperBatchPluginResource.matches("/confluence/download/superbatch/css/batch.css")); }
### Question: ResourceDownloadUtils { public static void addCachingHeaders(final HttpServletResponse httpServletResponse, final String... cacheControls) { if (!Boolean.getBoolean("maera.disable.caches")) { httpServletResponse.setDateHeader("Expires", System.currentTimeMillis() + TEN_YEARS); httpServletResponse.setHeader("Cache-Control", "max-age=" + TEN_YEARS); for (final String cacheControl : cacheControls) { httpServletResponse.addHeader("Cache-Control", cacheControl); } } } @Deprecated static void serveFileImpl(final HttpServletResponse httpServletResponse, final InputStream in); static void addCachingHeaders(final HttpServletResponse httpServletResponse, final String... cacheControls); @Deprecated static void addCachingHeaders(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse); static void addPublicCachingHeaders(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse); static void addPrivateCachingHeaders(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse); }### Answer: @Test public void testAddCachingHeadersWithCacheControls() { Mock mockResponse = new Mock(HttpServletResponse.class); mockResponse.expect("setDateHeader", C.ANY_ARGS); mockResponse.expect("setHeader", C.args(C.eq(CACHE_CONTROL), C.eq("max-age=" + TEN_YEARS))); mockResponse.expect("addHeader", C.args(C.eq(CACHE_CONTROL), C.eq("private"))); mockResponse.expect("addHeader", C.args(C.eq(CACHE_CONTROL), C.eq("foo"))); ResourceDownloadUtils.addCachingHeaders((HttpServletResponse) mockResponse.proxy(), "private", "foo"); }
### Question: ResourceDownloadUtils { public static void addPublicCachingHeaders(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) { addCachingHeaders(httpServletResponse, "public"); } @Deprecated static void serveFileImpl(final HttpServletResponse httpServletResponse, final InputStream in); static void addCachingHeaders(final HttpServletResponse httpServletResponse, final String... cacheControls); @Deprecated static void addCachingHeaders(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse); static void addPublicCachingHeaders(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse); static void addPrivateCachingHeaders(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse); }### Answer: @Test public void testAddPublicCachingHeaders() { Mock mockRequest = new Mock(HttpServletRequest.class); Mock mockResponse = new Mock(HttpServletResponse.class); mockResponse.expect("setDateHeader", C.ANY_ARGS); mockResponse.expect("setHeader", C.args(C.eq(CACHE_CONTROL), C.eq("max-age=" + TEN_YEARS))); mockResponse.expect("addHeader", C.args(C.eq(CACHE_CONTROL), C.eq("public"))); ResourceDownloadUtils.addPublicCachingHeaders((HttpServletRequest) mockRequest.proxy(), (HttpServletResponse) mockResponse.proxy()); }
### Question: PluginResourceDownload implements DownloadStrategy { public boolean matches(String urlPath) { return pluginResourceLocator.matches(urlPath); } PluginResourceDownload(); PluginResourceDownload(PluginResourceLocator pluginResourceLocator, ContentTypeResolver contentTypeResolver, String characterEncoding); boolean matches(String urlPath); void serveFile(HttpServletRequest request, HttpServletResponse response); void setCharacterEncoding(String characterEncoding); void setContentTypeResolver(ContentTypeResolver contentTypeResolver); void setPluginResourceLocator(PluginResourceLocator pluginResourceLocator); }### Answer: @Test public void testMatches() { mockPluginResourceLocator.expectAndReturn("matches", C.args(C.eq(SINGLE_RESOURCE)), true); assertTrue(pluginResourceDownload.matches(SINGLE_RESOURCE)); mockPluginResourceLocator.expectAndReturn("matches", C.args(C.eq(BATCH_RESOURCE)), true); assertTrue(pluginResourceDownload.matches(BATCH_RESOURCE)); }
### Question: ResourceUrlParser { public boolean matches(String resourceUrl) { return resourceUrl.indexOf(AbstractFileServerServlet.SERVLET_PATH + "/" + strategyPrefix) != -1; } ResourceUrlParser(String strategyPrefix); PluginResource parse(String resourceUrl); boolean matches(String resourceUrl); }### Answer: @Test public void testMatches() { assertTrue(parser.matches("download/resources/test.plugin.key:module/test.css")); assertTrue(parser.matches("/download/resources/test.plugin.key:module/test.css")); }
### Question: ResourceUrlParser { public PluginResource parse(String resourceUrl) { if (!matches(resourceUrl)) return null; int indexOfStrategyPrefix = resourceUrl.indexOf(strategyPrefix); String libraryAndResource = resourceUrl.substring(indexOfStrategyPrefix + strategyPrefix.length() + 1); String[] parts = libraryAndResource.split("/", 2); if (parts.length != 2) return null; return new PluginResource(parts[0], parts[1]); } ResourceUrlParser(String strategyPrefix); PluginResource parse(String resourceUrl); boolean matches(String resourceUrl); }### Answer: @Test public void testParseResourceWithSimpleName() { PluginResource resource = parser.parse("/download/resources/test.plugin.key:module/mydownload.jpg"); assertEquals("test.plugin.key:module", resource.getModuleCompleteKey()); assertEquals("mydownload.jpg", resource.getResourceName()); } @Test public void testParseResourceWithSlashesInName() { PluginResource resource = parser.parse("/download/resources/test.plugin.key:module/path/to/mydownload.jpg"); assertEquals("test.plugin.key:module", resource.getModuleCompleteKey()); assertEquals("path/to/mydownload.jpg", resource.getResourceName()); }
### Question: PluggableDownloadStrategy implements DownloadStrategy { @PluginEventListener public void pluginModuleDisabled(final PluginModuleDisabledEvent event) { final ModuleDescriptor<?> module = event.getModule(); if (!(module instanceof DownloadStrategyModuleDescriptor)) { return; } unregister(module.getCompleteKey()); } PluggableDownloadStrategy(final PluginEventManager pluginEventManager); boolean matches(final String urlPath); void serveFile(final HttpServletRequest request, final HttpServletResponse response); void register(final String key, final DownloadStrategy strategy); void unregister(final String key); @PluginEventListener void pluginModuleEnabled(final PluginModuleEnabledEvent event); @PluginEventListener void pluginModuleDisabled(final PluginModuleDisabledEvent event); }### Answer: @Test public void testPluginModuleDisabled() throws Exception { ModuleDescriptor module = new DownloadStrategyModuleDescriptor(getDefaultModuleClassFactory()) { public String getCompleteKey() { return "jungle.plugin:lion-strategy"; } public DownloadStrategy getModule() { return new StubDownloadStrategy("/lion", "ROAR!"); } }; strategy.pluginModuleEnabled(new PluginModuleEnabledEvent(module)); assertTrue(strategy.matches("/lion/something")); strategy.pluginModuleDisabled(new PluginModuleDisabledEvent(module)); assertFalse(strategy.matches("/lion/something")); }
### Question: PluggableDownloadStrategy implements DownloadStrategy { @PluginEventListener public void pluginModuleEnabled(final PluginModuleEnabledEvent event) { final ModuleDescriptor<?> module = event.getModule(); if (!(module instanceof DownloadStrategyModuleDescriptor)) { return; } register(module.getCompleteKey(), (DownloadStrategy) module.getModule()); } PluggableDownloadStrategy(final PluginEventManager pluginEventManager); boolean matches(final String urlPath); void serveFile(final HttpServletRequest request, final HttpServletResponse response); void register(final String key, final DownloadStrategy strategy); void unregister(final String key); @PluginEventListener void pluginModuleEnabled(final PluginModuleEnabledEvent event); @PluginEventListener void pluginModuleDisabled(final PluginModuleDisabledEvent event); }### Answer: @Test public void testPluginModuleEnabled() throws Exception { ModuleDescriptor module = new DownloadStrategyModuleDescriptor(getDefaultModuleClassFactory()) { public String getCompleteKey() { return "jungle.plugin:lion-strategy"; } public DownloadStrategy getModule() { return new StubDownloadStrategy("/lion", "ROAR!"); } }; strategy.pluginModuleEnabled(new PluginModuleEnabledEvent(module)); assertTrue(strategy.matches("/lion/something")); StringWriter result = new StringWriter(); Mock mockResponse = new Mock(HttpServletResponse.class); mockResponse.expectAndReturn("getWriter", new PrintWriter(result)); Mock mockRequest = new Mock(HttpServletRequest.class); mockRequest.expectAndReturn("getRequestURI", "/lion/something"); strategy.serveFile((HttpServletRequest) mockRequest.proxy(), (HttpServletResponse) mockResponse.proxy()); assertEquals("ROAR!" + IOUtils.LINE_SEPARATOR, result.toString()); }
### Question: PluggableDownloadStrategy implements DownloadStrategy { public void register(final String key, final DownloadStrategy strategy) { if (strategies.containsKey(key)) { log.warn("Replacing existing download strategy with module key: " + key); } strategies.put(key, strategy); } PluggableDownloadStrategy(final PluginEventManager pluginEventManager); boolean matches(final String urlPath); void serveFile(final HttpServletRequest request, final HttpServletResponse response); void register(final String key, final DownloadStrategy strategy); void unregister(final String key); @PluginEventListener void pluginModuleEnabled(final PluginModuleEnabledEvent event); @PluginEventListener void pluginModuleDisabled(final PluginModuleDisabledEvent event); }### Answer: @Test public void testRegister() throws Exception { strategy.register("monkey.key", new StubDownloadStrategy("/monkey", "Bananas")); assertTrue(strategy.matches("/monkey/something")); StringWriter result = new StringWriter(); Mock mockResponse = new Mock(HttpServletResponse.class); mockResponse.expectAndReturn("getWriter", new PrintWriter(result)); Mock mockRequest = new Mock(HttpServletRequest.class); mockRequest.expectAndReturn("getRequestURI", "/monkey/something"); strategy.serveFile((HttpServletRequest) mockRequest.proxy(), (HttpServletResponse) mockResponse.proxy()); assertEquals("Bananas" + IOUtils.LINE_SEPARATOR, result.toString()); }