target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void normalizeResourcePathSlash02() { assertEquals("Normalized", "/", Path.normalizeResourcePath(" /")); }
|
public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
@Test public void normalizeResourcePathSlash03() { assertEquals("Normalized", "/", Path.normalizeResourcePath(" / ")); }
|
public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
@Test public void normalizeResourcePathSlash04() { assertEquals("Normalized", "/", Path.normalizeResourcePath("/ ")); }
|
public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
@SuppressWarnings("deprecation") @Test public void testParseWebXml() throws Exception { WebAppParser parser = new WebAppParser(null); File file = new File("src/test/resources/web.xml"); assertTrue(file.exists()); WebAppType parseWebXml = parser.parseWebXml(file.toURL()); assertNotNull(parseWebXml); List<JAXBElement<?>> list = parseWebXml.getModuleNameOrDescriptionAndDisplayName(); for (JAXBElement<?> jaxbElement : list) { Object value = jaxbElement.getValue(); if (value instanceof SessionConfigType) { SessionConfigType sessionConfig = (SessionConfigType) value; BigInteger value2 = sessionConfig.getSessionTimeout().getValue(); assertThat(value2.intValue(), is(30)); } } }
|
protected WebAppType parseWebXml(URL url) { try { XMLReader reader = XMLReaderFactory.createXMLReader(); NamespaceFilter inFilter = new NamespaceFilter("http: inFilter.setParent(reader); JAXBContext context = JAXBContext.newInstance(WebAppType.class); Unmarshaller unmarshaller = context.createUnmarshaller(); SAXSource source = new SAXSource(inFilter, new InputSource(url.openStream())); return unmarshaller.unmarshal(source, WebAppType.class).getValue(); } catch (JAXBException | IOException | SAXException exc) { LOG.error("error parsing web.xml", exc); } return null; }
|
WebAppParser { protected WebAppType parseWebXml(URL url) { try { XMLReader reader = XMLReaderFactory.createXMLReader(); NamespaceFilter inFilter = new NamespaceFilter("http: inFilter.setParent(reader); JAXBContext context = JAXBContext.newInstance(WebAppType.class); Unmarshaller unmarshaller = context.createUnmarshaller(); SAXSource source = new SAXSource(inFilter, new InputSource(url.openStream())); return unmarshaller.unmarshal(source, WebAppType.class).getValue(); } catch (JAXBException | IOException | SAXException exc) { LOG.error("error parsing web.xml", exc); } return null; } }
|
WebAppParser { protected WebAppType parseWebXml(URL url) { try { XMLReader reader = XMLReaderFactory.createXMLReader(); NamespaceFilter inFilter = new NamespaceFilter("http: inFilter.setParent(reader); JAXBContext context = JAXBContext.newInstance(WebAppType.class); Unmarshaller unmarshaller = context.createUnmarshaller(); SAXSource source = new SAXSource(inFilter, new InputSource(url.openStream())); return unmarshaller.unmarshal(source, WebAppType.class).getValue(); } catch (JAXBException | IOException | SAXException exc) { LOG.error("error parsing web.xml", exc); } return null; } WebAppParser(ServiceTracker<PackageAdmin, PackageAdmin> packageAdmin); }
|
WebAppParser { protected WebAppType parseWebXml(URL url) { try { XMLReader reader = XMLReaderFactory.createXMLReader(); NamespaceFilter inFilter = new NamespaceFilter("http: inFilter.setParent(reader); JAXBContext context = JAXBContext.newInstance(WebAppType.class); Unmarshaller unmarshaller = context.createUnmarshaller(); SAXSource source = new SAXSource(inFilter, new InputSource(url.openStream())); return unmarshaller.unmarshal(source, WebAppType.class).getValue(); } catch (JAXBException | IOException | SAXException exc) { LOG.error("error parsing web.xml", exc); } return null; } WebAppParser(ServiceTracker<PackageAdmin, PackageAdmin> packageAdmin); void parse(final Bundle bundle, WebApp webApp); static Boolean canSeeClass(Bundle bundle, Class<?> clazz); }
|
WebAppParser { protected WebAppType parseWebXml(URL url) { try { XMLReader reader = XMLReaderFactory.createXMLReader(); NamespaceFilter inFilter = new NamespaceFilter("http: inFilter.setParent(reader); JAXBContext context = JAXBContext.newInstance(WebAppType.class); Unmarshaller unmarshaller = context.createUnmarshaller(); SAXSource source = new SAXSource(inFilter, new InputSource(url.openStream())); return unmarshaller.unmarshal(source, WebAppType.class).getValue(); } catch (JAXBException | IOException | SAXException exc) { LOG.error("error parsing web.xml", exc); } return null; } WebAppParser(ServiceTracker<PackageAdmin, PackageAdmin> packageAdmin); void parse(final Bundle bundle, WebApp webApp); static Boolean canSeeClass(Bundle bundle, Class<?> clazz); }
|
@Test public void testExtractNameVersionType() { String[] nameVersion; nameVersion = DeployerUtils.extractNameVersionType("test-1.0.0.war"); assertEquals("test", nameVersion[0]); assertEquals("1.0.0", nameVersion[1]); nameVersion = DeployerUtils.extractNameVersionType("test.war"); assertEquals("test", nameVersion[0]); assertEquals("0.0.0", nameVersion[1]); }
|
public static String[] extractNameVersionType(String url) { Matcher m = ARTIFACT_MATCHER.matcher(url); if (!m.matches()) { return new String[]{url.split("\\.")[0], DEFAULT_VERSION}; } else { StringBuilder v = new StringBuilder(); String d1 = m.group(1); String d2 = m.group(2); String d3 = m.group(3); String d4 = m.group(4); String d5 = m.group(5); String d6 = m.group(6); if (d2 != null) { v.append(d2); if (d3 != null) { v.append('.'); v.append(d3); if (d4 != null) { v.append('.'); v.append(d4); if (d5 != null) { v.append("."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0.0."); cleanupModifier(v, d5); } } return new String[]{d1, v.toString(), d6}; } }
|
DeployerUtils { public static String[] extractNameVersionType(String url) { Matcher m = ARTIFACT_MATCHER.matcher(url); if (!m.matches()) { return new String[]{url.split("\\.")[0], DEFAULT_VERSION}; } else { StringBuilder v = new StringBuilder(); String d1 = m.group(1); String d2 = m.group(2); String d3 = m.group(3); String d4 = m.group(4); String d5 = m.group(5); String d6 = m.group(6); if (d2 != null) { v.append(d2); if (d3 != null) { v.append('.'); v.append(d3); if (d4 != null) { v.append('.'); v.append(d4); if (d5 != null) { v.append("."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0.0."); cleanupModifier(v, d5); } } return new String[]{d1, v.toString(), d6}; } } }
|
DeployerUtils { public static String[] extractNameVersionType(String url) { Matcher m = ARTIFACT_MATCHER.matcher(url); if (!m.matches()) { return new String[]{url.split("\\.")[0], DEFAULT_VERSION}; } else { StringBuilder v = new StringBuilder(); String d1 = m.group(1); String d2 = m.group(2); String d3 = m.group(3); String d4 = m.group(4); String d5 = m.group(5); String d6 = m.group(6); if (d2 != null) { v.append(d2); if (d3 != null) { v.append('.'); v.append(d3); if (d4 != null) { v.append('.'); v.append(d4); if (d5 != null) { v.append("."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0.0."); cleanupModifier(v, d5); } } return new String[]{d1, v.toString(), d6}; } } private DeployerUtils(); }
|
DeployerUtils { public static String[] extractNameVersionType(String url) { Matcher m = ARTIFACT_MATCHER.matcher(url); if (!m.matches()) { return new String[]{url.split("\\.")[0], DEFAULT_VERSION}; } else { StringBuilder v = new StringBuilder(); String d1 = m.group(1); String d2 = m.group(2); String d3 = m.group(3); String d4 = m.group(4); String d5 = m.group(5); String d6 = m.group(6); if (d2 != null) { v.append(d2); if (d3 != null) { v.append('.'); v.append(d3); if (d4 != null) { v.append('.'); v.append(d4); if (d5 != null) { v.append("."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0.0."); cleanupModifier(v, d5); } } return new String[]{d1, v.toString(), d6}; } } private DeployerUtils(); static String[] extractNameVersionType(String url); }
|
DeployerUtils { public static String[] extractNameVersionType(String url) { Matcher m = ARTIFACT_MATCHER.matcher(url); if (!m.matches()) { return new String[]{url.split("\\.")[0], DEFAULT_VERSION}; } else { StringBuilder v = new StringBuilder(); String d1 = m.group(1); String d2 = m.group(2); String d3 = m.group(3); String d4 = m.group(4); String d5 = m.group(5); String d6 = m.group(6); if (d2 != null) { v.append(d2); if (d3 != null) { v.append('.'); v.append(d3); if (d4 != null) { v.append('.'); v.append(d4); if (d5 != null) { v.append("."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0.0."); cleanupModifier(v, d5); } } return new String[]{d1, v.toString(), d6}; } } private DeployerUtils(); static String[] extractNameVersionType(String url); }
|
@Test public void checkGetServiceFlow() { replay(bundle, serviceRegistration, httpService); Object result = underTest.getService(bundle, serviceRegistration); assertNotNull("expect not null", result); verify(bundle, serviceRegistration, httpService); }
|
@Override public HttpService getService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration) { LOG.info("Binding bundle: [" + bundle + "] to http service"); return createService(bundle); }
|
HttpServiceFactoryImpl implements
ServiceFactory<HttpService> { @Override public HttpService getService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration) { LOG.info("Binding bundle: [" + bundle + "] to http service"); return createService(bundle); } }
|
HttpServiceFactoryImpl implements
ServiceFactory<HttpService> { @Override public HttpService getService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration) { LOG.info("Binding bundle: [" + bundle + "] to http service"); return createService(bundle); } }
|
HttpServiceFactoryImpl implements
ServiceFactory<HttpService> { @Override public HttpService getService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration) { LOG.info("Binding bundle: [" + bundle + "] to http service"); return createService(bundle); } @Override HttpService getService(final Bundle bundle,
final ServiceRegistration<HttpService> serviceRegistration); @Override void ungetService(final Bundle bundle,
final ServiceRegistration<HttpService> serviceRegistration,
final HttpService httpService); }
|
HttpServiceFactoryImpl implements
ServiceFactory<HttpService> { @Override public HttpService getService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration) { LOG.info("Binding bundle: [" + bundle + "] to http service"); return createService(bundle); } @Override HttpService getService(final Bundle bundle,
final ServiceRegistration<HttpService> serviceRegistration); @Override void ungetService(final Bundle bundle,
final ServiceRegistration<HttpService> serviceRegistration,
final HttpService httpService); }
|
@Test public void checkUngetServiceFlow() { httpService.stop(); replay(bundle, serviceRegistration, httpService); underTest.ungetService(bundle, serviceRegistration, httpService); verify(bundle, serviceRegistration, httpService); }
|
@Override public void ungetService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration, final HttpService httpService) { LOG.info("Unbinding bundle: [" + bundle + "]"); ((StoppableHttpService) httpService).stop(); }
|
HttpServiceFactoryImpl implements
ServiceFactory<HttpService> { @Override public void ungetService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration, final HttpService httpService) { LOG.info("Unbinding bundle: [" + bundle + "]"); ((StoppableHttpService) httpService).stop(); } }
|
HttpServiceFactoryImpl implements
ServiceFactory<HttpService> { @Override public void ungetService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration, final HttpService httpService) { LOG.info("Unbinding bundle: [" + bundle + "]"); ((StoppableHttpService) httpService).stop(); } }
|
HttpServiceFactoryImpl implements
ServiceFactory<HttpService> { @Override public void ungetService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration, final HttpService httpService) { LOG.info("Unbinding bundle: [" + bundle + "]"); ((StoppableHttpService) httpService).stop(); } @Override HttpService getService(final Bundle bundle,
final ServiceRegistration<HttpService> serviceRegistration); @Override void ungetService(final Bundle bundle,
final ServiceRegistration<HttpService> serviceRegistration,
final HttpService httpService); }
|
HttpServiceFactoryImpl implements
ServiceFactory<HttpService> { @Override public void ungetService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration, final HttpService httpService) { LOG.info("Unbinding bundle: [" + bundle + "]"); ((StoppableHttpService) httpService).stop(); } @Override HttpService getService(final Bundle bundle,
final ServiceRegistration<HttpService> serviceRegistration); @Override void ungetService(final Bundle bundle,
final ServiceRegistration<HttpService> serviceRegistration,
final HttpService httpService); }
|
@Test public void handleSecurity() throws IOException { assertTrue(contextUnderTest.handleSecurity(null, null)); }
|
@Override public boolean handleSecurity(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException { return true; }
|
DefaultHttpContext implements WebContainerContext { @Override public boolean handleSecurity(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException { return true; } }
|
DefaultHttpContext implements WebContainerContext { @Override public boolean handleSecurity(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException { return true; } DefaultHttpContext(final Bundle bundle, String contextID); }
|
DefaultHttpContext implements WebContainerContext { @Override public boolean handleSecurity(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException { return true; } DefaultHttpContext(final Bundle bundle, String contextID); @Override boolean handleSecurity(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse); @Override URL getResource(final String name); @Override String getMimeType(String name); @Override Set<String> getResourcePaths(final String name); @Override String getContextId(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
|
DefaultHttpContext implements WebContainerContext { @Override public boolean handleSecurity(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException { return true; } DefaultHttpContext(final Bundle bundle, String contextID); @Override boolean handleSecurity(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse); @Override URL getResource(final String name); @Override String getMimeType(String name); @Override Set<String> getResourcePaths(final String name); @Override String getContextId(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
|
@SuppressWarnings("unchecked") @Test public void getOrCreateContextDoesNotRegisterMultipleServletContextsForSameContextModelMultiThreaded() throws Exception { final JettyServerWrapper jettyServerWrapperUnderTest = new JettyServerWrapper( serverModelMock, new QueuedThreadPool()); try { jettyServerWrapperUnderTest.start(); final CountDownLatch countDownLatch = new CountDownLatch(1); final Runnable getOrCreateContextRunnable = new Runnable() { @Override public void run() { try { countDownLatch.await(); HttpServiceContext context = jettyServerWrapperUnderTest .getOrCreateContext(contextModelMock); context.start(); } catch (final InterruptedException ex) { } catch (final Exception ex) { exceptionInRunnable = ex; } } }; final ExecutorService executor = Executors .newFixedThreadPool(NUMBER_OF_CONCURRENT_EXECUTIONS); for (int i = 0; i < NUMBER_OF_CONCURRENT_EXECUTIONS; i++) { executor.execute(getOrCreateContextRunnable); } countDownLatch.countDown(); executor.shutdown(); final boolean terminated = executor.awaitTermination(10, TimeUnit.SECONDS); if (exceptionInRunnable != null) { try { throw exceptionInRunnable; } finally { exceptionInRunnable = null; } } assertTrue("could not shutdown the executor within the timeout", terminated); verify(bundleContextMock, times(1)).registerService( same(ServletContext.class), any(ServletContext.class), any(Dictionary.class)); } finally { jettyServerWrapperUnderTest.stop(); } }
|
HttpServiceContext getOrCreateContext(final Model model) { return getOrCreateContext(model.getContextModel()); }
|
JettyServerWrapper extends Server { HttpServiceContext getOrCreateContext(final Model model) { return getOrCreateContext(model.getContextModel()); } }
|
JettyServerWrapper extends Server { HttpServiceContext getOrCreateContext(final Model model) { return getOrCreateContext(model.getContextModel()); } JettyServerWrapper(ServerModel serverModel, ThreadPool threadPool); }
|
JettyServerWrapper extends Server { HttpServiceContext getOrCreateContext(final Model model) { return getOrCreateContext(model.getContextModel()); } JettyServerWrapper(ServerModel serverModel, ThreadPool threadPool); HandlerCollection getRootHandlerCollection(); void configureContext(final Map<String, Object> attributes, final Integer timeout, final String cookie,
final String domain, final String path, final String url, final Boolean cookieHttpOnly,
final Boolean sessionCookieSecure, final String workerName, final Boolean lazy, final String directory,
Integer maxAge, final Boolean showStacks); void setServerConfigDir(File serverConfigDir); File getServerConfigDir(); URL getServerConfigURL(); void setServerConfigURL(URL serverConfigURL); String getDefaultAuthMethod(); void setDefaultAuthMethod(String defaultAuthMethod); String getDefaultRealmName(); void setDefaultRealmName(String defaultRealmName); }
|
JettyServerWrapper extends Server { HttpServiceContext getOrCreateContext(final Model model) { return getOrCreateContext(model.getContextModel()); } JettyServerWrapper(ServerModel serverModel, ThreadPool threadPool); HandlerCollection getRootHandlerCollection(); void configureContext(final Map<String, Object> attributes, final Integer timeout, final String cookie,
final String domain, final String path, final String url, final Boolean cookieHttpOnly,
final Boolean sessionCookieSecure, final String workerName, final Boolean lazy, final String directory,
Integer maxAge, final Boolean showStacks); void setServerConfigDir(File serverConfigDir); File getServerConfigDir(); URL getServerConfigURL(); void setServerConfigURL(URL serverConfigURL); String getDefaultAuthMethod(); void setDefaultAuthMethod(String defaultAuthMethod); String getDefaultRealmName(); void setDefaultRealmName(String defaultRealmName); }
|
@Test public void getMimeType() { assertEquals(null, contextUnderTest.getMimeType(null)); }
|
@Override public String getMimeType(String name) { return null; }
|
DefaultHttpContext implements WebContainerContext { @Override public String getMimeType(String name) { return null; } }
|
DefaultHttpContext implements WebContainerContext { @Override public String getMimeType(String name) { return null; } DefaultHttpContext(final Bundle bundle, String contextID); }
|
DefaultHttpContext implements WebContainerContext { @Override public String getMimeType(String name) { return null; } DefaultHttpContext(final Bundle bundle, String contextID); @Override boolean handleSecurity(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse); @Override URL getResource(final String name); @Override String getMimeType(String name); @Override Set<String> getResourcePaths(final String name); @Override String getContextId(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
|
DefaultHttpContext implements WebContainerContext { @Override public String getMimeType(String name) { return null; } DefaultHttpContext(final Bundle bundle, String contextID); @Override boolean handleSecurity(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse); @Override URL getResource(final String name); @Override String getMimeType(String name); @Override Set<String> getResourcePaths(final String name); @Override String getContextId(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
|
@Test public void getResource() throws MalformedURLException { URL url = new URL("file: expect(bundle.getResource("test")).andReturn(url); replay(bundle); contextUnderTest.getResource("test"); verify(bundle); }
|
@Override public URL getResource(final String name) { final String normalizedname = Path.normalizeResourcePath(name); LOG.debug("Searching bundle [" + bundle + "] for resource [" + normalizedname + "]"); return bundle.getResource(normalizedname); }
|
DefaultHttpContext implements WebContainerContext { @Override public URL getResource(final String name) { final String normalizedname = Path.normalizeResourcePath(name); LOG.debug("Searching bundle [" + bundle + "] for resource [" + normalizedname + "]"); return bundle.getResource(normalizedname); } }
|
DefaultHttpContext implements WebContainerContext { @Override public URL getResource(final String name) { final String normalizedname = Path.normalizeResourcePath(name); LOG.debug("Searching bundle [" + bundle + "] for resource [" + normalizedname + "]"); return bundle.getResource(normalizedname); } DefaultHttpContext(final Bundle bundle, String contextID); }
|
DefaultHttpContext implements WebContainerContext { @Override public URL getResource(final String name) { final String normalizedname = Path.normalizeResourcePath(name); LOG.debug("Searching bundle [" + bundle + "] for resource [" + normalizedname + "]"); return bundle.getResource(normalizedname); } DefaultHttpContext(final Bundle bundle, String contextID); @Override boolean handleSecurity(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse); @Override URL getResource(final String name); @Override String getMimeType(String name); @Override Set<String> getResourcePaths(final String name); @Override String getContextId(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
|
DefaultHttpContext implements WebContainerContext { @Override public URL getResource(final String name) { final String normalizedname = Path.normalizeResourcePath(name); LOG.debug("Searching bundle [" + bundle + "] for resource [" + normalizedname + "]"); return bundle.getResource(normalizedname); } DefaultHttpContext(final Bundle bundle, String contextID); @Override boolean handleSecurity(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse); @Override URL getResource(final String name); @Override String getMimeType(String name); @Override Set<String> getResourcePaths(final String name); @Override String getContextId(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
|
@Test public void replaceSlashesWithNull() { assertEquals("Replaced", null, Path.replaceSlashes(null)); }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
@Test public void replaceSlashes01() { assertEquals("Replaced", "/foo/bar/", Path.replaceSlashes("/foo/bar/")); }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
@Test public void replaceSlashes02() { assertEquals("Replaced", "/", Path.replaceSlashes("/")); }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
@Test public void replaceSlashes03() { assertEquals("Replaced", "/", Path.replaceSlashes(" }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
@Test public void replaceSlashes04() { assertEquals("Replaced", "/foo/bar", Path.replaceSlashes(" }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
@Test public void replaceSlashes05() { assertEquals("Replaced", "foo/bar/", Path.replaceSlashes("foo/bar }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
@Test public void replaceSlashes06() { assertEquals("Replaced", "foo/bar", Path.replaceSlashes("foo }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
@Test public void replaceSlashes07() { assertEquals("Replaced", "/foo/bar/car/", Path.replaceSlashes("/foo }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
@Test public void registrationAndUnregistrationOfTwoServletsThereShouldBeNoContexts() throws Exception { JettyServerImpl server = new JettyServerImpl(serverModelMock, null); server.start(); try { Bundle testBundle = mock(Bundle.class); ContextModel contextModel = new ContextModel(httpContextMock, testBundle, getClass().getClassLoader(), null); ServletModel servletModel1 = new ServletModel(contextModel, new DefaultServlet(), "/s1", null, null, null); ServletModel servletModel2 = new ServletModel(contextModel, new DefaultServlet(), "/s2", null, null, null); assertNull(server.getServer().getContext(httpContextMock)); server.addServlet(servletModel1); assertNotNull(server.getServer().getContext(httpContextMock)); server.addServlet(servletModel2); assertNotNull(server.getServer().getContext(httpContextMock)); server.removeServlet(servletModel1); assertNotNull(server.getServer().getContext(httpContextMock)); server.removeServlet(servletModel2); assertNull(server.getServer().getContext(httpContextMock)); } finally { server.stop(); } }
|
HttpServiceContext getContext(final HttpContext httpContext) { readLock.lock(); try { ServletContextInfo servletContextInfo = contexts.get(httpContext); if (servletContextInfo != null) { return servletContextInfo.getHandler(); } return null; } finally { readLock.unlock(); } }
|
JettyServerWrapper extends Server { HttpServiceContext getContext(final HttpContext httpContext) { readLock.lock(); try { ServletContextInfo servletContextInfo = contexts.get(httpContext); if (servletContextInfo != null) { return servletContextInfo.getHandler(); } return null; } finally { readLock.unlock(); } } }
|
JettyServerWrapper extends Server { HttpServiceContext getContext(final HttpContext httpContext) { readLock.lock(); try { ServletContextInfo servletContextInfo = contexts.get(httpContext); if (servletContextInfo != null) { return servletContextInfo.getHandler(); } return null; } finally { readLock.unlock(); } } JettyServerWrapper(ServerModel serverModel, ThreadPool threadPool); }
|
JettyServerWrapper extends Server { HttpServiceContext getContext(final HttpContext httpContext) { readLock.lock(); try { ServletContextInfo servletContextInfo = contexts.get(httpContext); if (servletContextInfo != null) { return servletContextInfo.getHandler(); } return null; } finally { readLock.unlock(); } } JettyServerWrapper(ServerModel serverModel, ThreadPool threadPool); HandlerCollection getRootHandlerCollection(); void configureContext(final Map<String, Object> attributes, final Integer timeout, final String cookie,
final String domain, final String path, final String url, final Boolean cookieHttpOnly,
final Boolean sessionCookieSecure, final String workerName, final Boolean lazy, final String directory,
Integer maxAge, final Boolean showStacks); void setServerConfigDir(File serverConfigDir); File getServerConfigDir(); URL getServerConfigURL(); void setServerConfigURL(URL serverConfigURL); String getDefaultAuthMethod(); void setDefaultAuthMethod(String defaultAuthMethod); String getDefaultRealmName(); void setDefaultRealmName(String defaultRealmName); }
|
JettyServerWrapper extends Server { HttpServiceContext getContext(final HttpContext httpContext) { readLock.lock(); try { ServletContextInfo servletContextInfo = contexts.get(httpContext); if (servletContextInfo != null) { return servletContextInfo.getHandler(); } return null; } finally { readLock.unlock(); } } JettyServerWrapper(ServerModel serverModel, ThreadPool threadPool); HandlerCollection getRootHandlerCollection(); void configureContext(final Map<String, Object> attributes, final Integer timeout, final String cookie,
final String domain, final String path, final String url, final Boolean cookieHttpOnly,
final Boolean sessionCookieSecure, final String workerName, final Boolean lazy, final String directory,
Integer maxAge, final Boolean showStacks); void setServerConfigDir(File serverConfigDir); File getServerConfigDir(); URL getServerConfigURL(); void setServerConfigURL(URL serverConfigURL); String getDefaultAuthMethod(); void setDefaultAuthMethod(String defaultAuthMethod); String getDefaultRealmName(); void setDefaultRealmName(String defaultRealmName); }
|
@Test public void normalizeResourcePathSlash01() { assertEquals("Normalized", "/", Path.normalizeResourcePath("/")); }
|
public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
@Test public void normalizeResourcePathSlash02() { assertEquals("Normalized", "/", Path.normalizeResourcePath(" /")); }
|
public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
@Test public void normalizeResourcePathSlash03() { assertEquals("Normalized", "/", Path.normalizeResourcePath(" / ")); }
|
public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
@Test public void normalizeResourcePathSlash04() { assertEquals("Normalized", "/", Path.normalizeResourcePath("/ ")); }
|
public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); }
|
@Test public void registerWithNoDispatcherInitParams() { FilterModel fm = new FilterModel(new ContextModel( createMock(WebContainerContext.class), null, getClass() .getClassLoader(), null), createMock(Filter.class), new String[]{"/*"}, null, new Hashtable<>(), false); System.out.println(Arrays.asList(fm.getDispatcher())); }
|
public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); }
|
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } }
|
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } FilterModel(final ContextModel contextModel, final Filter filter,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Filter filter,
final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter,
final boolean asyncSupported); }
|
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } FilterModel(final ContextModel contextModel, final Filter filter,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Filter filter,
final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter,
final boolean asyncSupported); Filter getFilter(); Class<? extends Filter> getFilterClass(); String getName(); String[] getUrlPatterns(); String[] getServletNames(); Map<String, String> getInitParams(); String[] getDispatcher(); boolean isAsyncSupported(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
|
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } FilterModel(final ContextModel contextModel, final Filter filter,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Filter filter,
final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter,
final boolean asyncSupported); Filter getFilter(); Class<? extends Filter> getFilterClass(); String getName(); String[] getUrlPatterns(); String[] getServletNames(); Map<String, String> getInitParams(); String[] getDispatcher(); boolean isAsyncSupported(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
|
@Test public void registerWithCorrectSubsetOfDispatcherInitParams() { FilterModel fm = new FilterModel(new ContextModel( createMock(WebContainerContext.class), null, getClass() .getClassLoader(), null), createMock(Filter.class), new String[]{" private static final long serialVersionUID = 6291128067491953259L; { put(WebContainerConstants.FILTER_MAPPING_DISPATCHER, "REQUEST, FORWARD"); } }, false); System.out.println(Arrays.asList(fm.getDispatcher())); }
|
public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); }
|
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } }
|
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } FilterModel(final ContextModel contextModel, final Filter filter,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Filter filter,
final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter,
final boolean asyncSupported); }
|
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } FilterModel(final ContextModel contextModel, final Filter filter,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Filter filter,
final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter,
final boolean asyncSupported); Filter getFilter(); Class<? extends Filter> getFilterClass(); String getName(); String[] getUrlPatterns(); String[] getServletNames(); Map<String, String> getInitParams(); String[] getDispatcher(); boolean isAsyncSupported(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
|
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } FilterModel(final ContextModel contextModel, final Filter filter,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Filter filter,
final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter,
final boolean asyncSupported); Filter getFilter(); Class<? extends Filter> getFilterClass(); String getName(); String[] getUrlPatterns(); String[] getServletNames(); Map<String, String> getInitParams(); String[] getDispatcher(); boolean isAsyncSupported(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
|
@Test public void registerWithFullComplimentOfDispatcherInitParams() { FilterModel fm = new FilterModel(new ContextModel( createMock(WebContainerContext.class), null, getClass() .getClassLoader(), null), createMock(Filter.class), new String[]{" private static final long serialVersionUID = 4025173284250768044L; { put(WebContainerConstants.FILTER_MAPPING_DISPATCHER, "REQUEST, FORWARD, ERROR , include"); } }, false); System.out.println(Arrays.asList(fm.getDispatcher())); }
|
public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); }
|
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } }
|
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } FilterModel(final ContextModel contextModel, final Filter filter,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Filter filter,
final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter,
final boolean asyncSupported); }
|
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } FilterModel(final ContextModel contextModel, final Filter filter,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Filter filter,
final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter,
final boolean asyncSupported); Filter getFilter(); Class<? extends Filter> getFilterClass(); String getName(); String[] getUrlPatterns(); String[] getServletNames(); Map<String, String> getInitParams(); String[] getDispatcher(); boolean isAsyncSupported(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
|
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } FilterModel(final ContextModel contextModel, final Filter filter,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Filter filter,
final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter,
final boolean asyncSupported); Filter getFilter(); Class<? extends Filter> getFilterClass(); String getName(); String[] getUrlPatterns(); String[] getServletNames(); Map<String, String> getInitParams(); String[] getDispatcher(); boolean isAsyncSupported(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
|
@Test public void replaceSlashesWithNull() { assertEquals("Replaced", null, Path.replaceSlashes(null)); }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
@Test public void replaceSlashes01() { assertEquals("Replaced", "/foo/bar/", Path.replaceSlashes("/foo/bar/")); }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
@Test public void replaceSlashes02() { assertEquals("Replaced", "/", Path.replaceSlashes("/")); }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
@Test public void replaceSlashes03() { assertEquals("Replaced", "/", Path.replaceSlashes(" }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
@Test public void replaceSlashes04() { assertEquals("Replaced", "/foo/bar", Path.replaceSlashes(" }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
@Test public void replaceSlashes05() { assertEquals("Replaced", "foo/bar/", Path.replaceSlashes("foo/bar }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
@Test public void replaceSlashes06() { assertEquals("Replaced", "foo/bar", Path.replaceSlashes("foo }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
@Test public void testCreateDirectoryStructure() { System.out.println("createDirectoryStructure"); String path = System.getProperty("user.home"); String project = "Test"; boolean expResult = true; boolean result = FileTools.createBlankProject(path, project); assertEquals(expResult, result); }
|
public static boolean createBlankProject(String path, String projectName) { boolean result = true; result &= createDirectory(path + File.separator + projectName); result &= createAssetDirectories(path + File.separator + projectName); return result; }
|
FileTools { public static boolean createBlankProject(String path, String projectName) { boolean result = true; result &= createDirectory(path + File.separator + projectName); result &= createAssetDirectories(path + File.separator + projectName); return result; } }
|
FileTools { public static boolean createBlankProject(String path, String projectName) { boolean result = true; result &= createDirectory(path + File.separator + projectName); result &= createAssetDirectories(path + File.separator + projectName); return result; } }
|
FileTools { public static boolean createBlankProject(String path, String projectName) { boolean result = true; result &= createDirectory(path + File.separator + projectName); result &= createAssetDirectories(path + File.separator + projectName); return result; } static String getJreDirectory(); static String getBuildsDirectory(); static String getProjectsDirectory(); static String getExecutionPath(Class clazz); static boolean createBlankProject(String path, String projectName); static Project createProjectFromTemplate(String path, String projectName, String template); static boolean createAssetDirectories(String path); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); static void saveAsset(AbstractAsset asset); }
|
FileTools { public static boolean createBlankProject(String path, String projectName) { boolean result = true; result &= createDirectory(path + File.separator + projectName); result &= createAssetDirectories(path + File.separator + projectName); return result; } static String getJreDirectory(); static String getBuildsDirectory(); static String getProjectsDirectory(); static String getExecutionPath(Class clazz); static boolean createBlankProject(String path, String projectName); static Project createProjectFromTemplate(String path, String projectName, String template); static boolean createAssetDirectories(String path); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); static void saveAsset(AbstractAsset asset); }
|
@Test @Ignore public void testDoChoosePath() { System.out.println("doChoosePath"); File expResult = null; File result = FileTools.doChoosePath(); assertEquals(expResult, result); fail("The test case is a prototype."); }
|
public static File doChoosePath() { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getCurrentDirectory(); } return null; }
|
FileTools { public static File doChoosePath() { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getCurrentDirectory(); } return null; } }
|
FileTools { public static File doChoosePath() { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getCurrentDirectory(); } return null; } }
|
FileTools { public static File doChoosePath() { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getCurrentDirectory(); } return null; } static String getJreDirectory(); static String getBuildsDirectory(); static String getProjectsDirectory(); static String getExecutionPath(Class clazz); static boolean createBlankProject(String path, String projectName); static Project createProjectFromTemplate(String path, String projectName, String template); static boolean createAssetDirectories(String path); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); static void saveAsset(AbstractAsset asset); }
|
FileTools { public static File doChoosePath() { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getCurrentDirectory(); } return null; } static String getJreDirectory(); static String getBuildsDirectory(); static String getProjectsDirectory(); static String getExecutionPath(Class clazz); static boolean createBlankProject(String path, String projectName); static Project createProjectFromTemplate(String path, String projectName, String template); static boolean createAssetDirectories(String path); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); static void saveAsset(AbstractAsset asset); }
|
@Test @Ignore public void testDoChooseFile() { System.out.println("doChooseFile"); String extension = ""; String directory = ""; String type = ""; File expResult = null; File result = FileTools.doChooseFile(extension, directory, type); assertEquals(expResult, result); fail("The test case is a prototype."); }
|
public static File doChooseFile(String extension, String directory, String type) { if (MainWindow.getInstance().getActiveProject() != null) { File projectPath = new File(System.getProperty("project.path") + File.separator + directory); if (projectPath.exists()) { JFileChooser fileChooser = new JFileChooser(new SingleRootFileSystemView(projectPath)); fileChooser.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter(type, extension); fileChooser.setFileFilter(filter); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFile(); } } } return null; }
|
FileTools { public static File doChooseFile(String extension, String directory, String type) { if (MainWindow.getInstance().getActiveProject() != null) { File projectPath = new File(System.getProperty("project.path") + File.separator + directory); if (projectPath.exists()) { JFileChooser fileChooser = new JFileChooser(new SingleRootFileSystemView(projectPath)); fileChooser.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter(type, extension); fileChooser.setFileFilter(filter); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFile(); } } } return null; } }
|
FileTools { public static File doChooseFile(String extension, String directory, String type) { if (MainWindow.getInstance().getActiveProject() != null) { File projectPath = new File(System.getProperty("project.path") + File.separator + directory); if (projectPath.exists()) { JFileChooser fileChooser = new JFileChooser(new SingleRootFileSystemView(projectPath)); fileChooser.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter(type, extension); fileChooser.setFileFilter(filter); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFile(); } } } return null; } }
|
FileTools { public static File doChooseFile(String extension, String directory, String type) { if (MainWindow.getInstance().getActiveProject() != null) { File projectPath = new File(System.getProperty("project.path") + File.separator + directory); if (projectPath.exists()) { JFileChooser fileChooser = new JFileChooser(new SingleRootFileSystemView(projectPath)); fileChooser.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter(type, extension); fileChooser.setFileFilter(filter); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFile(); } } } return null; } static String getJreDirectory(); static String getBuildsDirectory(); static String getProjectsDirectory(); static String getExecutionPath(Class clazz); static boolean createBlankProject(String path, String projectName); static Project createProjectFromTemplate(String path, String projectName, String template); static boolean createAssetDirectories(String path); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); static void saveAsset(AbstractAsset asset); }
|
FileTools { public static File doChooseFile(String extension, String directory, String type) { if (MainWindow.getInstance().getActiveProject() != null) { File projectPath = new File(System.getProperty("project.path") + File.separator + directory); if (projectPath.exists()) { JFileChooser fileChooser = new JFileChooser(new SingleRootFileSystemView(projectPath)); fileChooser.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter(type, extension); fileChooser.setFileFilter(filter); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFile(); } } } return null; } static String getJreDirectory(); static String getBuildsDirectory(); static String getProjectsDirectory(); static String getExecutionPath(Class clazz); static boolean createBlankProject(String path, String projectName); static Project createProjectFromTemplate(String path, String projectName, String template); static boolean createAssetDirectories(String path); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); static void saveAsset(AbstractAsset asset); }
|
@Test public void testAesEncrypt() { try { WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId); assertEquals(afterAesEncrypt, pc.encrypt(randomStr, replyMsg)); } catch (AesException e) { e.printStackTrace(); fail("no异常"); } }
|
String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(CHARSET); byteCollector.addBytes(randomStrBytes); byteCollector.addBytes(networkBytesOrder); byteCollector.addBytes(textBytes); byteCollector.addBytes(appidBytes); byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); byte[] unencrypted = byteCollector.toBytes(); try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); byte[] encrypted = cipher.doFinal(unencrypted); System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation()); String base64Encrypted = base64.encodeToString(encrypted); return base64Encrypted; } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.EncryptAESError); } }
|
WXBizMsgCrypt { String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(CHARSET); byteCollector.addBytes(randomStrBytes); byteCollector.addBytes(networkBytesOrder); byteCollector.addBytes(textBytes); byteCollector.addBytes(appidBytes); byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); byte[] unencrypted = byteCollector.toBytes(); try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); byte[] encrypted = cipher.doFinal(unencrypted); System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation()); String base64Encrypted = base64.encodeToString(encrypted); return base64Encrypted; } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.EncryptAESError); } } }
|
WXBizMsgCrypt { String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(CHARSET); byteCollector.addBytes(randomStrBytes); byteCollector.addBytes(networkBytesOrder); byteCollector.addBytes(textBytes); byteCollector.addBytes(appidBytes); byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); byte[] unencrypted = byteCollector.toBytes(); try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); byte[] encrypted = cipher.doFinal(unencrypted); System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation()); String base64Encrypted = base64.encodeToString(encrypted); return base64Encrypted; } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.EncryptAESError); } } WXBizMsgCrypt(String token, String encodingAesKey, String appId); }
|
WXBizMsgCrypt { String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(CHARSET); byteCollector.addBytes(randomStrBytes); byteCollector.addBytes(networkBytesOrder); byteCollector.addBytes(textBytes); byteCollector.addBytes(appidBytes); byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); byte[] unencrypted = byteCollector.toBytes(); try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); byte[] encrypted = cipher.doFinal(unencrypted); System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation()); String base64Encrypted = base64.encodeToString(encrypted); return base64Encrypted; } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.EncryptAESError); } } WXBizMsgCrypt(String token, String encodingAesKey, String appId); String encryptMsg(String replyMsg, String timeStamp, String nonce); String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData); String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr); }
|
WXBizMsgCrypt { String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(CHARSET); byteCollector.addBytes(randomStrBytes); byteCollector.addBytes(networkBytesOrder); byteCollector.addBytes(textBytes); byteCollector.addBytes(appidBytes); byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); byte[] unencrypted = byteCollector.toBytes(); try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); byte[] encrypted = cipher.doFinal(unencrypted); System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation()); String base64Encrypted = base64.encodeToString(encrypted); return base64Encrypted; } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.EncryptAESError); } } WXBizMsgCrypt(String token, String encodingAesKey, String appId); String encryptMsg(String replyMsg, String timeStamp, String nonce); String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData); String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr); }
|
@Test public void testAesEncrypt2() { try { WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId); assertEquals(afterAesEncrypt2, pc.encrypt(randomStr, replyMsg2)); } catch (AesException e) { e.printStackTrace(); fail("no异常"); } }
|
String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(CHARSET); byteCollector.addBytes(randomStrBytes); byteCollector.addBytes(networkBytesOrder); byteCollector.addBytes(textBytes); byteCollector.addBytes(appidBytes); byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); byte[] unencrypted = byteCollector.toBytes(); try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); byte[] encrypted = cipher.doFinal(unencrypted); System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation()); String base64Encrypted = base64.encodeToString(encrypted); return base64Encrypted; } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.EncryptAESError); } }
|
WXBizMsgCrypt { String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(CHARSET); byteCollector.addBytes(randomStrBytes); byteCollector.addBytes(networkBytesOrder); byteCollector.addBytes(textBytes); byteCollector.addBytes(appidBytes); byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); byte[] unencrypted = byteCollector.toBytes(); try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); byte[] encrypted = cipher.doFinal(unencrypted); System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation()); String base64Encrypted = base64.encodeToString(encrypted); return base64Encrypted; } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.EncryptAESError); } } }
|
WXBizMsgCrypt { String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(CHARSET); byteCollector.addBytes(randomStrBytes); byteCollector.addBytes(networkBytesOrder); byteCollector.addBytes(textBytes); byteCollector.addBytes(appidBytes); byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); byte[] unencrypted = byteCollector.toBytes(); try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); byte[] encrypted = cipher.doFinal(unencrypted); System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation()); String base64Encrypted = base64.encodeToString(encrypted); return base64Encrypted; } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.EncryptAESError); } } WXBizMsgCrypt(String token, String encodingAesKey, String appId); }
|
WXBizMsgCrypt { String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(CHARSET); byteCollector.addBytes(randomStrBytes); byteCollector.addBytes(networkBytesOrder); byteCollector.addBytes(textBytes); byteCollector.addBytes(appidBytes); byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); byte[] unencrypted = byteCollector.toBytes(); try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); byte[] encrypted = cipher.doFinal(unencrypted); System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation()); String base64Encrypted = base64.encodeToString(encrypted); return base64Encrypted; } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.EncryptAESError); } } WXBizMsgCrypt(String token, String encodingAesKey, String appId); String encryptMsg(String replyMsg, String timeStamp, String nonce); String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData); String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr); }
|
WXBizMsgCrypt { String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(CHARSET); byteCollector.addBytes(randomStrBytes); byteCollector.addBytes(networkBytesOrder); byteCollector.addBytes(textBytes); byteCollector.addBytes(appidBytes); byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); byte[] unencrypted = byteCollector.toBytes(); try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); byte[] encrypted = cipher.doFinal(unencrypted); System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation()); String base64Encrypted = base64.encodeToString(encrypted); return base64Encrypted; } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.EncryptAESError); } } WXBizMsgCrypt(String token, String encodingAesKey, String appId); String encryptMsg(String replyMsg, String timeStamp, String nonce); String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData); String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr); }
|
@Test public void testIsValidPartnerAgreement() throws IOException { JSONCPARepository repository = new JSONCPARepository(); repository.setCpaJsonFile(fileFromClasspath("agreementWithServices.json")); repository.init(); Map<String,Object> fields = new ImmutableMap.Builder<String, Object>() .put(EbmsConstants.CPA, repository.getActivePartnerAgreements().get(0)) .build(); assertThat(repository.isValidPartnerAgreement(fields),is(true)); Map<String,Object> fields2 = new ImmutableMap.Builder<String, Object>() .put(EbmsConstants.MESSAGE_SERVICE, "service2") .put(EbmsConstants.MESSAGE_ACTION,"action1") .build(); assertThat(repository.isValidPartnerAgreement(fields2),is(false)); }
|
public boolean isValidPartnerAgreement(final Map<String, Object> fields) { PartnerAgreement agreement = (PartnerAgreement) fields.get(EbmsConstants.CPA); return agreement != null; }
|
JSONCPARepository implements CPARepository { public boolean isValidPartnerAgreement(final Map<String, Object> fields) { PartnerAgreement agreement = (PartnerAgreement) fields.get(EbmsConstants.CPA); return agreement != null; } }
|
JSONCPARepository implements CPARepository { public boolean isValidPartnerAgreement(final Map<String, Object> fields) { PartnerAgreement agreement = (PartnerAgreement) fields.get(EbmsConstants.CPA); return agreement != null; } }
|
JSONCPARepository implements CPARepository { public boolean isValidPartnerAgreement(final Map<String, Object> fields) { PartnerAgreement agreement = (PartnerAgreement) fields.get(EbmsConstants.CPA); return agreement != null; } void init(); @Override List<PartnerAgreement> getPartnerAgreements(); @Override List<PartnerAgreement> getActivePartnerAgreements(); @Override PartnerAgreement findByCPAId(String cpaId); @Override PartnerAgreement findByServiceAndAction(final String service, final String action); @Override PartnerAgreement findByMessage(Document message, String ebmsVersion); boolean isValidPartnerAgreement(final Map<String, Object> fields); File getCpaJsonFile(); void setCpaJsonFile(File cpaJsonFile); }
|
JSONCPARepository implements CPARepository { public boolean isValidPartnerAgreement(final Map<String, Object> fields) { PartnerAgreement agreement = (PartnerAgreement) fields.get(EbmsConstants.CPA); return agreement != null; } void init(); @Override List<PartnerAgreement> getPartnerAgreements(); @Override List<PartnerAgreement> getActivePartnerAgreements(); @Override PartnerAgreement findByCPAId(String cpaId); @Override PartnerAgreement findByServiceAndAction(final String service, final String action); @Override PartnerAgreement findByMessage(Document message, String ebmsVersion); boolean isValidPartnerAgreement(final Map<String, Object> fields); File getCpaJsonFile(); void setCpaJsonFile(File cpaJsonFile); }
|
@Test public void testFileMessageStore() throws IOException { Exchange request = new DefaultExchange(context()); request.getIn().setHeader(EbmsConstants.EBMS_VERSION,EbmsConstants.EBMS_V3); request.getIn().setHeader(EbmsConstants.MESSAGE_ID,"testMessageID"); request.getIn().setBody(new ByteArrayInputStream("test".getBytes())); Exchange response = context().createProducerTemplate().send(MessageStore.DEFAULT_MESSAGE_STORE_ENDPOINT,request); String msgId = response.getIn().getHeader(MessageStore.JENTRATA_MESSAGE_ID, String.class); assertThat(msgId,equalTo("testMessageID")); assertThat(messageStore.findByMessageId(msgId,EbmsConstants.MESSAGE_DIRECTION_INBOUND).getMessageId(),equalTo(msgId)); }
|
@Override public Message findByMessageId(final String messageId, String messageDirection) { return new DefaultMessage(messageId); }
|
FileMessageStore implements MessageStore { @Override public Message findByMessageId(final String messageId, String messageDirection) { return new DefaultMessage(messageId); } }
|
FileMessageStore implements MessageStore { @Override public Message findByMessageId(final String messageId, String messageDirection) { return new DefaultMessage(messageId); } }
|
FileMessageStore implements MessageStore { @Override public Message findByMessageId(final String messageId, String messageDirection) { return new DefaultMessage(messageId); } @Override void store(@Body InputStream input, Exchange exchange); @Override void storeMessage(Exchange exchange); @Override Message findByMessageId(final String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection,String status); @Override void updateMessage(final String messageId, String messageDirection, MessageStatusType status, String statusDescription); String getBaseDir(); void setBaseDir(String baseDir); String getFileNameExpression(); void setFileNameExpression(String fileNameExpression); @Override String toString(); }
|
FileMessageStore implements MessageStore { @Override public Message findByMessageId(final String messageId, String messageDirection) { return new DefaultMessage(messageId); } @Override void store(@Body InputStream input, Exchange exchange); @Override void storeMessage(Exchange exchange); @Override Message findByMessageId(final String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection,String status); @Override void updateMessage(final String messageId, String messageDirection, MessageStatusType status, String statusDescription); String getBaseDir(); void setBaseDir(String baseDir); String getFileNameExpression(); void setFileNameExpression(String fileNameExpression); @Override String toString(); }
|
@Test public void testFindPayloadById() throws Exception { testFileMessageStore(); InputStream stream = messageStore.findPayloadById("testMessageID"); assertThat(IOUtils.toString(stream),equalTo("test")); }
|
@Override public InputStream findPayloadById(String messageId) { try { return new FileInputStream(getFilename(messageId)); } catch (FileNotFoundException e) { return null; } }
|
FileMessageStore implements MessageStore { @Override public InputStream findPayloadById(String messageId) { try { return new FileInputStream(getFilename(messageId)); } catch (FileNotFoundException e) { return null; } } }
|
FileMessageStore implements MessageStore { @Override public InputStream findPayloadById(String messageId) { try { return new FileInputStream(getFilename(messageId)); } catch (FileNotFoundException e) { return null; } } }
|
FileMessageStore implements MessageStore { @Override public InputStream findPayloadById(String messageId) { try { return new FileInputStream(getFilename(messageId)); } catch (FileNotFoundException e) { return null; } } @Override void store(@Body InputStream input, Exchange exchange); @Override void storeMessage(Exchange exchange); @Override Message findByMessageId(final String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection,String status); @Override void updateMessage(final String messageId, String messageDirection, MessageStatusType status, String statusDescription); String getBaseDir(); void setBaseDir(String baseDir); String getFileNameExpression(); void setFileNameExpression(String fileNameExpression); @Override String toString(); }
|
FileMessageStore implements MessageStore { @Override public InputStream findPayloadById(String messageId) { try { return new FileInputStream(getFilename(messageId)); } catch (FileNotFoundException e) { return null; } } @Override void store(@Body InputStream input, Exchange exchange); @Override void storeMessage(Exchange exchange); @Override Message findByMessageId(final String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection,String status); @Override void updateMessage(final String messageId, String messageDirection, MessageStatusType status, String statusDescription); String getBaseDir(); void setBaseDir(String baseDir); String getFileNameExpression(); void setFileNameExpression(String fileNameExpression); @Override String toString(); }
|
@Test public void testExtractPartProperties() { assertThat(EbmsUtils.extractPartProperties(null), hasSize(0)); assertThat(EbmsUtils.extractPartProperties(""), hasSize(0)); assertThat(EbmsUtils.extractPartProperties(";"), hasSize(0)); assertThat(EbmsUtils.extractPartProperties(";;"), hasSize(0)); List<Map<String,Object>> actual = EbmsUtils.extractPartProperties("test;"); assertThat(actual, hasSize(1)); assertThat(actual.get(0), hasEntry("name",(Object)"test")); assertThat(actual.get(0), hasEntry("value",null)); actual = EbmsUtils.extractPartProperties("test=test1;"); assertThat(actual, hasSize(1)); assertThat(actual.get(0), hasEntry("name",(Object)"test")); assertThat(actual.get(0), hasEntry("value",(Object)"test1")); actual = EbmsUtils.extractPartProperties("test=test1;test2="); assertThat(actual, hasSize(2)); assertThat(actual.get(0), hasEntry("name",(Object)"test")); assertThat(actual.get(0), hasEntry("value",(Object)"test1")); assertThat(actual.get(1), hasEntry("name",(Object)"test2")); assertThat(actual.get(1), hasEntry("value",null)); actual = EbmsUtils.extractPartProperties("test=;test2=test3"); assertThat(actual, hasSize(2)); assertThat(actual.get(0), hasEntry("name",(Object)"test")); assertThat(actual.get(0), hasEntry("value",null)); assertThat(actual.get(1), hasEntry("name",(Object)"test2")); assertThat(actual.get(1), hasEntry("value",(Object)"test3")); actual = EbmsUtils.extractPartProperties("test=;test2=test3;"); assertThat(actual, hasSize(2)); assertThat(actual.get(0), hasEntry("name",(Object)"test")); assertThat(actual.get(0), hasEntry("value",null)); assertThat(actual.get(1), hasEntry("name",(Object)"test2")); assertThat(actual.get(1), hasEntry("value",(Object)"test3")); }
|
public static List<Map<String, Object>> extractPartProperties(String partProperties) { List<Map<String,Object>> properites = new ArrayList<>(); if(partProperties != null && partProperties.length() > 0) { String [] propertyArray = partProperties.split(";"); for (String property : propertyArray) { String [] value = property.split("="); Map<String,Object> propertyMap = new HashMap<>(); propertyMap.put("name",value[0]); if(value.length == 2) { propertyMap.put("value",value[1]); } else { propertyMap.put("value",null); } properites.add(propertyMap); } } return properites; }
|
EbmsUtils { public static List<Map<String, Object>> extractPartProperties(String partProperties) { List<Map<String,Object>> properites = new ArrayList<>(); if(partProperties != null && partProperties.length() > 0) { String [] propertyArray = partProperties.split(";"); for (String property : propertyArray) { String [] value = property.split("="); Map<String,Object> propertyMap = new HashMap<>(); propertyMap.put("name",value[0]); if(value.length == 2) { propertyMap.put("value",value[1]); } else { propertyMap.put("value",null); } properites.add(propertyMap); } } return properites; } }
|
EbmsUtils { public static List<Map<String, Object>> extractPartProperties(String partProperties) { List<Map<String,Object>> properites = new ArrayList<>(); if(partProperties != null && partProperties.length() > 0) { String [] propertyArray = partProperties.split(";"); for (String property : propertyArray) { String [] value = property.split("="); Map<String,Object> propertyMap = new HashMap<>(); propertyMap.put("name",value[0]); if(value.length == 2) { propertyMap.put("value",value[1]); } else { propertyMap.put("value",null); } properites.add(propertyMap); } } return properites; } private EbmsUtils(); }
|
EbmsUtils { public static List<Map<String, Object>> extractPartProperties(String partProperties) { List<Map<String,Object>> properites = new ArrayList<>(); if(partProperties != null && partProperties.length() > 0) { String [] propertyArray = partProperties.split(";"); for (String property : propertyArray) { String [] value = property.split("="); Map<String,Object> propertyMap = new HashMap<>(); propertyMap.put("name",value[0]); if(value.length == 2) { propertyMap.put("value",value[1]); } else { propertyMap.put("value",null); } properites.add(propertyMap); } } return properites; } private EbmsUtils(); static final SOAPMessage createSOAP11MessageFromClasspath(String filename); static final SOAPMessage createSOAP12MessageFromClasspath(String filename); static final SOAPMessage createSOAP12Message(String ebmsMessage); static final SOAPMessage createSOAP11Message(String ebmsMessage); static final SOAPMessage createSOAPMessage(String soapProtocol, String ebmsMessage); static final SOAPMessage parse(String soapProtocol, String contentType, InputStream stream); static final SOAPMessage parse(Exchange exchange); static void addAttachment(SOAPMessage soapMessage,String contentId,String contentType,InputStream content); static void addAttachment(SOAPMessage soapMessage, String payloadId, String contentType, byte[] content); static void addAttachment(SOAPMessage soapMessage, String payloadId, String contentType, byte[] content, Map<String, String> mimeHeaders); static void addGZippedAttachment(SOAPMessage soapMessage, String payloadId, byte[] content); static void addAttachment(SOAPMessage soapMessage,String contentId,String contentType,InputStream content,Map<String,String> headers); static String encodeContentId(String contentId); static String decodeContentID(String contentId); static InputStream compressStream(String compressionType, byte [] content); static byte [] compress(String compressionType, byte [] content); static byte [] decompress(String compressionType, byte [] content); static String toString(SOAPMessage soapMessage); static String toString(Document doc); static byte[] toByteArray(SOAPMessage soapMessage); static void elementToStream(Element element, OutputStream out); static final Document toXML(String xmlString); static String toStringFromClasspath(String filename); static File fileFromClasspath(String filename); static final String ebmsXpathValue(Element element,String xpath); static final Node ebmsXpathNode(String xml,String xpath); static final Node ebmsXpathNode(Node xml,String xpath); static final NodeList ebmsXpathNodeList(String xml,String xpath); static final NodeList ebmsXpathNodeList(Node xml,String xpath); static boolean hasEbmsXpath(Document element, String query); static List<Map<String, Object>> extractPartProperties(String partProperties); }
|
EbmsUtils { public static List<Map<String, Object>> extractPartProperties(String partProperties) { List<Map<String,Object>> properites = new ArrayList<>(); if(partProperties != null && partProperties.length() > 0) { String [] propertyArray = partProperties.split(";"); for (String property : propertyArray) { String [] value = property.split("="); Map<String,Object> propertyMap = new HashMap<>(); propertyMap.put("name",value[0]); if(value.length == 2) { propertyMap.put("value",value[1]); } else { propertyMap.put("value",null); } properites.add(propertyMap); } } return properites; } private EbmsUtils(); static final SOAPMessage createSOAP11MessageFromClasspath(String filename); static final SOAPMessage createSOAP12MessageFromClasspath(String filename); static final SOAPMessage createSOAP12Message(String ebmsMessage); static final SOAPMessage createSOAP11Message(String ebmsMessage); static final SOAPMessage createSOAPMessage(String soapProtocol, String ebmsMessage); static final SOAPMessage parse(String soapProtocol, String contentType, InputStream stream); static final SOAPMessage parse(Exchange exchange); static void addAttachment(SOAPMessage soapMessage,String contentId,String contentType,InputStream content); static void addAttachment(SOAPMessage soapMessage, String payloadId, String contentType, byte[] content); static void addAttachment(SOAPMessage soapMessage, String payloadId, String contentType, byte[] content, Map<String, String> mimeHeaders); static void addGZippedAttachment(SOAPMessage soapMessage, String payloadId, byte[] content); static void addAttachment(SOAPMessage soapMessage,String contentId,String contentType,InputStream content,Map<String,String> headers); static String encodeContentId(String contentId); static String decodeContentID(String contentId); static InputStream compressStream(String compressionType, byte [] content); static byte [] compress(String compressionType, byte [] content); static byte [] decompress(String compressionType, byte [] content); static String toString(SOAPMessage soapMessage); static String toString(Document doc); static byte[] toByteArray(SOAPMessage soapMessage); static void elementToStream(Element element, OutputStream out); static final Document toXML(String xmlString); static String toStringFromClasspath(String filename); static File fileFromClasspath(String filename); static final String ebmsXpathValue(Element element,String xpath); static final Node ebmsXpathNode(String xml,String xpath); static final Node ebmsXpathNode(Node xml,String xpath); static final NodeList ebmsXpathNodeList(String xml,String xpath); static final NodeList ebmsXpathNodeList(Node xml,String xpath); static boolean hasEbmsXpath(Document element, String query); static List<Map<String, Object>> extractPartProperties(String partProperties); }
|
@Test public void testSoap12SignMessage() throws Exception { MessageDetector messageDetector = new MessageDetector(); Map<String,Object> headers = new HashMap<>(); InputStream stream = new ByteArrayInputStream(EbmsUtils.toStringFromClasspath("signal-message.xml").getBytes()); messageDetector.parse(stream,headers); assertThat((String) headers.get(EbmsConstants.SOAP_VERSION),equalTo(SOAPConstants.SOAP_1_2_PROTOCOL)); assertThat((String) headers.get(EbmsConstants.EBMS_VERSION),equalTo(EbmsConstants.EBMS_V3)); assertThat((String) headers.get(EbmsConstants.MESSAGE_ID),equalTo("[email protected]")); assertThat((String) headers.get(EbmsConstants.REF_TO_MESSAGE_ID),equalTo("[email protected]")); assertThat((String) headers.get(EbmsConstants.MESSAGE_TYPE),equalTo(MessageType.SIGNAL_MESSAGE_WITH_USER_MESSAGE.name())); }
|
public void parse(@Body InputStream input, @Headers Map<String, Object> headers) throws IOException { try { byte [] msgData = new byte[20480]; int count = input.read(msgData); if(count > 0) { String msg = new String(msgData); String soapVersion = msg.contains(EbmsConstants.SOAP_1_2_NAMESPACE) ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL; headers.put(EbmsConstants.SOAP_VERSION,soapVersion); String ebmsVersion = msg.contains(EbmsConstants.EBXML_V3_NAMESPACE) ? EbmsConstants.EBMS_V3 : EbmsConstants.EBMS_V2; headers.put(EbmsConstants.EBMS_VERSION,ebmsVersion); headers.put(EbmsConstants.MESSAGE_ID, getMessageId(msg)); headers.put(EbmsConstants.REF_TO_MESSAGE_ID, getRefMessageId(msg)); headers.put(EbmsConstants.MESSAGE_TYPE, getMessageType(msg).name()); } } finally { input.reset(); } }
|
MessageDetector { public void parse(@Body InputStream input, @Headers Map<String, Object> headers) throws IOException { try { byte [] msgData = new byte[20480]; int count = input.read(msgData); if(count > 0) { String msg = new String(msgData); String soapVersion = msg.contains(EbmsConstants.SOAP_1_2_NAMESPACE) ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL; headers.put(EbmsConstants.SOAP_VERSION,soapVersion); String ebmsVersion = msg.contains(EbmsConstants.EBXML_V3_NAMESPACE) ? EbmsConstants.EBMS_V3 : EbmsConstants.EBMS_V2; headers.put(EbmsConstants.EBMS_VERSION,ebmsVersion); headers.put(EbmsConstants.MESSAGE_ID, getMessageId(msg)); headers.put(EbmsConstants.REF_TO_MESSAGE_ID, getRefMessageId(msg)); headers.put(EbmsConstants.MESSAGE_TYPE, getMessageType(msg).name()); } } finally { input.reset(); } } }
|
MessageDetector { public void parse(@Body InputStream input, @Headers Map<String, Object> headers) throws IOException { try { byte [] msgData = new byte[20480]; int count = input.read(msgData); if(count > 0) { String msg = new String(msgData); String soapVersion = msg.contains(EbmsConstants.SOAP_1_2_NAMESPACE) ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL; headers.put(EbmsConstants.SOAP_VERSION,soapVersion); String ebmsVersion = msg.contains(EbmsConstants.EBXML_V3_NAMESPACE) ? EbmsConstants.EBMS_V3 : EbmsConstants.EBMS_V2; headers.put(EbmsConstants.EBMS_VERSION,ebmsVersion); headers.put(EbmsConstants.MESSAGE_ID, getMessageId(msg)); headers.put(EbmsConstants.REF_TO_MESSAGE_ID, getRefMessageId(msg)); headers.put(EbmsConstants.MESSAGE_TYPE, getMessageType(msg).name()); } } finally { input.reset(); } } }
|
MessageDetector { public void parse(@Body InputStream input, @Headers Map<String, Object> headers) throws IOException { try { byte [] msgData = new byte[20480]; int count = input.read(msgData); if(count > 0) { String msg = new String(msgData); String soapVersion = msg.contains(EbmsConstants.SOAP_1_2_NAMESPACE) ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL; headers.put(EbmsConstants.SOAP_VERSION,soapVersion); String ebmsVersion = msg.contains(EbmsConstants.EBXML_V3_NAMESPACE) ? EbmsConstants.EBMS_V3 : EbmsConstants.EBMS_V2; headers.put(EbmsConstants.EBMS_VERSION,ebmsVersion); headers.put(EbmsConstants.MESSAGE_ID, getMessageId(msg)); headers.put(EbmsConstants.REF_TO_MESSAGE_ID, getRefMessageId(msg)); headers.put(EbmsConstants.MESSAGE_TYPE, getMessageType(msg).name()); } } finally { input.reset(); } } void parse(@Body InputStream input, @Headers Map<String, Object> headers); }
|
MessageDetector { public void parse(@Body InputStream input, @Headers Map<String, Object> headers) throws IOException { try { byte [] msgData = new byte[20480]; int count = input.read(msgData); if(count > 0) { String msg = new String(msgData); String soapVersion = msg.contains(EbmsConstants.SOAP_1_2_NAMESPACE) ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL; headers.put(EbmsConstants.SOAP_VERSION,soapVersion); String ebmsVersion = msg.contains(EbmsConstants.EBXML_V3_NAMESPACE) ? EbmsConstants.EBMS_V3 : EbmsConstants.EBMS_V2; headers.put(EbmsConstants.EBMS_VERSION,ebmsVersion); headers.put(EbmsConstants.MESSAGE_ID, getMessageId(msg)); headers.put(EbmsConstants.REF_TO_MESSAGE_ID, getRefMessageId(msg)); headers.put(EbmsConstants.MESSAGE_TYPE, getMessageType(msg).name()); } } finally { input.reset(); } } void parse(@Body InputStream input, @Headers Map<String, Object> headers); }
|
@Test public void testSoap12SignReceipt() throws Exception { MessageDetector messageDetector = new MessageDetector(); Map<String,Object> headers = new HashMap<>(); InputStream stream = new ByteArrayInputStream(EbmsUtils.toStringFromClasspath("signed-receipt.xml").getBytes()); messageDetector.parse(stream,headers); assertThat((String) headers.get(EbmsConstants.SOAP_VERSION),equalTo(SOAPConstants.SOAP_1_2_PROTOCOL)); assertThat((String) headers.get(EbmsConstants.EBMS_VERSION),equalTo(EbmsConstants.EBMS_V3)); assertThat((String) headers.get(EbmsConstants.MESSAGE_ID),equalTo("[email protected]")); assertThat((String) headers.get(EbmsConstants.REF_TO_MESSAGE_ID),equalTo("[email protected]")); assertThat((String) headers.get(EbmsConstants.MESSAGE_TYPE),equalTo(MessageType.SIGNAL_MESSAGE.name())); }
|
public void parse(@Body InputStream input, @Headers Map<String, Object> headers) throws IOException { try { byte [] msgData = new byte[20480]; int count = input.read(msgData); if(count > 0) { String msg = new String(msgData); String soapVersion = msg.contains(EbmsConstants.SOAP_1_2_NAMESPACE) ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL; headers.put(EbmsConstants.SOAP_VERSION,soapVersion); String ebmsVersion = msg.contains(EbmsConstants.EBXML_V3_NAMESPACE) ? EbmsConstants.EBMS_V3 : EbmsConstants.EBMS_V2; headers.put(EbmsConstants.EBMS_VERSION,ebmsVersion); headers.put(EbmsConstants.MESSAGE_ID, getMessageId(msg)); headers.put(EbmsConstants.REF_TO_MESSAGE_ID, getRefMessageId(msg)); headers.put(EbmsConstants.MESSAGE_TYPE, getMessageType(msg).name()); } } finally { input.reset(); } }
|
MessageDetector { public void parse(@Body InputStream input, @Headers Map<String, Object> headers) throws IOException { try { byte [] msgData = new byte[20480]; int count = input.read(msgData); if(count > 0) { String msg = new String(msgData); String soapVersion = msg.contains(EbmsConstants.SOAP_1_2_NAMESPACE) ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL; headers.put(EbmsConstants.SOAP_VERSION,soapVersion); String ebmsVersion = msg.contains(EbmsConstants.EBXML_V3_NAMESPACE) ? EbmsConstants.EBMS_V3 : EbmsConstants.EBMS_V2; headers.put(EbmsConstants.EBMS_VERSION,ebmsVersion); headers.put(EbmsConstants.MESSAGE_ID, getMessageId(msg)); headers.put(EbmsConstants.REF_TO_MESSAGE_ID, getRefMessageId(msg)); headers.put(EbmsConstants.MESSAGE_TYPE, getMessageType(msg).name()); } } finally { input.reset(); } } }
|
MessageDetector { public void parse(@Body InputStream input, @Headers Map<String, Object> headers) throws IOException { try { byte [] msgData = new byte[20480]; int count = input.read(msgData); if(count > 0) { String msg = new String(msgData); String soapVersion = msg.contains(EbmsConstants.SOAP_1_2_NAMESPACE) ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL; headers.put(EbmsConstants.SOAP_VERSION,soapVersion); String ebmsVersion = msg.contains(EbmsConstants.EBXML_V3_NAMESPACE) ? EbmsConstants.EBMS_V3 : EbmsConstants.EBMS_V2; headers.put(EbmsConstants.EBMS_VERSION,ebmsVersion); headers.put(EbmsConstants.MESSAGE_ID, getMessageId(msg)); headers.put(EbmsConstants.REF_TO_MESSAGE_ID, getRefMessageId(msg)); headers.put(EbmsConstants.MESSAGE_TYPE, getMessageType(msg).name()); } } finally { input.reset(); } } }
|
MessageDetector { public void parse(@Body InputStream input, @Headers Map<String, Object> headers) throws IOException { try { byte [] msgData = new byte[20480]; int count = input.read(msgData); if(count > 0) { String msg = new String(msgData); String soapVersion = msg.contains(EbmsConstants.SOAP_1_2_NAMESPACE) ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL; headers.put(EbmsConstants.SOAP_VERSION,soapVersion); String ebmsVersion = msg.contains(EbmsConstants.EBXML_V3_NAMESPACE) ? EbmsConstants.EBMS_V3 : EbmsConstants.EBMS_V2; headers.put(EbmsConstants.EBMS_VERSION,ebmsVersion); headers.put(EbmsConstants.MESSAGE_ID, getMessageId(msg)); headers.put(EbmsConstants.REF_TO_MESSAGE_ID, getRefMessageId(msg)); headers.put(EbmsConstants.MESSAGE_TYPE, getMessageType(msg).name()); } } finally { input.reset(); } } void parse(@Body InputStream input, @Headers Map<String, Object> headers); }
|
MessageDetector { public void parse(@Body InputStream input, @Headers Map<String, Object> headers) throws IOException { try { byte [] msgData = new byte[20480]; int count = input.read(msgData); if(count > 0) { String msg = new String(msgData); String soapVersion = msg.contains(EbmsConstants.SOAP_1_2_NAMESPACE) ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL; headers.put(EbmsConstants.SOAP_VERSION,soapVersion); String ebmsVersion = msg.contains(EbmsConstants.EBXML_V3_NAMESPACE) ? EbmsConstants.EBMS_V3 : EbmsConstants.EBMS_V2; headers.put(EbmsConstants.EBMS_VERSION,ebmsVersion); headers.put(EbmsConstants.MESSAGE_ID, getMessageId(msg)); headers.put(EbmsConstants.REF_TO_MESSAGE_ID, getRefMessageId(msg)); headers.put(EbmsConstants.MESSAGE_TYPE, getMessageType(msg).name()); } } finally { input.reset(); } } void parse(@Body InputStream input, @Headers Map<String, Object> headers); }
|
@Test public void testUpdateStoreMimeMessage() throws Exception { File body = fileFromClasspath("simple-as4-receipt.xml"); String contentType = "Multipart/Related; boundary=\"----=_Part_7_10584188.1123489648993\"; type=\"application/soap+xml\"; start=\"<[email protected]>\""; String messageId = "testMimeMessage1"; assertStoredMessage(messageId, contentType, body, MessageType.USER_MESSAGE); messageStore.updateMessage(messageId, EbmsConstants.MESSAGE_DIRECTION_INBOUND, MessageStatusType.RECEIVED,"Message Received"); try(Connection conn = dataSource.getConnection()) { try (PreparedStatement st = conn.prepareStatement("select * from message where message_id = ?")) { st.setString(1,messageId); ResultSet resultSet = st.executeQuery(); assertThat(resultSet.next(),is(true)); assertThat(resultSet.getString("status"),equalTo("RECEIVED")); assertThat(resultSet.getString("status_description"),equalTo("Message Received")); } } }
|
@Override public void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription) { repositoryManager.updateMessage(messageId,messageDirection,status,statusDescription); }
|
JDBCMessageStore implements MessageStore { @Override public void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription) { repositoryManager.updateMessage(messageId,messageDirection,status,statusDescription); } }
|
JDBCMessageStore implements MessageStore { @Override public void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription) { repositoryManager.updateMessage(messageId,messageDirection,status,statusDescription); } }
|
JDBCMessageStore implements MessageStore { @Override public void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription) { repositoryManager.updateMessage(messageId,messageDirection,status,statusDescription); } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); }
|
JDBCMessageStore implements MessageStore { @Override public void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription) { repositoryManager.updateMessage(messageId,messageDirection,status,statusDescription); } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); }
|
@Test public void testFindByMessageId() throws Exception { String contentType = "application/soap+xml"; File body = fileFromClasspath("simple-as4-receipt.xml"); String messageId = "testSoapMessage1"; assertStoredMessage(messageId, contentType, body, MessageType.SIGNAL_MESSAGE_WITH_USER_MESSAGE); messageStore.updateMessage(messageId, EbmsConstants.MESSAGE_DIRECTION_INBOUND, MessageStatusType.RECEIVED,"Message Received"); Message message = messageStore.findByMessageId("testSoapMessage1",EbmsConstants.MESSAGE_DIRECTION_INBOUND); assertThat(message,notNullValue()); assertThat(message.getMessageId(),equalTo("testSoapMessage1")); assertThat(message.getStatus(),equalTo(MessageStatusType.RECEIVED)); assertThat(message.getStatusDescription(),equalTo("Message Received")); }
|
@Override public Message findByMessageId(String messageId, String messageDirection) { Map<String,Object> fields = new HashMap<>(); fields.put("message_id",messageId); fields.put("message_box",messageDirection); List<Message> messages = repositoryManager.selectMessageBy(fields); if(messages.size() > 0) { return messages.get(0); } return null; }
|
JDBCMessageStore implements MessageStore { @Override public Message findByMessageId(String messageId, String messageDirection) { Map<String,Object> fields = new HashMap<>(); fields.put("message_id",messageId); fields.put("message_box",messageDirection); List<Message> messages = repositoryManager.selectMessageBy(fields); if(messages.size() > 0) { return messages.get(0); } return null; } }
|
JDBCMessageStore implements MessageStore { @Override public Message findByMessageId(String messageId, String messageDirection) { Map<String,Object> fields = new HashMap<>(); fields.put("message_id",messageId); fields.put("message_box",messageDirection); List<Message> messages = repositoryManager.selectMessageBy(fields); if(messages.size() > 0) { return messages.get(0); } return null; } }
|
JDBCMessageStore implements MessageStore { @Override public Message findByMessageId(String messageId, String messageDirection) { Map<String,Object> fields = new HashMap<>(); fields.put("message_id",messageId); fields.put("message_box",messageDirection); List<Message> messages = repositoryManager.selectMessageBy(fields); if(messages.size() > 0) { return messages.get(0); } return null; } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); }
|
JDBCMessageStore implements MessageStore { @Override public Message findByMessageId(String messageId, String messageDirection) { Map<String,Object> fields = new HashMap<>(); fields.put("message_id",messageId); fields.put("message_box",messageDirection); List<Message> messages = repositoryManager.selectMessageBy(fields); if(messages.size() > 0) { return messages.get(0); } return null; } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); }
|
@Test public void testFindPayloadById() throws Exception { testFindByMessageId(); InputStream stream = messageStore.findPayloadById("testSoapMessage1"); assertThat(stream,notNullValue()); assertThat(IOUtils.toString(stream),equalTo(IOUtils.toString(new FileInputStream(fileFromClasspath("simple-as4-receipt.xml"))))); }
|
@Override public InputStream findPayloadById(String messageId) { InputStream payload = repositoryManager.selectRepositoryBy("message_id",messageId); return payload; }
|
JDBCMessageStore implements MessageStore { @Override public InputStream findPayloadById(String messageId) { InputStream payload = repositoryManager.selectRepositoryBy("message_id",messageId); return payload; } }
|
JDBCMessageStore implements MessageStore { @Override public InputStream findPayloadById(String messageId) { InputStream payload = repositoryManager.selectRepositoryBy("message_id",messageId); return payload; } }
|
JDBCMessageStore implements MessageStore { @Override public InputStream findPayloadById(String messageId) { InputStream payload = repositoryManager.selectRepositoryBy("message_id",messageId); return payload; } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); }
|
JDBCMessageStore implements MessageStore { @Override public InputStream findPayloadById(String messageId) { InputStream payload = repositoryManager.selectRepositoryBy("message_id",messageId); return payload; } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); }
|
@Test public void testFindMessageByStatus() throws Exception { testFindByMessageId(); List<Message> messages = messageStore.findByMessageStatus(EbmsConstants.MESSAGE_DIRECTION_INBOUND,MessageStatusType.RECEIVED.name()); assertThat(messages,notNullValue()); assertThat(messages,hasSize(1)); Message message = messages.get(0); assertThat(message,notNullValue()); assertThat(message.getMessageId(),equalTo("testSoapMessage1")); assertThat(message.getStatus(),equalTo(MessageStatusType.RECEIVED)); assertThat(message.getStatusDescription(),equalTo("Message Received")); }
|
@Override public List<Message> findByMessageStatus(String messageDirection, String status) { Map<String,Object> fields = new HashMap<>(); fields.put("status",status); fields.put("message_box",messageDirection); fields.put("orderByDesc","time_stamp"); fields.put("maxResults",100); List<Message> messages = repositoryManager.selectMessageBy(fields); return messages; }
|
JDBCMessageStore implements MessageStore { @Override public List<Message> findByMessageStatus(String messageDirection, String status) { Map<String,Object> fields = new HashMap<>(); fields.put("status",status); fields.put("message_box",messageDirection); fields.put("orderByDesc","time_stamp"); fields.put("maxResults",100); List<Message> messages = repositoryManager.selectMessageBy(fields); return messages; } }
|
JDBCMessageStore implements MessageStore { @Override public List<Message> findByMessageStatus(String messageDirection, String status) { Map<String,Object> fields = new HashMap<>(); fields.put("status",status); fields.put("message_box",messageDirection); fields.put("orderByDesc","time_stamp"); fields.put("maxResults",100); List<Message> messages = repositoryManager.selectMessageBy(fields); return messages; } }
|
JDBCMessageStore implements MessageStore { @Override public List<Message> findByMessageStatus(String messageDirection, String status) { Map<String,Object> fields = new HashMap<>(); fields.put("status",status); fields.put("message_box",messageDirection); fields.put("orderByDesc","time_stamp"); fields.put("maxResults",100); List<Message> messages = repositoryManager.selectMessageBy(fields); return messages; } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); }
|
JDBCMessageStore implements MessageStore { @Override public List<Message> findByMessageStatus(String messageDirection, String status) { Map<String,Object> fields = new HashMap<>(); fields.put("status",status); fields.put("message_box",messageDirection); fields.put("orderByDesc","time_stamp"); fields.put("maxResults",100); List<Message> messages = repositoryManager.selectMessageBy(fields); return messages; } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); }
|
@Test public void testGet() { AvailableSegment<TestItem> a = new AvailableSegment<>(model, 2); assertEquals(20, a.getFrom()); assertEquals(30, a.getTo()); assertEquals(2, a.getPage()); a.dataProvided(TestItem.range(20, 30)); assertEquals("p.20", a.get(20).toString()); assertEquals("p.29", a.get(29).toString()); assertNull(a.get(19)); assertNull(a.get(30)); }
|
public ITEM get(int position) { if (items == null) { return null; } if (covered(position)) { int index = position - getFrom(); return index < items.size() ? items.get(index) : null; } return null; }
|
AvailableSegment extends Segment implements Serializable { public ITEM get(int position) { if (items == null) { return null; } if (covered(position)) { int index = position - getFrom(); return index < items.size() ? items.get(index) : null; } return null; } }
|
AvailableSegment extends Segment implements Serializable { public ITEM get(int position) { if (items == null) { return null; } if (covered(position)) { int index = position - getFrom(); return index < items.size() ? items.get(index) : null; } return null; } AvailableSegment(UncoveringDataModel<?> model, int page); }
|
AvailableSegment extends Segment implements Serializable { public ITEM get(int position) { if (items == null) { return null; } if (covered(position)) { int index = position - getFrom(); return index < items.size() ? items.get(index) : null; } return null; } AvailableSegment(UncoveringDataModel<?> model, int page); int getMaxIndex(); ITEM get(int position); boolean covered(int position); void dataProvided(List<ITEM> items); void dataProvided(List<ITEM> items, int maxIndex); List<ITEM> getData(); String toString(); }
|
AvailableSegment extends Segment implements Serializable { public ITEM get(int position) { if (items == null) { return null; } if (covered(position)) { int index = position - getFrom(); return index < items.size() ? items.get(index) : null; } return null; } AvailableSegment(UncoveringDataModel<?> model, int page); int getMaxIndex(); ITEM get(int position); boolean covered(int position); void dataProvided(List<ITEM> items); void dataProvided(List<ITEM> items, int maxIndex); List<ITEM> getData(); String toString(); }
|
@Test public void testCovered() { AvailableSegment<TestItem> a = new AvailableSegment<>(model, 2); when(model.getPage(anyInt())).thenReturn(2); assertTrue(a.covered(0)); when(model.getPage(anyInt())).thenReturn(1); assertFalse(a.covered(0)); }
|
public boolean covered(int position) { return model.getPage(position) == page; }
|
AvailableSegment extends Segment implements Serializable { public boolean covered(int position) { return model.getPage(position) == page; } }
|
AvailableSegment extends Segment implements Serializable { public boolean covered(int position) { return model.getPage(position) == page; } AvailableSegment(UncoveringDataModel<?> model, int page); }
|
AvailableSegment extends Segment implements Serializable { public boolean covered(int position) { return model.getPage(position) == page; } AvailableSegment(UncoveringDataModel<?> model, int page); int getMaxIndex(); ITEM get(int position); boolean covered(int position); void dataProvided(List<ITEM> items); void dataProvided(List<ITEM> items, int maxIndex); List<ITEM> getData(); String toString(); }
|
AvailableSegment extends Segment implements Serializable { public boolean covered(int position) { return model.getPage(position) == page; } AvailableSegment(UncoveringDataModel<?> model, int page); int getMaxIndex(); ITEM get(int position); boolean covered(int position); void dataProvided(List<ITEM> items); void dataProvided(List<ITEM> items, int maxIndex); List<ITEM> getData(); String toString(); }
|
@Test public void testDataProvided() { AvailableSegment<TestItem> a = new AvailableSegment<>(model, 2); assertNull(a.get(20)); assertNull(a.get(29)); assertNull(a.get(19)); assertNull(a.get(30)); assertEquals(0, a.getMaxIndex()); a.dataProvided(TestItem.range(20, 29)); assertEquals("p.20", a.get(20).toString()); assertEquals("p.28", a.get(28).toString()); assertNull(a.get(19)); assertNull(a.get(29)); assertNull(a.get(30)); assertEquals(29, a.getMaxIndex()); a.dataProvided(TestItem.range(20, 30)); assertEquals(30, a.getMaxIndex()); assertEquals("p.29", a.get(29).toString()); a.dataProvided(null); assertNull(a.get(20)); assertNull(a.get(29)); assertNull(a.get(19)); assertNull(a.get(30)); assertEquals(0, a.getMaxIndex()); }
|
public void dataProvided(List<ITEM> items) { if (items == null) { dataProvided(items, 0); } else { dataProvided(items, getFrom() + items.size()); } }
|
AvailableSegment extends Segment implements Serializable { public void dataProvided(List<ITEM> items) { if (items == null) { dataProvided(items, 0); } else { dataProvided(items, getFrom() + items.size()); } } }
|
AvailableSegment extends Segment implements Serializable { public void dataProvided(List<ITEM> items) { if (items == null) { dataProvided(items, 0); } else { dataProvided(items, getFrom() + items.size()); } } AvailableSegment(UncoveringDataModel<?> model, int page); }
|
AvailableSegment extends Segment implements Serializable { public void dataProvided(List<ITEM> items) { if (items == null) { dataProvided(items, 0); } else { dataProvided(items, getFrom() + items.size()); } } AvailableSegment(UncoveringDataModel<?> model, int page); int getMaxIndex(); ITEM get(int position); boolean covered(int position); void dataProvided(List<ITEM> items); void dataProvided(List<ITEM> items, int maxIndex); List<ITEM> getData(); String toString(); }
|
AvailableSegment extends Segment implements Serializable { public void dataProvided(List<ITEM> items) { if (items == null) { dataProvided(items, 0); } else { dataProvided(items, getFrom() + items.size()); } } AvailableSegment(UncoveringDataModel<?> model, int page); int getMaxIndex(); ITEM get(int position); boolean covered(int position); void dataProvided(List<ITEM> items); void dataProvided(List<ITEM> items, int maxIndex); List<ITEM> getData(); String toString(); }
|
@Test public void testSegment() { UncoveringDataModel<TestItem> model = mock(UncoveringDataModel.class); when(model.getPageSize()).thenReturn(10); Segment s = new Segment(model, 20); assertEquals(200, s.getFrom()); assertEquals(210, s.getTo()); assertEquals(20, s.getPage()); }
|
public Segment(UncoveringDataModel<ITEM> model, int page) { this.model = model; this.page = page; }
|
Segment implements Serializable { public Segment(UncoveringDataModel<ITEM> model, int page) { this.model = model; this.page = page; } }
|
Segment implements Serializable { public Segment(UncoveringDataModel<ITEM> model, int page) { this.model = model; this.page = page; } Segment(UncoveringDataModel<ITEM> model, int page); }
|
Segment implements Serializable { public Segment(UncoveringDataModel<ITEM> model, int page) { this.model = model; this.page = page; } Segment(UncoveringDataModel<ITEM> model, int page); int getFrom(); int getTo(); int getPage(); @Override boolean equals(Object o); void setModel(UncoveringDataModel<ITEM> model); @Override int hashCode(); String toString(); }
|
Segment implements Serializable { public Segment(UncoveringDataModel<ITEM> model, int page) { this.model = model; this.page = page; } Segment(UncoveringDataModel<ITEM> model, int page); int getFrom(); int getTo(); int getPage(); @Override boolean equals(Object o); void setModel(UncoveringDataModel<ITEM> model); @Override int hashCode(); String toString(); }
|
@Test public void testRequestData() throws Exception { DataFetchManager<TestItem> fetcher = new DataFetchManager<>(); fetcher.setDataFetcher(primary); fetcher.setDataModel(model); fetcher.setDelayWhenPending(700); fetcher.setThreads(1); int pg2 = 2; int pg10 = 10; int pg20 = 20; int pg50 = 50; AvailableSegment<TestItem> s2 = new AvailableSegment<>(model, pg2); AvailableSegment<TestItem> s10 = new AvailableSegment<>(model, pg10); AvailableSegment<TestItem> s20 = new AvailableSegment<>(model, pg20); AvailableSegment<TestItem> s50 = new AvailableSegment<>(model, pg50); assertFalse(fetcher.alreadyFetching(pg2)); assertFalse(fetcher.alreadyFetching(pg10)); assertFalse(fetcher.alreadyFetching(pg20)); assertFalse(fetcher.alreadyFetching(pg50)); fetcher.requestData(pg2); assertTrue(fetcher.alreadyFetching(pg2)); assertFalse(fetcher.alreadyFetching(pg10)); assertFalse(fetcher.alreadyFetching(pg20)); assertFalse(fetcher.alreadyFetching(pg50)); fetcher.requestData(pg10); assertTrue(fetcher.alreadyFetching(pg2)); assertTrue(fetcher.alreadyFetching(pg10)); assertFalse(fetcher.alreadyFetching(pg20)); assertFalse(fetcher.alreadyFetching(pg50)); assertFalse(fetcher.alreadyFetching(3)); fetcher.requestData(pg20); fetcher.requestData(pg50); assertTrue(fetcher.alreadyFetching(pg2)); assertTrue(fetcher.alreadyFetching(pg10)); assertTrue(fetcher.alreadyFetching(pg20)); assertTrue(fetcher.alreadyFetching(pg50)); assertNotNull(primary.request()); assertEquals("Second request must only be queued", 1, primary.requests.size()); assertEquals(s2.getFrom(), primary.request().getFrom()); assertEquals(s2.getTo(), primary.request().getTo()); PrimaryResponse r2 = new PrimaryResponse(TestItem.range(s2.getFrom(), s2.getTo()), 777); fetcher.dataAvailable(primary.request(), r2); verify(model).dataAvailable(s2); assertEquals("Second request must be sent", 2, primary.requests.size()); assertEquals("p50 request must be sent first", 500, primary.request().getFrom()); Thread.sleep(2 * (fetcher.getDelayWhenPending() + fetcher.timerExtraDelay) + 300); assertEquals("All requests must be sent", 4, primary.requests.size()); assertEquals(20, primary.requests.get(0).getFrom()); assertEquals(500, primary.requests.get(1).getFrom()); assertEquals(200, primary.requests.get(2).getFrom()); assertEquals(100, primary.requests.get(3).getFrom()); PrimaryResponse r50 = new PrimaryResponse(TestItem.range(s50.getFrom(), s50.getTo()), 777); fetcher.dataAvailable(primary.request(1), r50); verify(model).dataAvailable(s50); PrimaryResponse r20 = new PrimaryResponse(TestItem.range(s20.getFrom(), s20.getTo()), 777); fetcher.dataAvailable(primary.request(2), r20); verify(model).dataAvailable(s20); PrimaryResponse r10 = new PrimaryResponse(TestItem.range(s10.getFrom(), s10.getTo()), 777); fetcher.dataAvailable(primary.request(3), r10); verify(model).dataAvailable(s10); }
|
public synchronized void requestData(int page) { AvailableSegment<ITEM> segment = new AvailableSegment<>(dataModel, page); PrimaryRequest request = new PrimaryRequest(segment.getFrom(), segment.getTo(), dataModel.getQuery(), dataModel.isFirstQueryResult()); request.setPage(segment.getPage()); coverage.put(segment.getPage(), segment); queue.push(request); int c = bestChannel(); if (now() - fetchInProcessing[c] > delayWhenPending) { servePending(); } else { scheduleServePending(); } }
|
DataFetchManager implements DataAvailableListener<ITEM> { public synchronized void requestData(int page) { AvailableSegment<ITEM> segment = new AvailableSegment<>(dataModel, page); PrimaryRequest request = new PrimaryRequest(segment.getFrom(), segment.getTo(), dataModel.getQuery(), dataModel.isFirstQueryResult()); request.setPage(segment.getPage()); coverage.put(segment.getPage(), segment); queue.push(request); int c = bestChannel(); if (now() - fetchInProcessing[c] > delayWhenPending) { servePending(); } else { scheduleServePending(); } } }
|
DataFetchManager implements DataAvailableListener<ITEM> { public synchronized void requestData(int page) { AvailableSegment<ITEM> segment = new AvailableSegment<>(dataModel, page); PrimaryRequest request = new PrimaryRequest(segment.getFrom(), segment.getTo(), dataModel.getQuery(), dataModel.isFirstQueryResult()); request.setPage(segment.getPage()); coverage.put(segment.getPage(), segment); queue.push(request); int c = bestChannel(); if (now() - fetchInProcessing[c] > delayWhenPending) { servePending(); } else { scheduleServePending(); } } DataFetchManager(); }
|
DataFetchManager implements DataAvailableListener<ITEM> { public synchronized void requestData(int page) { AvailableSegment<ITEM> segment = new AvailableSegment<>(dataModel, page); PrimaryRequest request = new PrimaryRequest(segment.getFrom(), segment.getTo(), dataModel.getQuery(), dataModel.isFirstQueryResult()); request.setPage(segment.getPage()); coverage.put(segment.getPage(), segment); queue.push(request); int c = bestChannel(); if (now() - fetchInProcessing[c] > delayWhenPending) { servePending(); } else { scheduleServePending(); } } DataFetchManager(); DataFetcher getDataFetcher(); DataFetchManager setDataFetcher(DataFetcher dataFetcher); UncoveringDataModel<ITEM> getDataModel(); DataFetchManager setDataModel(UncoveringDataModel<ITEM> dataModel); synchronized void requestData(int page); long getDelayWhenPending(); DataFetchManager setDelayWhenPending(long delayWhenPending); boolean alreadyFetching(int page); @Override synchronized void dataAvailable(PrimaryRequest request, PrimaryResponse<ITEM> data); @Override void notifyVisibleArea(int fromInclusive, int endExclusive); @Override synchronized void dataUnavailable(PrimaryRequest request); void reset(); DataFetchManager<ITEM> setThreads(int threads); int getTreads(); void lowMemory(); }
|
DataFetchManager implements DataAvailableListener<ITEM> { public synchronized void requestData(int page) { AvailableSegment<ITEM> segment = new AvailableSegment<>(dataModel, page); PrimaryRequest request = new PrimaryRequest(segment.getFrom(), segment.getTo(), dataModel.getQuery(), dataModel.isFirstQueryResult()); request.setPage(segment.getPage()); coverage.put(segment.getPage(), segment); queue.push(request); int c = bestChannel(); if (now() - fetchInProcessing[c] > delayWhenPending) { servePending(); } else { scheduleServePending(); } } DataFetchManager(); DataFetcher getDataFetcher(); DataFetchManager setDataFetcher(DataFetcher dataFetcher); UncoveringDataModel<ITEM> getDataModel(); DataFetchManager setDataModel(UncoveringDataModel<ITEM> dataModel); synchronized void requestData(int page); long getDelayWhenPending(); DataFetchManager setDelayWhenPending(long delayWhenPending); boolean alreadyFetching(int page); @Override synchronized void dataAvailable(PrimaryRequest request, PrimaryResponse<ITEM> data); @Override void notifyVisibleArea(int fromInclusive, int endExclusive); @Override synchronized void dataUnavailable(PrimaryRequest request); void reset(); DataFetchManager<ITEM> setThreads(int threads); int getTreads(); void lowMemory(); }
|
@Test public void shouldLoadForecastWeather() throws ParseException, IOException { final ThreeHoursForecastWeather item = Fakes.fakeResponse(Responses.JSON.THREE_HOUR_FORECAST); doReturn(Observable.just(item)) .when(weatherApi).getForecastWeather(anyDouble(), anyDouble()); TestObserver<ThreeHoursForecastWeather> testObserver = new TestObserver<>(); weatherService.getForecastWeather(1.0, 1.0).subscribe(testObserver); testObserver.assertSubscribed().assertNoErrors().assertComplete().assertValue(item); }
|
public Observable<ThreeHoursForecastWeather> getForecastWeather(double longitude, double latitude) { return api.getForecastWeather(longitude, latitude) .subscribeOn(scheduler) .take(1); }
|
WeatherService { public Observable<ThreeHoursForecastWeather> getForecastWeather(double longitude, double latitude) { return api.getForecastWeather(longitude, latitude) .subscribeOn(scheduler) .take(1); } }
|
WeatherService { public Observable<ThreeHoursForecastWeather> getForecastWeather(double longitude, double latitude) { return api.getForecastWeather(longitude, latitude) .subscribeOn(scheduler) .take(1); } @Inject WeatherService(WeatherApi api, @RxScheduler(NETWORK) Scheduler scheduler, ImageRequestManager imageRequestManager); }
|
WeatherService { public Observable<ThreeHoursForecastWeather> getForecastWeather(double longitude, double latitude) { return api.getForecastWeather(longitude, latitude) .subscribeOn(scheduler) .take(1); } @Inject WeatherService(WeatherApi api, @RxScheduler(NETWORK) Scheduler scheduler, ImageRequestManager imageRequestManager); Observable<Bitmap> loadIcon(String icon); Observable<TomorrowWeather> getTomorrowWeather(double longitude, double latitude); Observable<ThreeHoursForecastWeather> getForecastWeather(double longitude, double latitude); Observable<TodayWeather> getCurrentWeather(double longitude, double latitude); }
|
WeatherService { public Observable<ThreeHoursForecastWeather> getForecastWeather(double longitude, double latitude) { return api.getForecastWeather(longitude, latitude) .subscribeOn(scheduler) .take(1); } @Inject WeatherService(WeatherApi api, @RxScheduler(NETWORK) Scheduler scheduler, ImageRequestManager imageRequestManager); Observable<Bitmap> loadIcon(String icon); Observable<TomorrowWeather> getTomorrowWeather(double longitude, double latitude); Observable<ThreeHoursForecastWeather> getForecastWeather(double longitude, double latitude); Observable<TodayWeather> getCurrentWeather(double longitude, double latitude); }
|
@Test public void searchApiFunctionIsCalled() { final TestObserver<SearchModel> observer = new TestObserver<>(); searchService.searchByCity(CITY).subscribe(observer); verify(weatherApi).searchWeather(CITY); observer.assertSubscribed() .assertNoErrors() .assertComplete() .assertValue(item); }
|
public Observable<SearchModel> searchByCity(String city) { lastCity = city; return api.searchWeather(city).subscribeOn(this.scheduler); }
|
SearchService { public Observable<SearchModel> searchByCity(String city) { lastCity = city; return api.searchWeather(city).subscribeOn(this.scheduler); } }
|
SearchService { public Observable<SearchModel> searchByCity(String city) { lastCity = city; return api.searchWeather(city).subscribeOn(this.scheduler); } @Inject SearchService(WeatherApi api, @RxScheduler(NETWORK) Scheduler scheduler); }
|
SearchService { public Observable<SearchModel> searchByCity(String city) { lastCity = city; return api.searchWeather(city).subscribeOn(this.scheduler); } @Inject SearchService(WeatherApi api, @RxScheduler(NETWORK) Scheduler scheduler); Observable<SearchModel> searchByCity(String city); String getLastSearch(); }
|
SearchService { public Observable<SearchModel> searchByCity(String city) { lastCity = city; return api.searchWeather(city).subscribeOn(this.scheduler); } @Inject SearchService(WeatherApi api, @RxScheduler(NETWORK) Scheduler scheduler); Observable<SearchModel> searchByCity(String city); String getLastSearch(); }
|
@Test public void shouldNotLoadForecastsIfNoLocationIsPresent() { when(locationService.lastLocation()).thenReturn(null); vm.onViewAttached(); vm.loadForecastWeatherDataForTomorrow(); verifyZeroInteractions(weatherService); }
|
public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(this::handleForecastDataResult, this::showError); } }
|
TomorrowWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(this::handleForecastDataResult, this::showError); } } }
|
TomorrowWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(this::handleForecastDataResult, this::showError); } } @Inject @Replaceable TomorrowWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService,
WeatherService weatherService,
TomorrowWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); }
|
TomorrowWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(this::handleForecastDataResult, this::showError); } } @Inject @Replaceable TomorrowWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService,
WeatherService weatherService,
TomorrowWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); void loadForecastWeatherDataForTomorrow(); }
|
TomorrowWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(this::handleForecastDataResult, this::showError); } } @Inject @Replaceable TomorrowWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService,
WeatherService weatherService,
TomorrowWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); void loadForecastWeatherDataForTomorrow(); }
|
@Test public void shouldLoadForecastsIfLocationIsPresent() throws ParseException, IOException { double longitude = 1.0; double latitude = 1.0; final Location location = mockLocation(mock(Location.class), 1.0, 1.0); when(locationService.lastLocation()).thenReturn(location); String expectedResult = Responses.createExpectedFilteredResult(); when(weatherParser.parse(any(ThreeHoursForecastWeather.class))).thenReturn(expectedResult); when(weatherService.getForecastWeather(longitude, latitude)) .thenReturn(Observable.just(fakeResponse(Responses.JSON.THREE_HOUR_FORECAST))); vm.loadForecastWeatherDataForTomorrow(); verify(navigation).toForecastActivity(expectedResult); }
|
public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(this::handleForecastDataResult, this::showError); } }
|
TomorrowWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(this::handleForecastDataResult, this::showError); } } }
|
TomorrowWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(this::handleForecastDataResult, this::showError); } } @Inject @Replaceable TomorrowWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService,
WeatherService weatherService,
TomorrowWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); }
|
TomorrowWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(this::handleForecastDataResult, this::showError); } } @Inject @Replaceable TomorrowWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService,
WeatherService weatherService,
TomorrowWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); void loadForecastWeatherDataForTomorrow(); }
|
TomorrowWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(this::handleForecastDataResult, this::showError); } } @Inject @Replaceable TomorrowWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService,
WeatherService weatherService,
TomorrowWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); void loadForecastWeatherDataForTomorrow(); }
|
@Test public void shouldNotLoadForecastsIfNoLocationIsPresent() { when(locationService.lastLocation()).thenReturn(null); vm.onViewAttached(); vm.loadForecastWeatherDataForToday(); verifyZeroInteractions(weatherService); }
|
public void loadForecastWeatherDataForToday() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(forecastData -> { dispatchRequestFinished(); navigateToForecastActivity(forecastData); }, this::showError); } }
|
TodayWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForToday() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(forecastData -> { dispatchRequestFinished(); navigateToForecastActivity(forecastData); }, this::showError); } } }
|
TodayWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForToday() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(forecastData -> { dispatchRequestFinished(); navigateToForecastActivity(forecastData); }, this::showError); } } @Inject @Replaceable TodayWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService, WeatherService weatherService,
TodayWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); }
|
TodayWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForToday() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(forecastData -> { dispatchRequestFinished(); navigateToForecastActivity(forecastData); }, this::showError); } } @Inject @Replaceable TodayWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService, WeatherService weatherService,
TodayWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); void loadForecastWeatherDataForToday(); }
|
TodayWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForToday() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(forecastData -> { dispatchRequestFinished(); navigateToForecastActivity(forecastData); }, this::showError); } } @Inject @Replaceable TodayWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService, WeatherService weatherService,
TodayWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); void loadForecastWeatherDataForToday(); }
|
@Test public void shouldLoadForecastsIfLocationIsPresent() throws ParseException, IOException { double longitude = 1.0; double latitude = 1.0; final Location location = mockLocation(mock(Location.class), 1.0, 1.0); when(locationService.lastLocation()).thenReturn(location); String expectedResult = Responses.createExpectedFilteredResult(); when(weatherParser.parse(any(ThreeHoursForecastWeather.class))).thenReturn(expectedResult); when(weatherService.getForecastWeather(longitude, latitude)) .thenReturn(Observable.just(fakeResponse(Responses.JSON.THREE_HOUR_FORECAST))); vm.loadForecastWeatherDataForToday(); verify(navigation).toForecastActivity(expectedResult); }
|
public void loadForecastWeatherDataForToday() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(forecastData -> { dispatchRequestFinished(); navigateToForecastActivity(forecastData); }, this::showError); } }
|
TodayWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForToday() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(forecastData -> { dispatchRequestFinished(); navigateToForecastActivity(forecastData); }, this::showError); } } }
|
TodayWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForToday() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(forecastData -> { dispatchRequestFinished(); navigateToForecastActivity(forecastData); }, this::showError); } } @Inject @Replaceable TodayWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService, WeatherService weatherService,
TodayWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); }
|
TodayWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForToday() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(forecastData -> { dispatchRequestFinished(); navigateToForecastActivity(forecastData); }, this::showError); } } @Inject @Replaceable TodayWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService, WeatherService weatherService,
TodayWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); void loadForecastWeatherDataForToday(); }
|
TodayWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForToday() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(forecastData -> { dispatchRequestFinished(); navigateToForecastActivity(forecastData); }, this::showError); } } @Inject @Replaceable TodayWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService, WeatherService weatherService,
TodayWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); void loadForecastWeatherDataForToday(); }
|
@Test public void testCheckReset_IMMEDIATELY() { SyncTrigger syncTrigger = new SyncTrigger( () -> mockTrigger.triggered(), () -> mockThreshold.shouldTrigger(), IMMEDIATELY); when(mockThreshold.shouldTrigger()).thenReturn(false); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, times(1)).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, times(1)).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(false); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, times(1)).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); }
|
public void check(){ check(false); }
|
SyncTrigger { public void check(){ check(false); } }
|
SyncTrigger { public void check(){ check(false); } SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold); SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold, ResetRule resetRule); }
|
SyncTrigger { public void check(){ check(false); } SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold); SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold, ResetRule resetRule); void check(); void checkLazy(); }
|
SyncTrigger { public void check(){ check(false); } SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold); SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold, ResetRule resetRule); void check(); void checkLazy(); }
|
@Test public void testMultipleSpaceText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(DOUBLE_SPACE_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(FIRST_LINE_DOUBLE_SPACE, wrappedLines.get(0)); Assert.assertEquals("-multi space text", wrappedLines.get(1)); Assert.assertEquals(2, wrappedLines.size()); }
|
public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); static final String SPACE; static final String EMPTY; }
|
@Test public void testLineBreakText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(LINE_BREAK_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(FIRST_LINE_LINE_BREAK, wrappedLines.get(0)); Assert.assertEquals("fox jumped over the abc defghi", wrappedLines.get(1)); Assert.assertEquals("jklmnopqrstuvwxyz0123", wrappedLines.get(2)); Assert.assertEquals("", wrappedLines.get(3)); Assert.assertEquals("", wrappedLines.get(4)); Assert.assertEquals("45678 9abcde fghijklm nopqrs tuvwxyz0", wrappedLines.get(5)); Assert.assertEquals("123456", wrappedLines.get(6)); Assert.assertEquals(7, wrappedLines.size()); }
|
public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); static final String SPACE; static final String EMPTY; }
|
@Test public void testLongText_zeroWidthAvailable() { boolean exceptionThrown = false; try { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(LONG_TEXT, ZERO_CHARACTERS_AVAILABLE); } catch (IllegalArgumentException e) { exceptionThrown = true; } Assert.assertEquals(true, exceptionThrown); }
|
public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); static final String SPACE; static final String EMPTY; }
|
@Test public void testPaddingOnTheRight() { String paddedText = TextPadder.padText(TEXT_ORIG, 10, TextPadder.Pad.RIGHT, '+'); Assert.assertEquals(TEXT_ORIG + "+++++++", paddedText); }
|
public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter); }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter); }
|
@Test public void testPaddingOnTheLeft() { String paddedText = TextPadder.padText(TEXT_ORIG, 10, TextPadder.Pad.LEFT, '*'); Assert.assertEquals("*******" + TEXT_ORIG, paddedText); }
|
public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter); }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter); }
|
@Test public void testPaddingWhenAlreadyPadded() { String paddedText = TextPadder.padText(TEXT_ORIG, 3, TextPadder.Pad.LEFT, PADDING_CHARACTER); Assert.assertEquals(TEXT_ORIG, paddedText); }
|
public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter); }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter); }
|
@Test public void testPaddingIllegalValues() { try { TextPadder.padText(null, 3, TextPadder.Pad.LEFT, PADDING_CHARACTER); Assert.fail("should have thrown an exception by now: original text was null"); } catch (Exception e) { } try { TextPadder.padText(TEXT_ORIG, 3, null, PADDING_CHARACTER); Assert.fail("should have thrown an exception by now: pad direction was null"); } catch (Exception e) { } try { TextPadder.padText(TEXT_ORIG, 2, TextPadder.Pad.LEFT, PADDING_CHARACTER); Assert.fail("should have thrown an exception by now: original text was already longer than the desiredLength"); } catch (Exception e) { } }
|
public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter); }
|
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter); }
|
@Test public void observersNotifiedAtLeastOnce() throws Exception { CounterWithProgress counterWithProgress = new CounterWithProgress(WorkMode.SYNCHRONOUS, logger); Observer mockObserver = mock(Observer.class); counterWithProgress.addObserver(mockObserver); counterWithProgress.increaseBy20(); verify(mockObserver, atLeastOnce()).somethingChanged(); }
|
@SuppressLint("StaticFieldLeak") public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new Async<Void, Integer, Integer>(workMode) { @Override protected Integer doInBackground(Void... voids) { int totalIncrease = 0; for (int ii=0; ii<20; ii++) { synchronized (this) { try { wait(workMode == WorkMode.SYNCHRONOUS ? 1 : 100); } catch (InterruptedException e) { } } publishProgressTask(++totalIncrease); } return totalIncrease; } @Override protected void onProgressUpdate(Integer... values) { logger.i(TAG, "-tick-"); progress = values[0]; notifyObservers(); } @Override protected void onPostExecute(Integer result) { logger.i(TAG, "done"); count = count + result; isBusy = false; progress = 0; notifyObservers(); } }.executeTask((Void)null); }
|
CounterWithProgress extends ObservableImp { @SuppressLint("StaticFieldLeak") public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new Async<Void, Integer, Integer>(workMode) { @Override protected Integer doInBackground(Void... voids) { int totalIncrease = 0; for (int ii=0; ii<20; ii++) { synchronized (this) { try { wait(workMode == WorkMode.SYNCHRONOUS ? 1 : 100); } catch (InterruptedException e) { } } publishProgressTask(++totalIncrease); } return totalIncrease; } @Override protected void onProgressUpdate(Integer... values) { logger.i(TAG, "-tick-"); progress = values[0]; notifyObservers(); } @Override protected void onPostExecute(Integer result) { logger.i(TAG, "done"); count = count + result; isBusy = false; progress = 0; notifyObservers(); } }.executeTask((Void)null); } }
|
CounterWithProgress extends ObservableImp { @SuppressLint("StaticFieldLeak") public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new Async<Void, Integer, Integer>(workMode) { @Override protected Integer doInBackground(Void... voids) { int totalIncrease = 0; for (int ii=0; ii<20; ii++) { synchronized (this) { try { wait(workMode == WorkMode.SYNCHRONOUS ? 1 : 100); } catch (InterruptedException e) { } } publishProgressTask(++totalIncrease); } return totalIncrease; } @Override protected void onProgressUpdate(Integer... values) { logger.i(TAG, "-tick-"); progress = values[0]; notifyObservers(); } @Override protected void onPostExecute(Integer result) { logger.i(TAG, "done"); count = count + result; isBusy = false; progress = 0; notifyObservers(); } }.executeTask((Void)null); } CounterWithProgress(WorkMode workMode, Logger logger); }
|
CounterWithProgress extends ObservableImp { @SuppressLint("StaticFieldLeak") public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new Async<Void, Integer, Integer>(workMode) { @Override protected Integer doInBackground(Void... voids) { int totalIncrease = 0; for (int ii=0; ii<20; ii++) { synchronized (this) { try { wait(workMode == WorkMode.SYNCHRONOUS ? 1 : 100); } catch (InterruptedException e) { } } publishProgressTask(++totalIncrease); } return totalIncrease; } @Override protected void onProgressUpdate(Integer... values) { logger.i(TAG, "-tick-"); progress = values[0]; notifyObservers(); } @Override protected void onPostExecute(Integer result) { logger.i(TAG, "done"); count = count + result; isBusy = false; progress = 0; notifyObservers(); } }.executeTask((Void)null); } CounterWithProgress(WorkMode workMode, Logger logger); @SuppressLint("StaticFieldLeak") void increaseBy20(); boolean isBusy(); int getCount(); int getProgress(); }
|
CounterWithProgress extends ObservableImp { @SuppressLint("StaticFieldLeak") public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new Async<Void, Integer, Integer>(workMode) { @Override protected Integer doInBackground(Void... voids) { int totalIncrease = 0; for (int ii=0; ii<20; ii++) { synchronized (this) { try { wait(workMode == WorkMode.SYNCHRONOUS ? 1 : 100); } catch (InterruptedException e) { } } publishProgressTask(++totalIncrease); } return totalIncrease; } @Override protected void onProgressUpdate(Integer... values) { logger.i(TAG, "-tick-"); progress = values[0]; notifyObservers(); } @Override protected void onPostExecute(Integer result) { logger.i(TAG, "done"); count = count + result; isBusy = false; progress = 0; notifyObservers(); } }.executeTask((Void)null); } CounterWithProgress(WorkMode workMode, Logger logger); @SuppressLint("StaticFieldLeak") void increaseBy20(); boolean isBusy(); int getCount(); int getProgress(); static final String TAG; }
|
@Test public void observersNotifiedAtLeastOnce() throws Exception { CounterWithLambdas counterWithLambdas = new CounterWithLambdas(WorkMode.SYNCHRONOUS, logger); Observer mockObserver = mock(Observer.class); counterWithLambdas.addObserver(mockObserver); counterWithLambdas.increaseBy20(); verify(mockObserver, atLeastOnce()).somethingChanged(); }
|
public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new AsyncBuilder<Void, Integer>(workMode) .doInBackground(input -> CounterWithLambdas.this.doStuffInBackground(input)) .onPostExecute(result -> CounterWithLambdas.this.doThingsWithTheResult(result)) .execute((Void) null); }
|
CounterWithLambdas extends ObservableImp { public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new AsyncBuilder<Void, Integer>(workMode) .doInBackground(input -> CounterWithLambdas.this.doStuffInBackground(input)) .onPostExecute(result -> CounterWithLambdas.this.doThingsWithTheResult(result)) .execute((Void) null); } }
|
CounterWithLambdas extends ObservableImp { public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new AsyncBuilder<Void, Integer>(workMode) .doInBackground(input -> CounterWithLambdas.this.doStuffInBackground(input)) .onPostExecute(result -> CounterWithLambdas.this.doThingsWithTheResult(result)) .execute((Void) null); } CounterWithLambdas(WorkMode workMode, Logger logger); }
|
CounterWithLambdas extends ObservableImp { public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new AsyncBuilder<Void, Integer>(workMode) .doInBackground(input -> CounterWithLambdas.this.doStuffInBackground(input)) .onPostExecute(result -> CounterWithLambdas.this.doThingsWithTheResult(result)) .execute((Void) null); } CounterWithLambdas(WorkMode workMode, Logger logger); void increaseBy20(); boolean isBusy(); int getCount(); }
|
CounterWithLambdas extends ObservableImp { public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new AsyncBuilder<Void, Integer>(workMode) .doInBackground(input -> CounterWithLambdas.this.doStuffInBackground(input)) .onPostExecute(result -> CounterWithLambdas.this.doThingsWithTheResult(result)) .execute((Void) null); } CounterWithLambdas(WorkMode workMode, Logger logger); void increaseBy20(); boolean isBusy(); int getCount(); static final String TAG; }
|
@Test public void addNewTrack() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.addNewTrack(); Assert.assertEquals(1, playlistAdvancedModel.getTrackListSize()); Assert.assertEquals(1, playlistAdvancedModel.getTrack(0).getNumberOfPlaysRequested()); }
|
public void addNewTrack() { logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void addNewTrack() { logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void addNewTrack() { logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void addNewTrack() { logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void addNewTrack() { logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }
|
@Test public void testCheckReset_ONLY_AFTER_REVERSION() { SyncTrigger syncTrigger = new SyncTrigger( () -> mockTrigger.triggered(), () -> mockThreshold.shouldTrigger(), ONLY_AFTER_REVERSION); when(mockThreshold.shouldTrigger()).thenReturn(false); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, times(1)).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(false); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, times(1)).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); }
|
public void check(){ check(false); }
|
SyncTrigger { public void check(){ check(false); } }
|
SyncTrigger { public void check(){ check(false); } SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold); SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold, ResetRule resetRule); }
|
SyncTrigger { public void check(){ check(false); } SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold); SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold, ResetRule resetRule); void check(); void checkLazy(); }
|
SyncTrigger { public void check(){ check(false); } SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold); SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold, ResetRule resetRule); void check(); void checkLazy(); }
|
@Test public void removeTrack() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.addNewTrack(); playlistAdvancedModel.removeTrack(0); Assert.assertEquals(0, playlistAdvancedModel.getTrackListSize()); }
|
public void removeTrack(int index) { logger.i(TAG, "removeTrack() " + index); checkIndex(index); trackList.remove(index); notifyObservers(); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void removeTrack(int index) { logger.i(TAG, "removeTrack() " + index); checkIndex(index); trackList.remove(index); notifyObservers(); } }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void removeTrack(int index) { logger.i(TAG, "removeTrack() " + index); checkIndex(index); trackList.remove(index); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void removeTrack(int index) { logger.i(TAG, "removeTrack() " + index); checkIndex(index); trackList.remove(index); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void removeTrack(int index) { logger.i(TAG, "removeTrack() " + index); checkIndex(index); trackList.remove(index); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }
|
@Test public void add5NewTracks() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.add5NewTracks(); Assert.assertEquals(5, playlistAdvancedModel.getTrackListSize()); Assert.assertEquals(1, playlistAdvancedModel.getTrack(4).getNumberOfPlaysRequested()); }
|
public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); } }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }
|
@Test public void remove5Tracks() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.add5NewTracks(); playlistAdvancedModel.remove5Tracks(); Assert.assertEquals(0, playlistAdvancedModel.getTrackListSize()); }
|
public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.removeRange(0, 5); notifyObservers(); } }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.removeRange(0, 5); notifyObservers(); } } }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.removeRange(0, 5); notifyObservers(); } } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.removeRange(0, 5); notifyObservers(); } } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.removeRange(0, 5); notifyObservers(); } } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }
|
@Test public void removeAllTracks() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.add5NewTracks(); playlistAdvancedModel.addNewTrack(); playlistAdvancedModel.addNewTrack(); playlistAdvancedModel.removeAllTracks(); Assert.assertEquals(0, playlistAdvancedModel.getTrackListSize()); }
|
public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); } }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }
|
@Test public void observersNotifiedAtLeastOnceForAddTrack() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); Observer mockObserver = mock(Observer.class); playlistAdvancedModel.addObserver(mockObserver); playlistAdvancedModel.addNewTrack(); verify(mockObserver, atLeastOnce()).somethingChanged(); }
|
public void addNewTrack() { logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void addNewTrack() { logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void addNewTrack() { logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void addNewTrack() { logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }
|
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void addNewTrack() { logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); }
|
@Test public void initialConditions() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); Assert.assertEquals(0, playlistSimpleModel.getTrackListSize()); Assert.assertEquals(false, playlistSimpleModel.hasObservers()); }
|
public int getTrackListSize(){ return trackList.size(); }
|
PlaylistSimpleModel extends ObservableImp { public int getTrackListSize(){ return trackList.size(); } }
|
PlaylistSimpleModel extends ObservableImp { public int getTrackListSize(){ return trackList.size(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); }
|
PlaylistSimpleModel extends ObservableImp { public int getTrackListSize(){ return trackList.size(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
PlaylistSimpleModel extends ObservableImp { public int getTrackListSize(){ return trackList.size(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
@Test public void addNewTrack() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.addNewTrack(); Assert.assertEquals(1, playlistSimpleModel.getTrackListSize()); Assert.assertEquals(1, playlistSimpleModel.getTrack(0).getNumberOfPlaysRequested()); }
|
public void addNewTrack(){ logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); }
|
PlaylistSimpleModel extends ObservableImp { public void addNewTrack(){ logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } }
|
PlaylistSimpleModel extends ObservableImp { public void addNewTrack(){ logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); }
|
PlaylistSimpleModel extends ObservableImp { public void addNewTrack(){ logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
PlaylistSimpleModel extends ObservableImp { public void addNewTrack(){ logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
@Test public void removeTrack() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.addNewTrack(); playlistSimpleModel.removeTrack(0); Assert.assertEquals(0, playlistSimpleModel.getTrackListSize()); }
|
public void removeTrack(int index){ logger.i(TAG, "removeTrack() "+index); checkIndex(index); trackList.remove(index); notifyObservers(); }
|
PlaylistSimpleModel extends ObservableImp { public void removeTrack(int index){ logger.i(TAG, "removeTrack() "+index); checkIndex(index); trackList.remove(index); notifyObservers(); } }
|
PlaylistSimpleModel extends ObservableImp { public void removeTrack(int index){ logger.i(TAG, "removeTrack() "+index); checkIndex(index); trackList.remove(index); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); }
|
PlaylistSimpleModel extends ObservableImp { public void removeTrack(int index){ logger.i(TAG, "removeTrack() "+index); checkIndex(index); trackList.remove(index); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
PlaylistSimpleModel extends ObservableImp { public void removeTrack(int index){ logger.i(TAG, "removeTrack() "+index); checkIndex(index); trackList.remove(index); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
@Test public void add5NewTracks() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.add5NewTracks(); Assert.assertEquals(5, playlistSimpleModel.getTrackListSize()); Assert.assertEquals(1, playlistSimpleModel.getTrack(4).getNumberOfPlaysRequested()); }
|
public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); }
|
PlaylistSimpleModel extends ObservableImp { public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); } }
|
PlaylistSimpleModel extends ObservableImp { public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); }
|
PlaylistSimpleModel extends ObservableImp { public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
PlaylistSimpleModel extends ObservableImp { public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
@Test public void remove5Tracks() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.add5NewTracks(); playlistSimpleModel.remove5Tracks(); Assert.assertEquals(0, playlistSimpleModel.getTrackListSize()); }
|
public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.subList(0, 5).clear(); notifyObservers(); } }
|
PlaylistSimpleModel extends ObservableImp { public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.subList(0, 5).clear(); notifyObservers(); } } }
|
PlaylistSimpleModel extends ObservableImp { public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.subList(0, 5).clear(); notifyObservers(); } } PlaylistSimpleModel(WorkMode workMode, Logger logger); }
|
PlaylistSimpleModel extends ObservableImp { public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.subList(0, 5).clear(); notifyObservers(); } } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
PlaylistSimpleModel extends ObservableImp { public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.subList(0, 5).clear(); notifyObservers(); } } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
@Test public void testCheckReset_NEVER() { SyncTrigger syncTrigger = new SyncTrigger( () -> mockTrigger.triggered(), () -> mockThreshold.shouldTrigger(), NEVER); when(mockThreshold.shouldTrigger()).thenReturn(false); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, times(1)).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(false); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); }
|
public void check(){ check(false); }
|
SyncTrigger { public void check(){ check(false); } }
|
SyncTrigger { public void check(){ check(false); } SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold); SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold, ResetRule resetRule); }
|
SyncTrigger { public void check(){ check(false); } SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold); SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold, ResetRule resetRule); void check(); void checkLazy(); }
|
SyncTrigger { public void check(){ check(false); } SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold); SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold, ResetRule resetRule); void check(); void checkLazy(); }
|
@Test public void removeAllTracks() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.add5NewTracks(); playlistSimpleModel.addNewTrack(); playlistSimpleModel.addNewTrack(); playlistSimpleModel.removeAllTracks(); Assert.assertEquals(0, playlistSimpleModel.getTrackListSize()); }
|
public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); }
|
PlaylistSimpleModel extends ObservableImp { public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); } }
|
PlaylistSimpleModel extends ObservableImp { public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); }
|
PlaylistSimpleModel extends ObservableImp { public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
PlaylistSimpleModel extends ObservableImp { public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
@Test public void observersNotifiedAtLeastOnceForAddTrack() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); Observer mockObserver = mock(Observer.class); playlistSimpleModel.addObserver(mockObserver); playlistSimpleModel.addNewTrack(); verify(mockObserver, atLeastOnce()).somethingChanged(); }
|
public void addNewTrack(){ logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); }
|
PlaylistSimpleModel extends ObservableImp { public void addNewTrack(){ logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } }
|
PlaylistSimpleModel extends ObservableImp { public void addNewTrack(){ logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); }
|
PlaylistSimpleModel extends ObservableImp { public void addNewTrack(){ logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
PlaylistSimpleModel extends ObservableImp { public void addNewTrack(){ logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); }
|
@Test public void increaseMobileWallet() throws Exception { Wallet wallet = new Wallet(logger); wallet.increaseMobileWallet(); Assert.assertEquals(true, wallet.canIncrease()); Assert.assertEquals(true, wallet.canDecrease()); Assert.assertEquals(wallet.totalDollarsAvailable - 1, wallet.getSavingsWalletAmount()); Assert.assertEquals(1, wallet.getMobileWalletAmount()); }
|
public void increaseMobileWallet() { if (canIncrease()) { mobileWalletDollars++; logger.i(TAG, "Increasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } }
|
Wallet extends ObservableImp { public void increaseMobileWallet() { if (canIncrease()) { mobileWalletDollars++; logger.i(TAG, "Increasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } }
|
Wallet extends ObservableImp { public void increaseMobileWallet() { if (canIncrease()) { mobileWalletDollars++; logger.i(TAG, "Increasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); }
|
Wallet extends ObservableImp { public void increaseMobileWallet() { if (canIncrease()) { mobileWalletDollars++; logger.i(TAG, "Increasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); void increaseMobileWallet(); void decreaseMobileWallet(); int getMobileWalletAmount(); int getSavingsWalletAmount(); boolean canIncrease(); boolean canDecrease(); }
|
Wallet extends ObservableImp { public void increaseMobileWallet() { if (canIncrease()) { mobileWalletDollars++; logger.i(TAG, "Increasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); void increaseMobileWallet(); void decreaseMobileWallet(); int getMobileWalletAmount(); int getSavingsWalletAmount(); boolean canIncrease(); boolean canDecrease(); final int totalDollarsAvailable; }
|
@Test public void decreaseMobileWallet() throws Exception { Wallet wallet = new Wallet(logger); wallet.increaseMobileWallet(); Assert.assertEquals(1, wallet.getMobileWalletAmount()); wallet.decreaseMobileWallet(); Assert.assertEquals(true, wallet.canIncrease()); Assert.assertEquals(false, wallet.canDecrease()); Assert.assertEquals(wallet.totalDollarsAvailable, wallet.getSavingsWalletAmount()); Assert.assertEquals(0, wallet.getMobileWalletAmount()); }
|
public void decreaseMobileWallet(){ if (canDecrease()) { mobileWalletDollars--; logger.i(TAG, "Decreasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } }
|
Wallet extends ObservableImp { public void decreaseMobileWallet(){ if (canDecrease()) { mobileWalletDollars--; logger.i(TAG, "Decreasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } }
|
Wallet extends ObservableImp { public void decreaseMobileWallet(){ if (canDecrease()) { mobileWalletDollars--; logger.i(TAG, "Decreasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); }
|
Wallet extends ObservableImp { public void decreaseMobileWallet(){ if (canDecrease()) { mobileWalletDollars--; logger.i(TAG, "Decreasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); void increaseMobileWallet(); void decreaseMobileWallet(); int getMobileWalletAmount(); int getSavingsWalletAmount(); boolean canIncrease(); boolean canDecrease(); }
|
Wallet extends ObservableImp { public void decreaseMobileWallet(){ if (canDecrease()) { mobileWalletDollars--; logger.i(TAG, "Decreasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); void increaseMobileWallet(); void decreaseMobileWallet(); int getMobileWalletAmount(); int getSavingsWalletAmount(); boolean canIncrease(); boolean canDecrease(); final int totalDollarsAvailable; }
|
@Test public void observersNotifiedAtLeastOnceForIncrease() throws Exception { Wallet wallet = new Wallet(logger); Observer mockObserver = mock(Observer.class); wallet.addObserver(mockObserver); wallet.increaseMobileWallet(); verify(mockObserver, atLeastOnce()).somethingChanged(); }
|
public void increaseMobileWallet() { if (canIncrease()) { mobileWalletDollars++; logger.i(TAG, "Increasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } }
|
Wallet extends ObservableImp { public void increaseMobileWallet() { if (canIncrease()) { mobileWalletDollars++; logger.i(TAG, "Increasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } }
|
Wallet extends ObservableImp { public void increaseMobileWallet() { if (canIncrease()) { mobileWalletDollars++; logger.i(TAG, "Increasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); }
|
Wallet extends ObservableImp { public void increaseMobileWallet() { if (canIncrease()) { mobileWalletDollars++; logger.i(TAG, "Increasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); void increaseMobileWallet(); void decreaseMobileWallet(); int getMobileWalletAmount(); int getSavingsWalletAmount(); boolean canIncrease(); boolean canDecrease(); }
|
Wallet extends ObservableImp { public void increaseMobileWallet() { if (canIncrease()) { mobileWalletDollars++; logger.i(TAG, "Increasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); void increaseMobileWallet(); void decreaseMobileWallet(); int getMobileWalletAmount(); int getSavingsWalletAmount(); boolean canIncrease(); boolean canDecrease(); final int totalDollarsAvailable; }
|
@Test public void testMediumText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(LONG_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(FIRST_LINE, wrappedLines.get(0)); Assert.assertEquals(SECOND_LINE, wrappedLines.get(1)); Assert.assertEquals(THIRD_LINE, wrappedLines.get(2)); Assert.assertEquals(3, wrappedLines.size()); }
|
public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); static final String SPACE; static final String EMPTY; }
|
@Test public void testSmallText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(SHORT_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(SHORT_TEXT, wrappedLines.get(0)); Assert.assertEquals(1, wrappedLines.size()); }
|
public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); static final String SPACE; static final String EMPTY; }
|
@Test public void testEmptyText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(EMPTY_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals("", wrappedLines.get(0)); Assert.assertEquals(1, wrappedLines.size()); }
|
public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); static final String SPACE; static final String EMPTY; }
|
@Test public void testSpaceText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(SPACE_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(SPACE_TEXT, wrappedLines.get(0)); Assert.assertEquals(1, wrappedLines.size()); }
|
public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); static final String SPACE; static final String EMPTY; }
|
@Test public void testLongSpaceText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(LONG_SPACE_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(SPACE_TEXT, wrappedLines.get(0)); Assert.assertEquals(1, wrappedLines.size()); }
|
public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); static final String SPACE; static final String EMPTY; }
|
@Test public void testShortText_tinyWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(SHORT_TEXT, TINY_CHARACTERS_AVAILABLE); Assert.assertEquals("h", wrappedLines.get(0)); Assert.assertEquals("e", wrappedLines.get(1)); Assert.assertEquals("l", wrappedLines.get(2)); Assert.assertEquals("l", wrappedLines.get(3)); Assert.assertEquals("o", wrappedLines.get(4)); Assert.assertEquals(5, wrappedLines.size()); }
|
public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); static final String SPACE; static final String EMPTY; }
|
@Test public void testLongTextWithLongWord_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(LONG_TEXT_LONG_WORD, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(FIRST_LINE, wrappedLines.get(0)); Assert.assertEquals("1", wrappedLines.get(1)); Assert.assertEquals("abcdefghijklmnopqrstuvwxyz0123456789abcd", wrappedLines.get(2)); Assert.assertEquals("efghijklmnopqrstuvwxyz0123456789 the", wrappedLines.get(3)); Assert.assertEquals("quick brown fox", wrappedLines.get(4)); Assert.assertEquals(5, wrappedLines.size()); }
|
public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); }
|
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); static final String SPACE; static final String EMPTY; }
|
@Test public void testAsInteger() throws Exception { Document document = XpathUtils.documentFrom(DOCUMENT); assertEquals((Integer) 1, XpathUtils.asInteger("Foo/Count", document)); assertEquals(null, XpathUtils.asInteger("Foo/Empty", document)); }
|
public static Integer asInteger(String expression, Node node) throws XPathExpressionException { String intString = evaluateAsString(expression, node); return (isEmptyString(intString)) ? null : Integer.valueOf(intString); }
|
XpathUtils { public static Integer asInteger(String expression, Node node) throws XPathExpressionException { String intString = evaluateAsString(expression, node); return (isEmptyString(intString)) ? null : Integer.valueOf(intString); } }
|
XpathUtils { public static Integer asInteger(String expression, Node node) throws XPathExpressionException { String intString = evaluateAsString(expression, node); return (isEmptyString(intString)) ? null : Integer.valueOf(intString); } }
|
XpathUtils { public static Integer asInteger(String expression, Node node) throws XPathExpressionException { String intString = evaluateAsString(expression, node); return (isEmptyString(intString)) ? null : Integer.valueOf(intString); } static Document documentFrom(InputStream is); static Document documentFrom(String xml); static Document documentFrom(URL url); static Double asDouble(String expression, Node node); static String asString(String expression, Node node); static Integer asInteger(String expression, Node node); static Boolean asBoolean(String expression, Node node); static Float asFloat(String expression, Node node); static Long asLong(String expression, Node node); static Byte asByte(String expression, Node node); static Date asDate(String expression, Node node); static ByteBuffer asByteBuffer(String expression, Node node); static boolean isEmpty(Node node); static int nodeLength(NodeList list); static Node asNode(String nodeName, Node node); static XPath xpath(); }
|
XpathUtils { public static Integer asInteger(String expression, Node node) throws XPathExpressionException { String intString = evaluateAsString(expression, node); return (isEmptyString(intString)) ? null : Integer.valueOf(intString); } static Document documentFrom(InputStream is); static Document documentFrom(String xml); static Document documentFrom(URL url); static Double asDouble(String expression, Node node); static String asString(String expression, Node node); static Integer asInteger(String expression, Node node); static Boolean asBoolean(String expression, Node node); static Float asFloat(String expression, Node node); static Long asLong(String expression, Node node); static Byte asByte(String expression, Node node); static Date asDate(String expression, Node node); static ByteBuffer asByteBuffer(String expression, Node node); static boolean isEmpty(Node node); static int nodeLength(NodeList list); static Node asNode(String nodeName, Node node); static XPath xpath(); }
|
@Test public void testAsBoolean() throws Exception { Document document = XpathUtils.documentFrom(DOCUMENT); assertEquals(true, XpathUtils.asBoolean("Foo/Enabled", document)); assertEquals(null, XpathUtils.asBoolean("Foo/Empty", document)); }
|
public static Boolean asBoolean(String expression, Node node) throws XPathExpressionException { String booleanString = evaluateAsString(expression, node); return (isEmptyString(booleanString)) ? null : Boolean.valueOf(booleanString); }
|
XpathUtils { public static Boolean asBoolean(String expression, Node node) throws XPathExpressionException { String booleanString = evaluateAsString(expression, node); return (isEmptyString(booleanString)) ? null : Boolean.valueOf(booleanString); } }
|
XpathUtils { public static Boolean asBoolean(String expression, Node node) throws XPathExpressionException { String booleanString = evaluateAsString(expression, node); return (isEmptyString(booleanString)) ? null : Boolean.valueOf(booleanString); } }
|
XpathUtils { public static Boolean asBoolean(String expression, Node node) throws XPathExpressionException { String booleanString = evaluateAsString(expression, node); return (isEmptyString(booleanString)) ? null : Boolean.valueOf(booleanString); } static Document documentFrom(InputStream is); static Document documentFrom(String xml); static Document documentFrom(URL url); static Double asDouble(String expression, Node node); static String asString(String expression, Node node); static Integer asInteger(String expression, Node node); static Boolean asBoolean(String expression, Node node); static Float asFloat(String expression, Node node); static Long asLong(String expression, Node node); static Byte asByte(String expression, Node node); static Date asDate(String expression, Node node); static ByteBuffer asByteBuffer(String expression, Node node); static boolean isEmpty(Node node); static int nodeLength(NodeList list); static Node asNode(String nodeName, Node node); static XPath xpath(); }
|
XpathUtils { public static Boolean asBoolean(String expression, Node node) throws XPathExpressionException { String booleanString = evaluateAsString(expression, node); return (isEmptyString(booleanString)) ? null : Boolean.valueOf(booleanString); } static Document documentFrom(InputStream is); static Document documentFrom(String xml); static Document documentFrom(URL url); static Double asDouble(String expression, Node node); static String asString(String expression, Node node); static Integer asInteger(String expression, Node node); static Boolean asBoolean(String expression, Node node); static Float asFloat(String expression, Node node); static Long asLong(String expression, Node node); static Byte asByte(String expression, Node node); static Date asDate(String expression, Node node); static ByteBuffer asByteBuffer(String expression, Node node); static boolean isEmpty(Node node); static int nodeLength(NodeList list); static Node asNode(String nodeName, Node node); static XPath xpath(); }
|
@Test public void testAsFloat() throws Exception { Document document = XpathUtils.documentFrom(DOCUMENT); assertEquals((Float) 0.0000071759f, XpathUtils.asFloat("Foo/Usage", document)); assertEquals(null, XpathUtils.asFloat("Foo/Empty", document)); }
|
public static Float asFloat(String expression, Node node) throws XPathExpressionException { String floatString = evaluateAsString(expression, node); return (isEmptyString(floatString)) ? null : Float.valueOf(floatString); }
|
XpathUtils { public static Float asFloat(String expression, Node node) throws XPathExpressionException { String floatString = evaluateAsString(expression, node); return (isEmptyString(floatString)) ? null : Float.valueOf(floatString); } }
|
XpathUtils { public static Float asFloat(String expression, Node node) throws XPathExpressionException { String floatString = evaluateAsString(expression, node); return (isEmptyString(floatString)) ? null : Float.valueOf(floatString); } }
|
XpathUtils { public static Float asFloat(String expression, Node node) throws XPathExpressionException { String floatString = evaluateAsString(expression, node); return (isEmptyString(floatString)) ? null : Float.valueOf(floatString); } static Document documentFrom(InputStream is); static Document documentFrom(String xml); static Document documentFrom(URL url); static Double asDouble(String expression, Node node); static String asString(String expression, Node node); static Integer asInteger(String expression, Node node); static Boolean asBoolean(String expression, Node node); static Float asFloat(String expression, Node node); static Long asLong(String expression, Node node); static Byte asByte(String expression, Node node); static Date asDate(String expression, Node node); static ByteBuffer asByteBuffer(String expression, Node node); static boolean isEmpty(Node node); static int nodeLength(NodeList list); static Node asNode(String nodeName, Node node); static XPath xpath(); }
|
XpathUtils { public static Float asFloat(String expression, Node node) throws XPathExpressionException { String floatString = evaluateAsString(expression, node); return (isEmptyString(floatString)) ? null : Float.valueOf(floatString); } static Document documentFrom(InputStream is); static Document documentFrom(String xml); static Document documentFrom(URL url); static Double asDouble(String expression, Node node); static String asString(String expression, Node node); static Integer asInteger(String expression, Node node); static Boolean asBoolean(String expression, Node node); static Float asFloat(String expression, Node node); static Long asLong(String expression, Node node); static Byte asByte(String expression, Node node); static Date asDate(String expression, Node node); static ByteBuffer asByteBuffer(String expression, Node node); static boolean isEmpty(Node node); static int nodeLength(NodeList list); static Node asNode(String nodeName, Node node); static XPath xpath(); }
|
@Test public void testAsByte() throws Exception { Document document = XpathUtils.documentFrom(DOCUMENT); assertEquals(new Byte((byte) 123), XpathUtils.asByte("Foo/PositiveByte", document)); assertEquals(new Byte((byte) -99), XpathUtils.asByte("Foo/NegativeByte", document)); assertEquals(null, XpathUtils.asByte("Foo/Empty", document)); }
|
public static Byte asByte(String expression, Node node) throws XPathExpressionException { String byteString = evaluateAsString(expression, node); return (isEmptyString(byteString)) ? null : Byte.valueOf(byteString); }
|
XpathUtils { public static Byte asByte(String expression, Node node) throws XPathExpressionException { String byteString = evaluateAsString(expression, node); return (isEmptyString(byteString)) ? null : Byte.valueOf(byteString); } }
|
XpathUtils { public static Byte asByte(String expression, Node node) throws XPathExpressionException { String byteString = evaluateAsString(expression, node); return (isEmptyString(byteString)) ? null : Byte.valueOf(byteString); } }
|
XpathUtils { public static Byte asByte(String expression, Node node) throws XPathExpressionException { String byteString = evaluateAsString(expression, node); return (isEmptyString(byteString)) ? null : Byte.valueOf(byteString); } static Document documentFrom(InputStream is); static Document documentFrom(String xml); static Document documentFrom(URL url); static Double asDouble(String expression, Node node); static String asString(String expression, Node node); static Integer asInteger(String expression, Node node); static Boolean asBoolean(String expression, Node node); static Float asFloat(String expression, Node node); static Long asLong(String expression, Node node); static Byte asByte(String expression, Node node); static Date asDate(String expression, Node node); static ByteBuffer asByteBuffer(String expression, Node node); static boolean isEmpty(Node node); static int nodeLength(NodeList list); static Node asNode(String nodeName, Node node); static XPath xpath(); }
|
XpathUtils { public static Byte asByte(String expression, Node node) throws XPathExpressionException { String byteString = evaluateAsString(expression, node); return (isEmptyString(byteString)) ? null : Byte.valueOf(byteString); } static Document documentFrom(InputStream is); static Document documentFrom(String xml); static Document documentFrom(URL url); static Double asDouble(String expression, Node node); static String asString(String expression, Node node); static Integer asInteger(String expression, Node node); static Boolean asBoolean(String expression, Node node); static Float asFloat(String expression, Node node); static Long asLong(String expression, Node node); static Byte asByte(String expression, Node node); static Date asDate(String expression, Node node); static ByteBuffer asByteBuffer(String expression, Node node); static boolean isEmpty(Node node); static int nodeLength(NodeList list); static Node asNode(String nodeName, Node node); static XPath xpath(); }
|
@Test public void testAsDate() throws Exception { Calendar expectedDate = new GregorianCalendar(); expectedDate.set(Calendar.YEAR, 2008); expectedDate.set(Calendar.MONTH, Calendar.OCTOBER); expectedDate.set(Calendar.DAY_OF_MONTH, 7); expectedDate.set(Calendar.AM_PM, Calendar.AM); expectedDate.set(Calendar.HOUR, 11); expectedDate.set(Calendar.MINUTE, 51); expectedDate.set(Calendar.SECOND, 50); expectedDate.set(Calendar.MILLISECOND, 0); expectedDate.setTimeZone(new SimpleTimeZone(0, "UTC")); Document document = XpathUtils.documentFrom(DOCUMENT); Date date = XpathUtils.asDate("Foo/Since", document); assertNotNull(date); assertEquals(expectedDate.getTimeInMillis(), date.getTime()); assertEquals(null, XpathUtils.asDate("Foo/Empty", document)); }
|
public static Date asDate(String expression, Node node) throws XPathExpressionException { String dateString = evaluateAsString(expression, node); if (isEmptyString(dateString)) return null; return DateUtils.parseISO8601Date(dateString); }
|
XpathUtils { public static Date asDate(String expression, Node node) throws XPathExpressionException { String dateString = evaluateAsString(expression, node); if (isEmptyString(dateString)) return null; return DateUtils.parseISO8601Date(dateString); } }
|
XpathUtils { public static Date asDate(String expression, Node node) throws XPathExpressionException { String dateString = evaluateAsString(expression, node); if (isEmptyString(dateString)) return null; return DateUtils.parseISO8601Date(dateString); } }
|
XpathUtils { public static Date asDate(String expression, Node node) throws XPathExpressionException { String dateString = evaluateAsString(expression, node); if (isEmptyString(dateString)) return null; return DateUtils.parseISO8601Date(dateString); } static Document documentFrom(InputStream is); static Document documentFrom(String xml); static Document documentFrom(URL url); static Double asDouble(String expression, Node node); static String asString(String expression, Node node); static Integer asInteger(String expression, Node node); static Boolean asBoolean(String expression, Node node); static Float asFloat(String expression, Node node); static Long asLong(String expression, Node node); static Byte asByte(String expression, Node node); static Date asDate(String expression, Node node); static ByteBuffer asByteBuffer(String expression, Node node); static boolean isEmpty(Node node); static int nodeLength(NodeList list); static Node asNode(String nodeName, Node node); static XPath xpath(); }
|
XpathUtils { public static Date asDate(String expression, Node node) throws XPathExpressionException { String dateString = evaluateAsString(expression, node); if (isEmptyString(dateString)) return null; return DateUtils.parseISO8601Date(dateString); } static Document documentFrom(InputStream is); static Document documentFrom(String xml); static Document documentFrom(URL url); static Double asDouble(String expression, Node node); static String asString(String expression, Node node); static Integer asInteger(String expression, Node node); static Boolean asBoolean(String expression, Node node); static Float asFloat(String expression, Node node); static Long asLong(String expression, Node node); static Byte asByte(String expression, Node node); static Date asDate(String expression, Node node); static ByteBuffer asByteBuffer(String expression, Node node); static boolean isEmpty(Node node); static int nodeLength(NodeList list); static Node asNode(String nodeName, Node node); static XPath xpath(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.