src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ResourceBundleUiMessageSource implements IUiMessageSource { @Override public String getMessage(String key, Locale locale) { ResourceBundle bundle = getBundle(locale); if (bundle.containsKey(key)) { return bundle.getString(key); } return "{{ message missing: " + key + "}}"; } ResourceBundleUiMessageSource(String baseName); @Override String getMessage(String key, Locale locale); @Override String getMessage(String key, Object[] args, Locale locale); }
@Test public void testGetMessageStringLocale() { String message = instance.getMessage("message.key", new Locale("de")); assertNotNull(message); assertEquals("Hier ein kleiner Text um die Sache zu erläutern.", message); } @Test public void testGetMessageStringLocaleDefault() { String message = instance.getMessage("message.default", new Locale("en")); assertNotNull(message); assertEquals("Dieser Text steht nur in deutsch", message); } @Test public void testGetMessageStringObjectArrayLocale() { String message = instance.getMessage("message.args", new Object[] {"PARAM"}, new Locale("de")); assertNotNull(message); assertEquals("Hier eine Nachricht mit Parametern... PARAM wurde eingegeben.", message); }
MethodHandler implements TargetHandler { @Override public String getTargetNamespace() { return "urn:org.vaadin.mvp.uibinder.method"; } MethodHandler(ComponentHandler ch); @Override String getTargetNamespace(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); }
@Test public void getTargetNamespace() { assertEquals("urn:org.vaadin.mvp.uibinder.method", instance.getTargetNamespace()); }
MethodHandler implements TargetHandler { @Override public void handleElementOpen(String uri, String name) { method = findMethod(ch.getCurrent().getClass(), name); if (method == null) { throw new IllegalArgumentException("The method " + name + " is missing in " + ch.getCurrent().getClass()); } ch.setCurrentMethod(method); } MethodHandler(ComponentHandler ch); @Override String getTargetNamespace(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); }
@Test public void handleElementOpen() { instance.handleElementOpen("", "addComponent"); Method m = ch.getCurrentMethod(); assertNotNull(m); assertEquals("addComponent", m.getName()); assertEquals(1, m.getParameterTypes().length); } @Test (expected = IllegalArgumentException.class) public void handleElementOpenFail() { instance.handleElementOpen("", "nirvanaMethod"); }
MethodHandler implements TargetHandler { protected Method findMethod(Class<?> clazz, String name) { Class<?> searchType = clazz; while (searchType != null) { Method[] methods = (searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods()); for (Method method : methods) { if (name.equals(method.getName()) && method.getParameterTypes().length == 1 && Component.class.isAssignableFrom(method.getParameterTypes()[0])) { return method; } } searchType = searchType.getSuperclass(); } return null; } MethodHandler(ComponentHandler ch); @Override String getTargetNamespace(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); }
@Test public void findMethod() throws SecurityException, NoSuchMethodException { Method m = instance.findMethod(VerticalLayout.class, "addComponent"); assertNotNull(m); assertEquals("addComponent", m.getName()); assertEquals(1, m.getParameterTypes().length); } @Test public void findMethodNotFound() throws SecurityException, NoSuchMethodException { Method m = instance.findMethod(VerticalLayout.class, "nirvanaMethod"); assertNull(m); }
ComponentHandler implements TargetHandler { protected Method findApplicableSetterMethod(Object target, String propertyName, Object value) { String methodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); Method[] methods = target.getClass().getMethods(); if (value.getClass().isArray()) { } else { Method method = MethodUtils.getAccessibleMethod(target.getClass(), methodName, value.getClass()); if (method != null) { return method; } for (Method m : methods) { if (!m.getName().equals(methodName)) { continue; } Class<?>[] parameterTypes = m.getParameterTypes(); if (parameterTypes.length != 1) { continue; } Class<?> mpt = parameterTypes[0]; if (mpt.isAssignableFrom(value.getClass())) { return m; } Converter converter = ConvertUtils.lookup(mpt); if (converter != null) { return m; } } } if (value == null || value.toString().length() == 0) { for (Method m : methods) { if (m.getName().equals(methodName) && m.getParameterTypes().length == 0) { return m; } } } return null; } ComponentHandler(UiBinder uiBinder, Component view, Locale locale); IEventBinder getEventBinder(); void setEventBinder(IEventBinder eventBinder); @Override String getTargetNamespace(); Component getRootComponent(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); Component getCurrent(); void setCurrentMethod(Method currentMethod); }
@Test public void testFindApplicableSetterMethodStringArg() throws SecurityException, NoSuchMethodException { Method m = instance.findApplicableSetterMethod(bean, "height", "67%"); assertEquals("wrong setter selected", VerticalLayout.class.getMethod("setHeight", String.class), m); } @Ignore("Currently not supported, introduce expressions, e.g. MVEL to support this.") @Test public void testFindApplicableSetterMethodFloatIntArg() throws SecurityException, NoSuchMethodException { Method m = instance.findApplicableSetterMethod(bean, "height", "67, #UNITS_PERCENTAGE"); assertEquals("wrong setter selected", VerticalLayout.class.getMethod("setHeight", float.class, int.class), m); } @Test public void testFindApplicableSetterMethodNoArg() throws SecurityException, NoSuchMethodException { Method m = instance.findApplicableSetterMethod(bean, "sizeFull", ""); assertEquals("wrong setter selected", VerticalLayout.class.getMethod("setSizeFull"), m); }
ComponentHandler implements TargetHandler { protected String namespaceUriToPackageName(String uri) throws UiConstraintException { if (packages.containsKey(uri)) { return packages.get(uri); } try { URI nsUri = new URI(uri); String pkg = null; String scheme = nsUri.getScheme(); if ("urn".equals(scheme)) { pkg = nsUri.getSchemeSpecificPart(); } else if ("http".equals(scheme)) { String[] hostParts = nsUri.getHost().split("\\."); String[] pathParts = nsUri.getPath().substring(1).split("/"); StringBuilder sb = new StringBuilder(); List<String> list = new ArrayList<String>(Arrays.asList(hostParts)); Collections.reverse(list); list.addAll(Arrays.asList(pathParts)); if (list.size() > 0) { sb.append(list.get(0)); for (int i = 1; i < list.size(); i++) { sb.append(".").append(list.get(i)); } } pkg = sb.toString(); } else { throw new UiConstraintException("Unsupported namespace URI scheme: " + scheme + " (URI = " + uri + ")"); } if (pkg.startsWith("import:")) { pkg = pkg.substring("import:".length()); } packages.put(uri, pkg); return pkg; } catch (URISyntaxException e) { throw new UiConstraintException("Invalid namespace URI", e); } } ComponentHandler(UiBinder uiBinder, Component view, Locale locale); IEventBinder getEventBinder(); void setEventBinder(IEventBinder eventBinder); @Override String getTargetNamespace(); Component getRootComponent(); @Override void handleElementOpen(String uri, String name); @Override void handleElementClose(); @Override void handleAttribute(String name, Object value); Component getCurrent(); void setCurrentMethod(Method currentMethod); }
@Test public void testNamespaceUriToPackageName() throws UiConstraintException { String pkg = instance.namespaceUriToPackageName("urn:import:org.vaadin.test"); assertEquals("invalid conversion of namespace to package", "org.vaadin.test", pkg); } @Test public void testNamespaceUriToPackageNameHttp() throws UiConstraintException { String pkg = instance.namespaceUriToPackageName("http: assertEquals("invalid conversion of namespace to package", "org.vaadin.test.some.pkg", pkg); }
EventBusManager { public <T extends EventBus> T getEventBus(Class<T> busType) { if (isPrivateEventBus(busType)) { throw new IllegalArgumentException("The bus " + busType + " is marked as private and it can be retrieved only from his presenter"); } assertEventBus(busType); EventBus eventBus = eventBusses.get(busType); return busType.cast(eventBus); } EventBusManager(); T register(Class<T> busType, Object subscriber); T register(Class<T> busType, Object subscriber,EventBus parentEventBus); void addSubscriber(Object subscriber); T getEventBus(Class<T> busType); }
@Test(expected = IllegalArgumentException.class) public void testGetEventBus_privateEventBus_NotSupported() { eventBusManager.getEventBus(StubPrivateEventBus.class); } @Test public void testGetEventBus_NonPrivateEventBus_Supported() { eventBusManager.getEventBus(StubEventBus.class); }
EventBusManager { public <T extends EventBus> T register(Class<T> busType, Object subscriber) { return this.register(busType,subscriber,null); } EventBusManager(); T register(Class<T> busType, Object subscriber); T register(Class<T> busType, Object subscriber,EventBus parentEventBus); void addSubscriber(Object subscriber); T getEventBus(Class<T> busType); }
@Test public void testRegister_NonPrivateEventBus_mustReturnSameBus() { EventBus eventBus = eventBusManager.register(StubEventBus.class,new Object()); EventBus eventBus2 = eventBusManager.register(StubEventBus.class,new Object()); Assert.assertSame("Different event bus instances",eventBus,eventBus2); } @Test public void testRegister_NonPrivateEventBus_mustReturnDifferentBus() { EventBus eventBus = eventBusManager.register(StubPrivateEventBus.class,new Object()); EventBus eventBus2 = eventBusManager.register(StubPrivateEventBus.class,new Object()); Assert.assertNotSame("Same event bus instances",eventBus,eventBus2); }
EventBusHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("toString".equals(method.getName())) { return "EventBus<" + busName + ">"; } logger.info("Event received: {}", method.getName()); Event eventDef = method.getAnnotation(Event.class); logger.info("Event annotation: {}", eventDef); boolean localHandlerMethodFound = false; final boolean fallbackOnParent = parent != null; String eventName = method.getName(); String eventHandlerName = buildExpectedEventHandlerMethodName(eventName); Class<?>[] handlerTypes = eventDef.handlers(); for (Class<?> handlerType : handlerTypes) { Object handler = handlerRegistry.lookupReceiver(handlerType); if (handler == null) { logger.info("Handler {} not registered", handlerType.getName()); continue; } Method handlerMethod = lookupHandlerMethod(method, eventName, eventHandlerName, handler); if (handlerMethod == null) { continue; } try { localHandlerMethodFound = true; handlerMethod.invoke(handler, args); } catch (Exception e) { logger.debug("Failed to propagate event {} to handler {}", eventName, handlerType.getName()); throw new RuntimeException("During the invocations of the handler method an exception has occurred",e); } } if (!localHandlerMethodFound && fallbackOnParent) { delegateToParent(method.getName(),method.getParameterTypes(), args); } return null; } EventBusHandler(IEventReceiverRegistry hr, String name); EventBusHandler(IEventReceiverRegistry hr, String name, EventBus parent); @Override Object invoke(Object proxy, Method method, Object[] args); }
@Test public void testParentFallbackEventsDelivery_notExistingEventOnChildWillBeForwarded() throws Exception{ StubPrivateEventBus parentEventBus = createNiceMock(StubPrivateEventBus.class); parentEventBus.niceEvent(); replay(mainEventReceiverRegistry, parentEventBus); StubEventBus eventBus = EventBusHandlerProxyFactory.createEventBusHandler(StubEventBus.class, mainEventReceiverRegistry,parentEventBus); Class<? extends EventBus> eventBusType = eventBus.getClass(); Method method = eventBusType.getMethod("niceEvent"); method.invoke(eventBus); verify(mainEventReceiverRegistry,parentEventBus); } @Test(expected = Exception.class) public void testParentFallbackEventsDelivery_notExistingEventOnChildWillBeForwarded_exceptionIsThrown() throws Exception{ StubPrivateEventBus parentEventBus = createNiceMock(StubPrivateEventBus.class); parentEventBus.niceEvent(); expectLastCall().andThrow(new RuntimeException()); replay(mainEventReceiverRegistry, parentEventBus); StubEventBus eventBus = EventBusHandlerProxyFactory.createEventBusHandler(StubEventBus.class, mainEventReceiverRegistry,parentEventBus); Class<? extends EventBus> eventBusType = eventBus.getClass(); Method method = eventBusType.getMethod("niceEvent"); method.invoke(eventBus); verify(mainEventReceiverRegistry,parentEventBus); }
SpringPresenterFactory extends AbstractPresenterFactory implements ApplicationContextAware { @SuppressWarnings("unchecked") public IPresenter<?, ? extends EventBus> create(Object name,EventBus parentEventBus) { if (!(name instanceof String)) { throw new IllegalArgumentException("Argument is expected to be a bean name (string)"); } String beanName = (String) name; if (applicationContext.containsBean(beanName)) { IPresenter p = applicationContext.getBean(beanName, IPresenter.class); p.setApplication(application); p.setMessageSource(messageSource); Presenter def = p.getClass().getAnnotation(Presenter.class); if (def == null) { throw new IllegalArgumentException("Missing @Presenter annotation on bean '" + beanName + "'"); } EventBus eventBus = createEventBus((Class<IPresenter>) p.getClass(), p,parentEventBus); p.setEventBus(eventBus); try { Object view = viewFactory.createView(eventBusManager, p, def.view(), locale); p.setView(view); } catch (ViewFactoryException e) { logger.error("Failed to create view for presenter", e); } p.bind(); return p; } throw new IllegalArgumentException("No presenter is defined for name: " + name); } @Override void setApplicationContext(ApplicationContext applicationContext); @SuppressWarnings("unchecked") IPresenter<?, ? extends EventBus> create(Object name,EventBus parentEventBus); @Override IViewFactory getViewFactory(); }
@Test public void testCreate() { IPresenter<?, ? extends EventBus> presenter = instance.createPresenter("spring"); assertNotNull("created presenter is null", presenter); assertNotNull("presenters view is null", presenter.getView()); assertTrue("presenters bind() method has not been called", ((SpringPresenter)presenter).bound); assertNotNull("presenter eventbus is null", presenter.getEventBus()); }
EventDeserializer extends AbstractAttributeStoreDeserializer<BaseEvent, EventBuilder> { @Override public BaseEvent build(EventBuilder entityBuilder) { return (BaseEvent) entityBuilder.build(); } @Override EventBuilder deserialize(JsonNode root); @Override BaseEvent build(EventBuilder entityBuilder); }
@Test public void testBasicDeserialization() throws Exception { Event event = create("type", "id", 0) .attr("key", "value") .attr("key1", "valu1") .build(); String json = objectMapper.writeValueAsString(event); Event actualEntity = objectMapper.readValue(json, Event.class); assertEquals(actualEntity.getId(), event.getId()); assertEquals(actualEntity.getTimestamp(), event.getTimestamp()); assertEquals(new HashSet<>(actualEntity.getAttributes()), new HashSet<>(event.getAttributes())); } @Test public void testBasicDeserialization2() throws Exception { Event event = create("type", "id", currentTimeMillis()) .attr("key", "value") .attr("key1", "valu1") .build(); String json = objectMapper.writeValueAsString(event); Event actualEntity = objectMapper.readValue(json, Event.class); assertEquals(actualEntity.getId(), event.getId()); assertEquals(actualEntity.getTimestamp(), event.getTimestamp()); assertEquals(new HashSet<>(actualEntity.getAttributes()), new HashSet<>(event.getAttributes())); }
CloseableIterators { public static <T> CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize) { return wrap(Iterators.limit(iterator, limitSize), iterator); } private CloseableIterators(); static CloseableIterator<T> fromStream(Stream<T> stream); static CloseableIterator<T> fromIterator(Iterator<T> iterator); static CloseableIterator<T> distinct(final CloseableIterator<T> iterator); static CloseableIterator<List<T>> groupBy(final CloseableIterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); static CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators); @SuppressWarnings("unchecked") static CloseableIterator<T> emptyIterator(); static CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter); static CloseableIterator<T> filter(final CloseableIterator<?> iterator, final Class<T> type); static CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize); static CloseableIterator<List<T>> paddedParition(final CloseableIterator<T> iterator, final int size); static CloseableIterator<List<T>> partition(final CloseableIterator<T> iterator, final int size); static PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator); static CloseableIterator<T> singletonIterator(T value); static CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function); @SafeVarargs static CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators); static CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator); static CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator); @Deprecated static CloseableIterator<T> wrap(final Iterator<T> iterator); }
@Test public void testLimit() { CloseableIterator<Integer> firstThree = limit(testIterator(), 3); assertTrue(elementsEqual(asList(1, 2, 3).iterator(), firstThree)); assertFalse(firstThree.hasNext()); firstThree.close(); }
CloseableIterators { public static <T> CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter) { return wrap(Iterators.filter(iterator, filter::test), iterator); } private CloseableIterators(); static CloseableIterator<T> fromStream(Stream<T> stream); static CloseableIterator<T> fromIterator(Iterator<T> iterator); static CloseableIterator<T> distinct(final CloseableIterator<T> iterator); static CloseableIterator<List<T>> groupBy(final CloseableIterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); static CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators); @SuppressWarnings("unchecked") static CloseableIterator<T> emptyIterator(); static CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter); static CloseableIterator<T> filter(final CloseableIterator<?> iterator, final Class<T> type); static CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize); static CloseableIterator<List<T>> paddedParition(final CloseableIterator<T> iterator, final int size); static CloseableIterator<List<T>> partition(final CloseableIterator<T> iterator, final int size); static PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator); static CloseableIterator<T> singletonIterator(T value); static CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function); @SafeVarargs static CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators); static CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator); static CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator); @Deprecated static CloseableIterator<T> wrap(final Iterator<T> iterator); }
@Test public void testFilter() { CloseableIterator<Integer> odd = filter(testIterator(), input -> input % 2 == 0); assertTrue(elementsEqual(asList(2, 4).iterator(), odd)); assertFalse(odd.hasNext()); odd.close(); }
CloseableIterators { public static <T> CloseableIterator<T> distinct(final CloseableIterator<T> iterator) { return wrap(Iterators2.distinct(iterator), iterator); } private CloseableIterators(); static CloseableIterator<T> fromStream(Stream<T> stream); static CloseableIterator<T> fromIterator(Iterator<T> iterator); static CloseableIterator<T> distinct(final CloseableIterator<T> iterator); static CloseableIterator<List<T>> groupBy(final CloseableIterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); static CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators); @SuppressWarnings("unchecked") static CloseableIterator<T> emptyIterator(); static CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter); static CloseableIterator<T> filter(final CloseableIterator<?> iterator, final Class<T> type); static CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize); static CloseableIterator<List<T>> paddedParition(final CloseableIterator<T> iterator, final int size); static CloseableIterator<List<T>> partition(final CloseableIterator<T> iterator, final int size); static PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator); static CloseableIterator<T> singletonIterator(T value); static CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function); @SafeVarargs static CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators); static CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator); static CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator); @Deprecated static CloseableIterator<T> wrap(final Iterator<T> iterator); }
@Test public void testDistinct() { CloseableIterator<Integer> distinct = distinct(fromIterator(asList(1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7).iterator())); assertTrue(elementsEqual(asList(1, 2, 3, 4, 5, 6, 7).iterator(), distinct)); assertFalse(distinct.hasNext()); distinct.close(); }
CloseableIterators { @SafeVarargs public static <T> CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators) { return chain(Iterators.forArray(iterators)); } private CloseableIterators(); static CloseableIterator<T> fromStream(Stream<T> stream); static CloseableIterator<T> fromIterator(Iterator<T> iterator); static CloseableIterator<T> distinct(final CloseableIterator<T> iterator); static CloseableIterator<List<T>> groupBy(final CloseableIterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); static CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators); @SuppressWarnings("unchecked") static CloseableIterator<T> emptyIterator(); static CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter); static CloseableIterator<T> filter(final CloseableIterator<?> iterator, final Class<T> type); static CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize); static CloseableIterator<List<T>> paddedParition(final CloseableIterator<T> iterator, final int size); static CloseableIterator<List<T>> partition(final CloseableIterator<T> iterator, final int size); static PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator); static CloseableIterator<T> singletonIterator(T value); static CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function); @SafeVarargs static CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators); static CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator); static CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator); @Deprecated static CloseableIterator<T> wrap(final Iterator<T> iterator); }
@SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testChain() { CloseableIterator iterator = chain(emptyIterator(), emptyIterator(), emptyIterator()); assertFalse(iterator.hasNext()); try { iterator.next(); fail(); } catch (NoSuchElementException ignored) { } iterator.close(); iterator = chain(fromIterator(asList(1).iterator())); try { assertTrue(iterator.hasNext()); iterator.next(); } catch (NoSuchElementException ex) { fail("should not throw NoSuchElementException here"); } finally { iterator.closeQuietly(); } iterator.close(); iterator = chain( fromIterator(asList(1, 2).iterator()), fromIterator(asList(3, 4).iterator()), fromIterator(asList(5, 6).iterator())); assertTrue(iterator.hasNext()); assertTrue(Iterators.elementsEqual(asList(1, 2, 3, 4, 5, 6).iterator(), iterator)); assertFalse(iterator.hasNext()); iterator.close(); }
CloseableIterators { public static <T> CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator) { requireNonNull(iterator); return new CloseableIterator<T>() { private boolean closed = false; @Override public void close() { if (closed) return; closed = true; iterator.close(); } @Override public boolean hasNext() { try { if (closed) return false; if (!iterator.hasNext()) { closeQuietly(); return false; } return true; } catch (RuntimeException re) { closeQuietly(); throw re; } } @Override public T next() { if (!closed) { try { return iterator.next(); } catch (RuntimeException re) { closeQuietly(); throw re; } } throw new NoSuchElementException(); } @Override public void remove() { if (!closed) { try { iterator.remove(); } catch (RuntimeException re) { closeQuietly(); throw re; } } throw new IllegalStateException(); } }; } private CloseableIterators(); static CloseableIterator<T> fromStream(Stream<T> stream); static CloseableIterator<T> fromIterator(Iterator<T> iterator); static CloseableIterator<T> distinct(final CloseableIterator<T> iterator); static CloseableIterator<List<T>> groupBy(final CloseableIterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); static CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators); @SuppressWarnings("unchecked") static CloseableIterator<T> emptyIterator(); static CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter); static CloseableIterator<T> filter(final CloseableIterator<?> iterator, final Class<T> type); static CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize); static CloseableIterator<List<T>> paddedParition(final CloseableIterator<T> iterator, final int size); static CloseableIterator<List<T>> partition(final CloseableIterator<T> iterator, final int size); static PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator); static CloseableIterator<T> singletonIterator(T value); static CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function); @SafeVarargs static CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators); static CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator); static CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator); @Deprecated static CloseableIterator<T> wrap(final Iterator<T> iterator); }
@Test public void testAutoClose() { MockIterator<Integer> iterator = testIterator(); CloseableIterator<Integer> closeableIterator = autoClose(iterator); closeableIterator.close(); assertTrue(iterator.isClosed()); iterator = testIterator(); closeableIterator = autoClose(iterator); Iterators.size(closeableIterator); assertTrue(iterator.isClosed()); iterator = testExceptionThrowingIterator(); closeableIterator = autoClose(iterator); try { closeableIterator.next(); fail(); } catch (RuntimeException ignored) { } assertTrue(iterator.isClosed()); iterator = testIterator(); closeableIterator = autoClose(iterator); closeableIterator.close(); try { closeableIterator.next(); } catch (NoSuchElementException ignored) { } assertTrue(iterator.isClosed()); iterator = testExceptionThrowingIterator(); closeableIterator = autoClose(iterator); try { closeableIterator.remove(); fail(); } catch (RuntimeException ignored) { } assertTrue(iterator.isClosed()); iterator = testIterator(); closeableIterator = autoClose(iterator); closeableIterator.close(); try { closeableIterator.remove(); } catch (IllegalStateException ignored) { } assertTrue(iterator.isClosed()); }
CloseableIterables { @SuppressWarnings("unchecked") public static <T> CloseableIterable<T> emptyIterable() { return EMPTY_ITERABLE; } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }
@Test public void testCloseEmptyMultipleTimes() { CloseableIterable<Integer> iterable = CloseableIterables.emptyIterable(); iterable.iterator(); iterable.closeQuietly(); iterable = CloseableIterables.emptyIterable(); iterable.iterator(); iterable.closeQuietly(); }
CloseableIterables { @Deprecated public static <T> CloseableIterable<T> wrap(final Iterable<T> iterable) { return fromIterable(iterable); } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }
@Test public void testWrap() { CloseableIterable<Integer> wrapped = CloseableIterables.fromIterable(asList(1, 2, 3, 4, 5)); assertTrue(elementsEqual(asList(1, 2, 3, 4, 5), wrapped)); wrapped.close(); try { wrapped.iterator(); fail(); } catch (IllegalStateException ignored) { } }
CloseableIterables { public static <F, T> CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function) { return wrap(Iterables.transform(iterable, function::apply), iterable); } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }
@Test public void testTransform() { CloseableIterable<Integer> addOne = transform(testIterable(), input -> input + 1); CloseableIterable<Integer> multTen = transform(addOne, input -> input * 10); assertTrue(elementsEqual(asList(20, 30, 40, 50, 60), multTen)); multTen.close(); try { multTen.iterator(); fail(); } catch (IllegalStateException ignored) { } }
CloseableIterables { public static <T> CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize) { return wrap(Iterables.limit(iterable, limitSize), iterable); } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }
@Test public void testLimit() { CloseableIterable<Integer> firstThree = limit(testIterable(), 3); assertEquals(3, Iterables.size(firstThree)); assertTrue(elementsEqual(asList(1, 2, 3), firstThree)); firstThree.close(); try { firstThree.iterator(); fail(); } catch (IllegalStateException ignored) { } }
CloseableIterables { public static <T> CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type) { return wrap(Iterables.filter(iterable, type), iterable); } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }
@Test public void testFilter() { CloseableIterable<Integer> odd = filter(testIterable(), input -> input % 2 == 0); assertTrue(elementsEqual(asList(2, 4), odd)); odd.close(); try { odd.iterator(); fail(); } catch (IllegalStateException ignored) { } }
CloseableIterables { public static <T> CloseableIterable<T> distinct(final CloseableIterable<T> iterable) { return wrap(Iterables2.distinct(iterable), iterable); } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }
@Test public void testDistinct() { CloseableIterable<Integer> distinct = distinct(fromIterable(asList(1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7))); assertEquals(7, Iterables.size(distinct)); assertTrue(elementsEqual(asList(1, 2, 3, 4, 5, 6, 7), distinct)); distinct.close(); try { distinct.iterator(); fail(); } catch (IllegalStateException ignored) { } }
CloseableIterables { public static <T> CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable) { requireNonNull(iterable); return new FluentCloseableIterable<T>() { @Override protected void doClose() { iterable.close(); } @Override protected Iterator<T> retrieveIterator() { return CloseableIterators.autoClose( CloseableIterators.wrap(iterable.iterator(), iterable) ); } }; } private CloseableIterables(); static CloseableIterable<T> fromStream(Stream<T> stream); static CloseableIterable<T> fromIterable(Iterable<T> iterable); static CloseableIterable<T> distinct(final CloseableIterable<T> iterable); static CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); static CloseableIterable<T> concat(final CloseableIterable<? extends Iterable<? extends T>> inputs); static CloseableIterable<T> cycle(final CloseableIterable<T> iterable); static CloseableIterable<T> filter(final CloseableIterable<?> iterable, final Class<T> type); static CloseableIterable<T> filter(final CloseableIterable<T> iterable, final Predicate<? super T> filter); static CloseableIterable<T> limit(final CloseableIterable<T> iterable, final int limitSize); static CloseableIterable<List<T>> paddedParition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<List<T>> partition(final CloseableIterable<T> iterable, final int size); static CloseableIterable<T> skip(final CloseableIterable<T> iterable, final int numberToSkip); static CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function); @SafeVarargs static CloseableIterable<T> chain(CloseableIterable<? extends T>... iterables); static CloseableIterable<T> chain(final Iterable<? extends CloseableIterable<? extends T>> iterables); static CloseableIterable<T> autoClose(final CloseableIterable<? extends T> iterable); @SuppressWarnings("unchecked") static CloseableIterable<T> emptyIterable(); static CloseableIterable<T> singleton(T value); @Deprecated static CloseableIterable<T> wrap(final Iterable<T> iterable); }
@Test public void testAutoClose() { MockIterable<Integer> iterable = testIterable(); CloseableIterable<Integer> closeableIterable = autoClose(iterable); closeableIterable.close(); assertTrue(iterable.isClosed()); iterable = testIterable(); closeableIterable = autoClose(iterable); Iterator<Integer> iterator = closeableIterable.iterator(); Iterators.size(iterator); assertTrue(iterable.isClosed()); iterable = testExceptionThrowingIterable(); closeableIterable = autoClose(iterable); iterator = closeableIterable.iterator(); try { iterator.next(); fail(); } catch (RuntimeException ignored) { } assertTrue(iterable.isClosed()); }
FluentCloseableIterable extends AbstractCloseableIterable<T> { public final FluentCloseableIterable<T> limit(int size) { return from(CloseableIterables.limit(this, size)); } protected FluentCloseableIterable(); static FluentCloseableIterable<E> from(final CloseableIterable<E> iterable); final FluentCloseableIterable<T> autoClose(); @Override String toString(); final int size(); final boolean contains(Object target); final FluentCloseableIterable<T> cycle(); final FluentCloseableIterable<T> append(Iterable<? extends T> other); @SafeVarargs final FluentCloseableIterable<T> append(T... elements); final FluentCloseableIterable<T> filter(Predicate<? super T> predicate); final FluentCloseableIterable<E> filter(Class<E> type); final boolean anyMatch(Predicate<? super T> predicate); final boolean allMatch(Predicate<? super T> predicate); final Optional<T> firstMatch(Predicate<? super T> predicate); final FluentCloseableIterable<E> transform(Function<? super T, ? extends E> function); final FluentCloseableIterable<E> transformAndConcat(Function<? super T, ? extends Iterable<E>> function); final Optional<T> first(); final Optional<T> last(); final FluentCloseableIterable<T> skip(int numberToSkip); final FluentCloseableIterable<T> limit(int size); final boolean isEmpty(); final ImmutableList<T> toList(); final ImmutableList<T> toSortedList(Comparator<? super T> comparator); final ImmutableSet<T> toSet(); final ImmutableSortedSet<T> toSortedSet(Comparator<? super T> comparator); final ImmutableMultiset<T> toMultiset(); final ImmutableMap<T, V> toMap(Function<? super T, V> valueFunction); final ImmutableListMultimap<K, T> index(Function<? super T, K> keyFunction); final ImmutableMap<K, T> uniqueIndex(Function<? super T, K> keyFunction); final T[] toArray(Class<T> type); final C copyInto(C collection); final String join(Joiner joiner); final T get(int position); final Iterable<T> toSimpleIterable(); }
@Test public void testLimit() { CloseableIterable<Integer> closeableIterable = fromIterable(asList(1, 2, 3, 4, 5)); FluentCloseableIterable<Integer> limit = FluentCloseableIterable. from(closeableIterable).limit(3); assertEquals(3, Iterables.size(limit)); limit.close(); }
Iterators2 { public static <T> Iterator<T> distinct(final Iterator<T> iterator) { requireNonNull(iterator); return new AbstractIterator<T>() { private final PeekingIterator<T> peekingIterator = peekingIterator(iterator); private T curr = null; @Override protected T computeNext() { while (peekingIterator.hasNext() && Objects.equals(curr, peekingIterator.peek())) { peekingIterator.next(); } if (!peekingIterator.hasNext()) return endOfData(); curr = peekingIterator.next(); return curr; } }; } private Iterators2(); static Iterator<T> distinct(final Iterator<T> iterator); static Iterator<List<T>> groupBy(final Iterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); }
@Test public void distinctTest() throws Exception { Iterator<Integer> distinct = distinct(asList(1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7).iterator()); assertTrue(elementsEqual(asList(1, 2, 3, 4, 5, 6, 7).iterator(), distinct)); assertFalse(distinct.hasNext()); } @Test(expected = NullPointerException.class) public void distinctNullIteratorTest() { distinct(null); }
Iterators2 { public static <T> Iterator<List<T>> groupBy(final Iterator<? extends T> iterator, final Function<? super T, ?> groupingFunction) { requireNonNull(iterator); requireNonNull(groupingFunction); return new AbstractIterator<List<T>>() { private final PeekingIterator<T> peekingIterator = peekingIterator(iterator); @Override protected List<T> computeNext() { if (!peekingIterator.hasNext()) return endOfData(); Object key = groupingFunction.apply(peekingIterator.peek()); List<T> group = new ArrayList<>(); do { group.add(peekingIterator.next()); } while (peekingIterator.hasNext() && Objects.equals(key, groupingFunction.apply(peekingIterator.peek()))); return unmodifiableList(group); } }; } private Iterators2(); static Iterator<T> distinct(final Iterator<T> iterator); static Iterator<List<T>> groupBy(final Iterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); }
@Test public void groupByTest() { List<Integer> testdata = asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); Iterator<List<Integer>> grouped = groupBy(testdata.iterator(), input -> input / 5); assertTrue(grouped.hasNext()); assertEquals(asList(0, 1, 2, 3, 4), grouped.next()); assertEquals(asList(5, 6, 7, 8, 9), grouped.next()); assertFalse(grouped.hasNext()); grouped = groupBy(testdata.iterator(), input -> null); assertTrue(grouped.hasNext()); assertEquals(testdata, grouped.next()); assertFalse(grouped.hasNext()); grouped = groupBy(testdata.iterator(), input -> input); assertTrue(grouped.hasNext()); for (int i = 0; i< testdata.size(); i++) { assertTrue(grouped.hasNext()); List<Integer> group = grouped.next(); assertEquals(1, group.size()); assertEquals(new Integer(i), group.get(0)); } assertFalse(grouped.hasNext()); } @Test(expected = NullPointerException.class) public void groupByNullIteratorTest() { groupBy(null, input -> null); } @Test(expected = NullPointerException.class) public void groupByNullEquivTest() { groupBy(emptyIterator(), null); }
MoreInetAddresses { public static InetAddress forString(String ipString) { requireNonNull(ipString); InetAddress address = InetAddresses.forString(ipString); if (address instanceof Inet4Address && ipString.contains(":")) return getIPv4MappedIPv6Address((Inet4Address) address); return address; } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }
@Test public void forStringTest() { InetAddress address; address = MoreInetAddresses.forString("1.2.3.4"); assertTrue(address instanceof Inet4Address); assertEquals("1.2.3.4", toAddrString(address)); address = MoreInetAddresses.forString("::1.2.3.4"); assertTrue(address instanceof Inet6Address); assertEquals("::102:304", toAddrString(address)); address = MoreInetAddresses.forString("::ffff:1.2.3.4"); assertTrue(address instanceof Inet6Address); assertEquals("::ffff:102:304", toAddrString(address)); } @Test(expected = NullPointerException.class) public void forStringNullTest() { MoreInetAddresses.forString(null); }
EntityDeserializer extends AbstractAttributeStoreDeserializer<BaseEntity, EntityBuilder> { @Override public BaseEntity build(EntityBuilder entityBuilder) { return (BaseEntity)entityBuilder.build(); } @Override EntityBuilder deserialize(JsonNode root); @Override BaseEntity build(EntityBuilder entityBuilder); }
@Test public void testBasicDeserialization() throws Exception { Entity entity = create("type", "id") .attr("key", "value") .build(); String json = objectMapper.writeValueAsString(entity); Entity actualEntity = objectMapper.readValue(json, Entity.class); assertEquals(actualEntity.getType(), entity.getType()); assertEquals(actualEntity.getId(), entity.getId()); assertEquals(new HashSet<>(actualEntity.getAttributes()), new HashSet<>(entity.getAttributes())); }
MoreInetAddresses { public static Inet4Address forIPv4String(String ipString) { requireNonNull(ipString); try{ InetAddress parsed = forString(ipString); if (parsed instanceof Inet4Address) return (Inet4Address) parsed; } catch(Exception ignored){} throw new IllegalArgumentException(format("Invalid IPv4 representation: %s", ipString)); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }
@Test public void forIpv4StringTest() { Inet4Address address; address = forIPv4String("1.2.3.4"); assertEquals("1.2.3.4", toAddrString(address)); } @Test(expected = NullPointerException.class) public void forIpv4StringNullTest() { forIPv4String(null); } @Test(expected = IllegalArgumentException.class) public void forIpv4StringWithIpv6Test() { forIPv4String("::1.2.3.4"); } @Test(expected = IllegalArgumentException.class) public void forIpv4StringWithMappedIpv4Test() { forIPv4String("::ffff:1.2.3.4"); }
MoreInetAddresses { public static Inet6Address forIPv6String(String ipString) { requireNonNull(ipString); try{ InetAddress parsed = forString(ipString); if (parsed instanceof Inet6Address) return (Inet6Address) parsed; } catch(Exception ignored){} throw new IllegalArgumentException(format("Invalid IPv6 representation: %s", ipString)); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }
@Test public void forIpv6StringTest() { Inet6Address address; address = forIPv6String("::1.2.3.4"); assertEquals("::102:304", toAddrString(address)); address = forIPv6String("::ffff:1.2.3.4"); assertEquals("::ffff:102:304", toAddrString(address)); } @Test(expected = NullPointerException.class) public void forIpv6StringNullTest() { forIPv6String(null); } @Test(expected = IllegalArgumentException.class) public void forIpv6StringWithIpv4Test() { forIPv6String("1.2.3.4"); }
MoreInetAddresses { public static boolean isMappedIPv4Address(Inet6Address ip) { byte bytes[] = ip.getAddress(); return ((bytes[0] == 0x00) && (bytes[1] == 0x00) && (bytes[2] == 0x00) && (bytes[3] == 0x00) && (bytes[4] == 0x00) && (bytes[5] == 0x00) && (bytes[6] == 0x00) && (bytes[7] == 0x00) && (bytes[8] == 0x00) && (bytes[9] == 0x00) && (bytes[10] == (byte)0xff) && (bytes[11] == (byte)0xff)); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }
@Test public void isMappedIPv4AddressTest() throws UnknownHostException { byte[] bytes = new byte[]{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, (byte) 0xff, (byte) 0xff, 0x1, 0x2, 0x3, 0x4 }; Inet6Address address = Inet6Address.getByAddress(null, bytes, -1); assertTrue(MoreInetAddresses.isMappedIPv4Address(address)); bytes = new byte[]{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x2, 0x3, 0x4 }; address = Inet6Address.getByAddress(null, bytes, -1); assertFalse(MoreInetAddresses.isMappedIPv4Address(address)); } @Test(expected = NullPointerException.class) public void isMappedIPv4AddressNullTest() { MoreInetAddresses.isMappedIPv4Address(null); }
MoreInetAddresses { public static Inet4Address getMappedIPv4Address(Inet6Address ip) { if (!isMappedIPv4Address(ip)) throw new IllegalArgumentException(String.format("Address '%s' is not IPv4-mapped.", toAddrString(ip))); return getInet4Address(copyOfRange(ip.getAddress(), 12, 16)); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }
@Test public void getMappedIPv4AddressTest() throws UnknownHostException { byte[] bytes = new byte[]{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, (byte) 0xff, (byte) 0xff, 0x1, 0x2, 0x3, 0x4 }; Inet6Address address = Inet6Address.getByAddress(null, bytes, -1); Inet4Address inet4Address = MoreInetAddresses.getMappedIPv4Address(address); assertEquals(InetAddress.getByAddress(bytes), inet4Address); } @Test(expected = NullPointerException.class) public void getMappedIPv4AddressNullTest() { MoreInetAddresses.getMappedIPv4Address(null); } @Test(expected = IllegalArgumentException.class) public void getMappedIPv4AddressInvalidTypeTest() throws UnknownHostException { byte[] bytes = new byte[]{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x2, 0x3, 0x4 }; Inet6Address address = Inet6Address.getByAddress(null, bytes, -1); MoreInetAddresses.getMappedIPv4Address(address); }
Iterables2 { public static <T> Iterable<T> distinct(final Iterable<T> iterable) { requireNonNull(iterable); return () -> Iterators2.distinct(iterable.iterator()); } private Iterables2(); static Iterable<T> simpleIterable(final Iterable<T> iterable); static Iterable<T> distinct(final Iterable<T> iterable); static Iterable<List<T>> groupBy(final Iterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); }
@Test public void distinctTest() throws Exception { Iterable<Integer> distinct = distinct(asList(1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7)); assertEquals(asList(1, 2, 3, 4, 5, 6, 7), newArrayList(distinct)); } @Test(expected = NullPointerException.class) public void distinctNullIteratorTest() { distinct(null); }
MoreInetAddresses { public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) { return isMappedIPv4Address(ip) || InetAddresses.hasEmbeddedIPv4ClientAddress(ip); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }
@Test public void hasEmbeddedIPv4ClientAddressTest() { assertTrue(MoreInetAddresses.hasEmbeddedIPv4ClientAddress(forIPv6String("::ffff:1.2.3.4"))); assertTrue(MoreInetAddresses.hasEmbeddedIPv4ClientAddress(forIPv6String("::1.2.3.4"))); assertTrue(MoreInetAddresses.hasEmbeddedIPv4ClientAddress(forIPv6String("2002:102:304::"))); assertFalse(MoreInetAddresses.hasEmbeddedIPv4ClientAddress(forIPv6String("1::1.2.3.4"))); } @Test(expected = NullPointerException.class) public void hasEmbeddedIPv4ClientAddressNullTest() { MoreInetAddresses.hasEmbeddedIPv4ClientAddress(null); }
MoreInetAddresses { public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) { if (isMappedIPv4Address(ip)) return getMappedIPv4Address(ip); return InetAddresses.getEmbeddedIPv4ClientAddress(ip); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }
@Test public void getEmbeddedIPv4ClientAddressTest() { assertEquals(MoreInetAddresses.forString("1.2.3.4"), MoreInetAddresses.getEmbeddedIPv4ClientAddress(forIPv6String("::ffff:1.2.3.4"))); assertEquals(MoreInetAddresses.forString("1.2.3.4"), MoreInetAddresses.getEmbeddedIPv4ClientAddress(forIPv6String("::1.2.3.4"))); assertEquals(MoreInetAddresses.forString("1.2.3.4"), MoreInetAddresses.getEmbeddedIPv4ClientAddress(forIPv6String("2002:102:304::"))); } @Test(expected = NullPointerException.class) public void getEmbeddedIPv4ClientAddressNullTest() { MoreInetAddresses.getEmbeddedIPv4ClientAddress(null); }
MoreInetAddresses { public static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip) { byte[] from = ip.getAddress(); byte[] bytes = new byte[] { 0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0, 0x0,0x0,(byte)0xff,(byte)0xff, from[0],from[1],from[2],from[3] }; return getInet6Address(bytes); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }
@Test public void getIPv4MappedIPv6AddressTest() { assertEquals("::ffff:102:304", toAddrString(MoreInetAddresses.getIPv4MappedIPv6Address(forIPv4String("1.2.3.4")))); } @Test(expected = NullPointerException.class) public void getIPv4MappedIPv6AddressNullTest() { MoreInetAddresses.getIPv4MappedIPv6Address(null); }
MoreInetAddresses { public static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip) { byte[] from = ip.getAddress(); byte[] bytes = new byte[] { 0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0, from[0],from[1],from[2],from[3] }; return getInet6Address(bytes); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }
@Test public void getIPv4CompatIPv6AddressTest() { assertEquals("::102:304", toAddrString(MoreInetAddresses.getIPV4CompatIPv6Address(forIPv4String("1.2.3.4")))); } @Test(expected = NullPointerException.class) public void getIPv4CompatIPv6AddressNullTest() { MoreInetAddresses.getIPV4CompatIPv6Address(null); }
MoreInetAddresses { public static CidrInfo parseCIDR(String cidr) { requireNonNull(cidr); try { String[] parts = cidr.split("/"); checkArgument(parts.length == 2); byte[] bytes = forString(parts[0]).getAddress(); int maskBits = parseInt(parts[1]); checkArgument(maskBits >= 0 && maskBits <= bytes.length * 8); int remainingBits = maskBits; byte[] network = new byte[bytes.length]; byte[] broadcast = new byte[bytes.length]; for (int i = 0; i< bytes.length; i++) { if (remainingBits >= 8) { network[i] = bytes[i]; broadcast[i] = bytes[i]; } else if (remainingBits > 0) { int byteMask = -1 << (8 - remainingBits); network [i] = (byte) (bytes[i] & byteMask); broadcast [i] = (byte) (bytes[i] | ~byteMask); } else { network[i] = 0; broadcast[i] = (byte)0xff; } remainingBits -= 8; } return new CidrInfo(maskBits, bytesToInetAddress(network), bytesToInetAddress(broadcast)); }catch(Exception ignored){} throw new IllegalArgumentException(format("Invalid CIDR string: %s", cidr)); } private MoreInetAddresses(); static InetAddress forString(String ipString); static Inet4Address forIPv4String(String ipString); static Inet6Address forIPv6String(String ipString); static boolean isMappedIPv4Address(Inet6Address ip); static Inet4Address getMappedIPv4Address(Inet6Address ip); static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip); static Inet6Address getIPv4MappedIPv6Address(Inet4Address ip); static Inet6Address getIPV4CompatIPv6Address(Inet4Address ip); static Inet4Address increment(Inet4Address ip); static Inet6Address increment(Inet6Address ip); static Inet4Address decrement(Inet4Address ip); static Inet6Address decrement(Inet6Address ip); static CidrInfo parseCIDR(String cidr); }
@Test public void forCIDRStringTest() { MoreInetAddresses.CidrInfo cidr = MoreInetAddresses.parseCIDR("255.255.255.255/16"); assertTrue(cidr.getNetwork() instanceof Inet4Address); assertEquals("255.255.0.0", toAddrString(cidr.getNetwork())); assertEquals("255.255.255.255", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("0.0.0.0/16"); assertTrue(cidr.getNetwork() instanceof Inet4Address); assertEquals("0.0.0.0", toAddrString(cidr.getNetwork())); assertEquals("0.0.255.255", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("255.255.255.255/20"); assertTrue(cidr.getNetwork() instanceof Inet4Address); assertEquals("255.255.240.0", toAddrString(cidr.getNetwork())); assertEquals("255.255.255.255", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("0.0.0.0/20"); assertTrue(cidr.getNetwork() instanceof Inet4Address); assertEquals("0.0.0.0", toAddrString(cidr.getNetwork())); assertEquals("0.0.15.255", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("123.45.67.0/21"); assertTrue(cidr.getNetwork() instanceof Inet4Address); assertEquals("123.45.64.0", toAddrString(cidr.getNetwork())); assertEquals("123.45.71.255", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("1.2.3.4/32"); assertTrue(cidr.getNetwork() instanceof Inet4Address); assertEquals("1.2.3.4", toAddrString(cidr.getNetwork())); assertEquals("1.2.3.4", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("1.2.3.4/0"); assertTrue(cidr.getNetwork() instanceof Inet4Address); assertEquals("0.0.0.0", toAddrString(cidr.getNetwork())); assertEquals("255.255.255.255", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/64"); assertTrue(cidr.getNetwork() instanceof Inet6Address); assertEquals("ffff:ffff:ffff:ffff::", toAddrString(cidr.getNetwork())); assertEquals("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/68"); assertTrue(cidr.getNetwork() instanceof Inet6Address); assertEquals("ffff:ffff:ffff:ffff:f000::", toAddrString(cidr.getNetwork())); assertEquals("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("::/64"); assertTrue(cidr.getNetwork() instanceof Inet6Address); assertEquals("::", toAddrString(cidr.getNetwork())); assertEquals("::ffff:ffff:ffff:ffff", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("::/68"); assertTrue(cidr.getNetwork() instanceof Inet6Address); assertEquals("::", toAddrString(cidr.getNetwork())); assertEquals("::fff:ffff:ffff:ffff", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("1:2:3:4:5:6:7:8/128"); assertTrue(cidr.getNetwork() instanceof Inet6Address); assertEquals("1:2:3:4:5:6:7:8", toAddrString(cidr.getNetwork())); assertEquals("1:2:3:4:5:6:7:8", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("1:2:3:4:5:6:7:8/0"); assertTrue(cidr.getNetwork() instanceof Inet6Address); assertEquals("::", toAddrString(cidr.getNetwork())); assertEquals("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", toAddrString(cidr.getBroadcast())); cidr = MoreInetAddresses.parseCIDR("::ffff:1.2.3.4/112"); assertTrue(cidr.getNetwork() instanceof Inet6Address); assertEquals("::ffff:102:0", toAddrString(cidr.getNetwork())); assertEquals("::ffff:102:ffff", toAddrString(cidr.getBroadcast())); }
IP implements Serializable { @Override public String toString() { return toAddrString(address); } protected IP(T address); @SuppressWarnings("unchecked") T getAddress(); byte[] toByteArray(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void ipv4ToStringTest() { IPv4 ip = new IPv4(forIPv4String("1.2.3.4")); assertEquals("1.2.3.4", ip.toString()); } @Test public void ipv6ToStringTest() { IPv6 ip = new IPv6(forIPv6String("::1.2.3.4")); assertEquals("::102:304", ip.toString()); ip = new IPv6(forIPv6String("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")); assertEquals("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", ip.toString()); ip = new IPv6(forIPv6String("1234:0000:0000:0000:0000:0000:0000:1234")); assertEquals("1234::1234", ip.toString()); }
QueryBuilder { public QueryBuilder eq(String type, Object value) { checkFinished(); if (this.current == null) { this.current = new AndNode(); finished = true; } EqualsLeaf equalsLeaf = new EqualsLeaf<>(type, value, current); this.current.addChild(equalsLeaf); return this; } protected QueryBuilder(); protected QueryBuilder(ParentNode current, QueryBuilder parentBuilder); static QueryBuilder create(); QueryBuilder and(); QueryBuilder or(); Node build(); QueryBuilder eq(String type, Object value); QueryBuilder has(String key); QueryBuilder hasNot(String key); QueryBuilder in(String key, Collection<Object> values); QueryBuilder in(String key, Object... values); QueryBuilder notIn(String key, Collection<Object> values); QueryBuilder notIn(String key, Object... values); QueryBuilder notEq(String type, Object value); QueryBuilder lessThan(String type, Object value); QueryBuilder lessThanEq(String type, Object value); QueryBuilder greaterThan(String type, Object value); QueryBuilder greaterThanEq(String type, Object value); QueryBuilder range(String type, Object start, Object end); QueryBuilder end(); }
@Test public void testEq() throws Exception { Node build = QueryBuilder.create().eq("feedName", "netflowv9").build(); StringWriter writer = new StringWriter(); build.accept(new PrintNodeVisitor(writer)); assertEquals("AndNode(Equals[feedName,netflowv9],),", writer.toString()); }
CollapseParentClauseVisitor implements NodeVisitor { @Override public void end(ParentNode node) { } @Override void begin(ParentNode node); @Override void end(ParentNode node); @Override void visit(Leaf node); }
@Test public void testCollapseAndAndChildren() throws Exception { StringWriter writer = new StringWriter(); Node node = QueryBuilder.create().and().and().eq("k1", "v1").eq("k2", "v2").end().end().build(); node.accept(new PrintNodeVisitor(writer)); writer.append('\n'); node.accept(new CollapseParentClauseVisitor()); node.accept(new PrintNodeVisitor(writer)); writer.append('\n'); } @Test public void testCollapseAndAndOrChildren() throws Exception { StringWriter writer = new StringWriter(); Node node = QueryBuilder.create().and().and().eq("k1", "v1").eq("k2", "v2").end().or().eq("k3", "v3").eq("k4", "v4").end().end().build(); node.accept(new PrintNodeVisitor(writer)); writer.append('\n'); node.accept(new CollapseParentClauseVisitor()); node.accept(new PrintNodeVisitor(writer)); writer.append('\n'); }
LessThanEqualsCriteria extends ComparableTermValueCriteria<T> { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (getComparator().compare((T)(attribute.getValue()), getValue()) <= 0) return true; } return false; } LessThanEqualsCriteria(String term, T value, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }
@Test public void test() { LessThanEqualsCriteria criteria = new LessThanEqualsCriteria<>("key1", 5, naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id"); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 10); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 5); assertTrue(criteria.test(entity.build())); entity = entity.attr("key1", 4); assertTrue(criteria.test(entity.build())); }
EqualsCriteria extends ComparableTermValueCriteria<T> { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (getComparator().compare((T)(attribute.getValue()), getValue()) == 0) return true; } return false; } EqualsCriteria(String term, T value, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }
@Test public void testEquals() { Criteria eq = new EqualsCriteria<>("key1", "val1", naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", "val1"); assertTrue(eq.test(entity.build())); } @Test public void testNotEquals() { Criteria eq = new EqualsCriteria<>("key1", "val1", naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", "val2"); assertFalse(eq.test(entity.build())); }
NotEqualsCriteria extends ComparableTermValueCriteria<T> { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (getComparator().compare((T)(attribute.getValue()), getValue()) != 0) return true; } return false; } NotEqualsCriteria(String term, T value, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }
@Test public void testNotEquals() { Criteria eq = new NotEqualsCriteria<>("key1", "val1", naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", "val2"); assertTrue(eq.test(entity.build())); } @Test public void testEquals() { Criteria eq = new NotEqualsCriteria<>("key1", "val1", naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", "val1"); assertFalse(eq.test(entity.build())); }
Iterables2 { public static <T> Iterable<List<T>> groupBy(final Iterable<? extends T> iterable, final Function<? super T, ?> groupingFunction) { requireNonNull(iterable); requireNonNull(groupingFunction); return () -> Iterators2.groupBy(iterable.iterator(), groupingFunction); } private Iterables2(); static Iterable<T> simpleIterable(final Iterable<T> iterable); static Iterable<T> distinct(final Iterable<T> iterable); static Iterable<List<T>> groupBy(final Iterable<? extends T> iterable, final Function<? super T, ?> groupingFunction); }
@Test public void groupByTest() { List<Integer> testdata = asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); Iterable<List<Integer>> grouped = groupBy(testdata, input -> input / 5); assertEquals(2, size(grouped)); assertEquals(asList(0, 1, 2, 3, 4), get(grouped, 0)); assertEquals(asList(5, 6, 7, 8, 9), get(grouped, 1)); grouped = groupBy(testdata, input -> null); assertEquals(1, size(grouped)); assertEquals(testdata, get(grouped, 0)); grouped = groupBy(testdata, input -> input); assertEquals(10, size(grouped)); for (int i = 0; i< testdata.size(); i++) { List<Integer> group = get(grouped, i); assertEquals(1, group.size()); assertEquals(new Integer(i), group.get(0)); } } @Test(expected = NullPointerException.class) public void groupByNullIteratorTest() { groupBy(null, input -> null); } @Test(expected = NullPointerException.class) public void groupByNullEquivTest() { groupBy(emptyList(), null); }
LessThanCriteria extends ComparableTermValueCriteria<T> { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (getComparator().compare((T)(attribute.getValue()), getValue()) < 0) return true; } return false; } LessThanCriteria(String term, T value, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }
@Test public void test() { LessThanCriteria criteria = new LessThanCriteria<>("key1", 5, naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id"); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 10); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 4); assertTrue(criteria.test(entity.build())); }
HasNotCriteria extends TermCriteria { @Override public boolean test(AttributeStore obj) { if(obj.get(getTerm()) == null) return true; Collection<Attribute> attributes = obj.getAttributes(getTerm()); if(attributes.size() > 0 && clazz == null) return false; for(Attribute attribute : attributes) { if(attribute.getValue().getClass().equals(clazz)) return false; } return true; } HasNotCriteria(String term, Class<T> clazz, ParentCriteria parentCriteria); HasNotCriteria(String term, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override String toString(); }
@Test public void test() { HasNotCriteria criteria = new HasNotCriteria("key1", null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key2", "val2"); assertTrue(criteria.test(entity.build())); entity = entity.attr("key1", "val1"); assertFalse(criteria.test(entity.build())); }
RangeCriteria extends TermCriteria { @Override public boolean test(AttributeStore obj) { for (Attribute attribute : obj.getAttributes(getTerm())) { if (comparator.compare((T)(attribute.getValue()), start) >= 0 && comparator.compare((T)(attribute.getValue()), end) <= 0) { return true; } } return false; } RangeCriteria(String term, T start, T end, Comparator<T> comparator, ParentCriteria parentCriteria); @Override boolean test(AttributeStore obj); @Override Criteria clone(ParentCriteria parentCriteria); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void test() { RangeCriteria criteria = new RangeCriteria<>("key1", 5, 10, naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id"); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 11); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 4); assertFalse(criteria.test(entity.build())); entity = entity.attr("key1", 5); assertTrue(criteria.test(entity.build())); entity = entity.attr("key1", 6); assertTrue(criteria.test(entity.build())); } @Test public void acceptAnyTupleWithinRange() { RangeCriteria criteria = new RangeCriteria<>("key1", 5, 10, naturalOrder(), null); EntityBuilder entity = EntityBuilder.create("type", "id") .attr("key1", 4) .attr("key1", 6); assertTrue(criteria.test(entity.build())); }
NodeUtils { public static Criteria criteriaFromNode(Node node) { return criteriaFromNode(node, naturalOrder(), null); } NodeUtils(); static boolean isLeaf(Node node); static boolean isEmpty(Node node); static boolean parentContainsOnlyLeaves(ParentNode parentNode); static boolean isRangeLeaf(Leaf leaf); static Criteria criteriaFromNode(Node node); static Criteria criteriaFromNode(Node node, Comparator rangeComparator); }
@Test public void testCriteriaFromNode_fullTree() { Node node = QueryBuilder.create().or().and().eq("key1", "val1").eq("key2", "val2").end().eq("key3", "val3").end().build(); Criteria criteria = NodeUtils.criteriaFromNode(node); assertTrue(criteria instanceof OrCriteria); assertTrue(criteria.children().get(0) instanceof AndCriteria); assertTrue(criteria.children().get(0).children().get(0) instanceof EqualsCriteria); assertTrue(criteria.children().get(0).children().get(1) instanceof EqualsCriteria); assertTrue(criteria.children().get(1).children().get(0) instanceof EqualsCriteria); }
AbstractCloseableIterable implements CloseableIterable<T> { @Override public void close() { if (!closed) { doClose(); closed = true; } } @Override void close(); @Override Iterator<T> iterator(); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test public void closeTest() throws Exception { MockIterable iterable = new MockIterable(emptyList()); iterable.close(); assertTrue(iterable.isClosed()); }
CloseableIterators { public static <F, T> CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function) { return wrap(Iterators.transform(iterator, function::apply), iterator); } private CloseableIterators(); static CloseableIterator<T> fromStream(Stream<T> stream); static CloseableIterator<T> fromIterator(Iterator<T> iterator); static CloseableIterator<T> distinct(final CloseableIterator<T> iterator); static CloseableIterator<List<T>> groupBy(final CloseableIterator<? extends T> iterator, final Function<? super T, ?> groupingFunction); static CloseableIterator<T> concat(final CloseableIterator<? extends Iterator<? extends T>> iterators); @SuppressWarnings("unchecked") static CloseableIterator<T> emptyIterator(); static CloseableIterator<T> filter(final CloseableIterator<T> iterator, final Predicate<T> filter); static CloseableIterator<T> filter(final CloseableIterator<?> iterator, final Class<T> type); static CloseableIterator<T> limit(final CloseableIterator<T> iterator, final int limitSize); static CloseableIterator<List<T>> paddedParition(final CloseableIterator<T> iterator, final int size); static CloseableIterator<List<T>> partition(final CloseableIterator<T> iterator, final int size); static PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator); static CloseableIterator<T> singletonIterator(T value); static CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function); @SafeVarargs static CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators); static CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator); static CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator); @Deprecated static CloseableIterator<T> wrap(final Iterator<T> iterator); }
@Test public void testTransform() { CloseableIterator<Integer> addOne = transform(testIterator(), input -> input + 1); CloseableIterator<Integer> multTen = transform(addOne, input -> input * 10); assertTrue(elementsEqual(asList(20, 30, 40, 50, 60).iterator(), multTen)); assertFalse(multTen.hasNext()); multTen.close(); }
GlobalIndexExpirationFilter extends Filter { @Override public boolean accept(Key k, Value v) { long expiration = new GlobalIndexValue(v).getExpiration(); return !MetadataExpirationFilter.shouldExpire(expiration, k.getTimestamp()); } @Override boolean accept(Key k, Value v); }
@Test public void testExpiration() { GlobalIndexExpirationFilter expirationFilter = new GlobalIndexExpirationFilter(); Key key = new Key(); key.setTimestamp(System.currentTimeMillis() - 1000); assertTrue(expirationFilter.accept(key, new GlobalIndexValue(1, 100000).toValue())); assertFalse(expirationFilter.accept(key, new GlobalIndexValue(1, 1).toValue())); assertTrue(expirationFilter.accept(key, new GlobalIndexValue(1, -1).toValue())); assertTrue(expirationFilter.accept(key, new Value("1".getBytes()))); }
NodeToJexl { public String transform(Set<String> types, Node node) { StringBuilder builder = new StringBuilder(); Iterator<String> typesItr = types.iterator(); while(typesItr.hasNext()) { builder.append(runTransform(typesItr.next(), node)); if(typesItr.hasNext()) builder.append(" or "); } return builder.toString(); } NodeToJexl(TypeRegistry<String> registry); static String removeInvalidChars(String key); static String revertToOriginalkey(String fixedString); String transform(Set<String> types, Node node); static char[] badChars; static String[] strings; static String[] chars; static final String JEXL_NORM_PREFIX; }
@Test public void testHas() { String jexl = nodeToJexl.transform(singleton(""), create().has("hello").build()); assertEquals("((hello >= '\u0000'))", jexl); } @Test public void testHasNot() { String jexl = nodeToJexl.transform(singleton(""), create().hasNot("hello").build()); assertEquals("(!(hello >= '\u0000'))", jexl); } @Test public void testIn() { String jexl = nodeToJexl.transform(singleton(""), create().in("key", "hello", "goodbye").build()); assertEquals("((key == 'string\u0001hello' or key == 'string\u0001goodbye'))", jexl); } @Test public void testNotIn() { String jexl = nodeToJexl.transform(singleton(""), create().notIn("key", "hello", "goodbye").build()); assertEquals("((key != 'string\u0001hello' and key != 'string\u0001goodbye'))", jexl); } @Test public void testSimpleEquals_AndNode() { String jexl = nodeToJexl.transform(singleton(""), create().and().eq("hello", "goodbye").eq("key1", true).end().build()); assertEquals("((hello == 'string\u0001goodbye') and (key1 == 'boolean\u00011'))", jexl); } @Test public void testSimpleEquals_OrNode() { String jexl = nodeToJexl.transform(singleton(""), create().or().eq("hello", "goodbye").eq("key1", true).end().build()); assertEquals("((hello == 'string\u0001goodbye') or (key1 == 'boolean\u00011'))", jexl); } @Test public void testGreaterThan() { String jexl = nodeToJexl.transform(singleton(""), create().greaterThan("hello", "goodbye").build()); assertEquals("((hello > 'string\u0001goodbye'))", jexl); } @Test public void testLessThan() { String jexl = nodeToJexl.transform(singleton(""), create().lessThan("hello", "goodbye").build()); assertEquals("((hello < 'string\u0001goodbye'))", jexl); } @Test public void testGreaterThanEquals() { String jexl = nodeToJexl.transform(singleton(""), create().greaterThanEq("hello", "goodbye").build()); assertEquals("((hello >= 'string\u0001goodbye'))", jexl); } @Test public void testLessThanEquals() { String jexl = nodeToJexl.transform(singleton(""), create().lessThanEq("hello", "goodbye").build()); assertEquals("((hello <= 'string\u0001goodbye'))", jexl); } @Test public void testNotEquals() { String jexl = nodeToJexl.transform(singleton(""), create().notEq("hello", "goodbye").build()); assertEquals("((hello != 'string\u0001goodbye'))", jexl); }
EventWritable implements Writable, Settable<Event>, Gettable<Event> { public Event get() { return entry; } EventWritable(); EventWritable(Event entry); void setAttributeWritable(AttributeWritable sharedAttributeWritable); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); void set(Event entry); Event get(); }
@Test public void testSerializesAndDeserializes() throws IOException { Event event = EventBuilder.create("", "id", System.currentTimeMillis()) .attr(new Attribute("key", "val", ImmutableMap.of("metaKey", "metaVal"))).build(); byte[] serialized = serialize(new EventWritable(event)); Event actual = asWritable(serialized, EventWritable.class).get(); assertEquals(event, actual); }
AttributeWritable implements Writable, Gettable<Attribute>, Settable<Attribute> { @Override public Attribute get() { return attribute; } AttributeWritable(); AttributeWritable(Attribute attribute); void setTypeRegistry(TypeRegistry<String> registry); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); @Override Attribute get(); @Override void set(Attribute item); }
@Test public void testSerializesAndDeserializes() throws IOException { Attribute attribute = new Attribute("key", "val", ImmutableMap.of("metaKey", "metaVal")); byte[] serialized = serialize(new AttributeWritable(attribute)); Attribute actual = asWritable(serialized, AttributeWritable.class).get(); assertEquals(attribute, actual); }
CardinalityReorderVisitor implements NodeVisitor { @Override public void end(ParentNode parentNode) { } CardinalityReorderVisitor(Map<AttributeIndexKey, Long> cardinalities, TypeRegistry<String> typeRegistry); @Override void begin(ParentNode parentNode); @Override void end(ParentNode parentNode); @Override void visit(Leaf leaf); }
@Test public void test_basicReorder() { Map<AttributeIndexKey, Long> cardinalities = new HashMap<AttributeIndexKey, Long>(); cardinalities.put(new AttributeIndexKey("key1", "val1", "string"), 500l); cardinalities.put(new AttributeIndexKey("key2", "val2", "string"), 50l); cardinalities.put(new AttributeIndexKey("key3", "val3", "string"), 1000l); Node node = QueryBuilder.create().or().eq("key3", "val3").and().eq("key2", "val2").eq("key1", "val1") .end().end().build(); node.accept(new CardinalityReorderVisitor(cardinalities, LEXI_TYPES)); System.out.println(new NodeToJexl(LEXI_TYPES).transform(singleton(""), node)); assertTrue(node instanceof OrNode); assertTrue(node.children().get(0) instanceof AndNode); assertEquals("key2", ((TermLeaf) node.children().get(0).children().get(0)).getTerm()); assertEquals("key1", ((TermLeaf) node.children().get(0).children().get(1)).getTerm()); assertEquals("key3", ((TermLeaf) node.children().get(1)).getTerm()); } @Test public void test_pruneCardinalities_AndNode() { Map<AttributeIndexKey, Long> cardinalities = new HashMap<AttributeIndexKey, Long>(); cardinalities.put(new AttributeIndexKey("key1", "val1", "string"), 500l); cardinalities.put(new AttributeIndexKey("key2", "val2", "string"), 0l); cardinalities.put(new AttributeIndexKey("key3", "val3", "string"), 1000l); Node node = QueryBuilder.create().or().eq("key3", "val3").and().eq("key2", "val2").eq("key1", "val1") .end().end().build(); node.accept(new CardinalityReorderVisitor(cardinalities, LEXI_TYPES)); System.out.println(new NodeToJexl(LEXI_TYPES).transform(singleton(""), node)); assertTrue(node instanceof OrNode); assertTrue(node.children().get(0) instanceof EqualsLeaf); assertEquals(1, node.children().size()); assertEquals("key3", ((TermLeaf) node.children().get(0)).getTerm()); } @Test public void test_pruneCardinalities_OrNode() { Map<AttributeIndexKey, Long> cardinalities = new HashMap<AttributeIndexKey, Long>(); cardinalities.put(new AttributeIndexKey("key1", "val1", "string"), 0l); cardinalities.put(new AttributeIndexKey("key2", "val2", "string"), 0l); cardinalities.put(new AttributeIndexKey("key3", "val3", "string"), 1000l); Node node = QueryBuilder.create().or().eq("key3", "val3").or().eq("key2", "val2").eq("key1", "val1") .end().end().build(); node.accept(new CardinalityReorderVisitor(cardinalities, LEXI_TYPES)); System.out.println(new NodeToJexl(LEXI_TYPES).transform(singleton(""), node)); assertTrue(node instanceof OrNode); assertTrue(node.children().get(0) instanceof EqualsLeaf); assertEquals(1, node.children().size()); assertEquals("key3", ((TermLeaf) node.children().get(0)).getTerm()); } @Test public void test_pruneCardinalities_AllNodesZero() { Map<AttributeIndexKey, Long> cardinalities = new HashMap<AttributeIndexKey, Long>(); cardinalities.put(new AttributeIndexKey("key1", "val1", "string"), 0l); cardinalities.put(new AttributeIndexKey("key2", "val2", "string"), 0l); cardinalities.put(new AttributeIndexKey("key3", "val3", "string"), 0l); Node node = QueryBuilder.create().or().eq("key3", "val3").or().eq("key2", "val2").eq("key1", "val1") .end().end().build(); node.accept(new CardinalityReorderVisitor(cardinalities, LEXI_TYPES)); System.out.println(new NodeToJexl(LEXI_TYPES).transform(singleton(""), node)); assertTrue(node instanceof OrNode); assertEquals(0, node.children().size()); }
GlobalIndexCombiner extends Combiner { @Override public Value reduce(Key key, Iterator<Value> valueIterator) { long cardinality = 0; long expiration = 0; while(valueIterator.hasNext()) { GlobalIndexValue value = new GlobalIndexValue(valueIterator.next()); cardinality += value.getCardinatlity(); if(value.getExpiration() == -1) expiration = -1; if(expiration != -1) expiration = Math.max(expiration, value.getExpiration()); } return new GlobalIndexValue(cardinality, expiration).toValue(); } @Override Value reduce(Key key, Iterator<Value> valueIterator); }
@Test public void testWithExpiration() { GlobalIndexCombiner combiner = new GlobalIndexCombiner(); Collection<Value> values = new ArrayList<Value>(); GlobalIndexValue value = new GlobalIndexValue(1, 2); GlobalIndexValue value2 = new GlobalIndexValue(1, 2); GlobalIndexValue value3 = new GlobalIndexValue(1, 50); GlobalIndexValue value4 = new GlobalIndexValue(1, 2); GlobalIndexValue value5 = new GlobalIndexValue(1, 2); values.add(value.toValue()); values.add(value2.toValue()); values.add(value3.toValue()); values.add(value4.toValue()); values.add(value5.toValue()); Value actualVal = combiner.reduce(new Key(), values.iterator()); GlobalIndexValue actualGiv = new GlobalIndexValue(actualVal); assertEquals(5, actualGiv.getCardinatlity()); assertEquals(50, actualGiv.getExpiration()); } @Test public void testWithNoExpiration() { GlobalIndexCombiner combiner = new GlobalIndexCombiner(); Collection<Value> values = new ArrayList<Value>(); GlobalIndexValue value = new GlobalIndexValue(1, 2); GlobalIndexValue value2 = new GlobalIndexValue(1, 2); GlobalIndexValue value3 = new GlobalIndexValue(1, -1); GlobalIndexValue value4 = new GlobalIndexValue(1, 2); GlobalIndexValue value5 = new GlobalIndexValue(1, 2); values.add(value.toValue()); values.add(value2.toValue()); values.add(value3.toValue()); values.add(value4.toValue()); values.add(value5.toValue()); Value actualVal = combiner.reduce(new Key(), values.iterator()); GlobalIndexValue actualGiv = new GlobalIndexValue(actualVal); assertEquals(5, actualGiv.getCardinatlity()); assertEquals(-1, actualGiv.getExpiration()); }
RangeSplitterVisitor implements NodeVisitor { @Override public void end(ParentNode parentNode) { } @Override void begin(ParentNode parentNode); @Override void end(ParentNode parentNode); @Override void visit(Leaf leaf); }
@Test public void test() { Node query = QueryBuilder.create().and().eq("key1", "val1").range("key2", 0, 5).end().build(); query.accept(new RangeSplitterVisitor()); assertTrue(query instanceof AndNode); assertEquals(3, query.children().size()); assertTrue(query.children().get(0) instanceof EqualsLeaf); assertTrue(query.children().get(1) instanceof GreaterThanEqualsLeaf); assertTrue(query.children().get(2) instanceof LessThanEqualsLeaf); query = QueryBuilder.create().or().eq("key1", "val1").range("key2", 0, 5).end().build(); query.accept(new RangeSplitterVisitor()); assertTrue(query instanceof OrNode); assertEquals(2, query.children().size()); assertTrue(query.children().get(0) instanceof EqualsLeaf); assertTrue(query.children().get(1) instanceof AndNode); assertTrue(query.children().get(1).children().get(0) instanceof GreaterThanEqualsLeaf); assertTrue(query.children().get(1).children().get(1) instanceof LessThanEqualsLeaf); }
ExtractInNotInVisitor implements NodeVisitor { @Override public void end(ParentNode parentNode) { } @Override void begin(ParentNode parentNode); @Override void end(ParentNode parentNode); @Override void visit(Leaf leaf); }
@Test public void testIn() { Node query = QueryBuilder.create().in("key", "hello", "goodbye").build(); Node expected = QueryBuilder.create().and().or().eq("key", "hello").eq("key", "goodbye").end().end().build(); query.accept(new ExtractInNotInVisitor()); assertEquals(expected, query); }
EntityWritable implements WritableComparable, Settable<Entity>, Gettable<Entity> { public Entity get() { return entity; } EntityWritable(); EntityWritable(Entity entity); void setAttributeWritable(AttributeWritable sharedAttributeWritable); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); void set(Entity entity); Entity get(); @Override int compareTo(Object o); }
@Test public void testSerializesAndDeserializes() throws IOException { Entity entity = EntityBuilder.create("type", "id") .attr(new Attribute("key", "val", ImmutableMap.of("metaKey", "metaVal"))) .build(); byte[] serialized = serialize(new EntityWritable(entity)); Entity actual = asWritable(serialized, EntityWritable.class).get(); assertEquals(entity, actual); }
Metric implements Writable { public double getVariance() { BigDecimal sumSquare = new BigDecimal(this.sumSquare); if(count < 2) return 0; BigDecimal sumSquareDivideByCount = sumSquare.divide(valueOf(count), 15, FLOOR); return (sumSquareDivideByCount.subtract(new BigDecimal(getMean() * getMean()))).doubleValue(); } Metric(); Metric(long value); Metric(long min, long max, long sum, long count, BigInteger sumSquare); long getMin(); long getMax(); long getSum(); long getCount(); BigInteger getSumSquare(); double getMean(); double getVariance(); double getStdDev(); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testVariance() { Metric metric = new Metric(1); assertEquals(0.0, metric.getVariance()); metric = new Metric(1, 1, 1, 5, BigInteger.valueOf(1)); assertEquals(0.16, metric.getVariance()); metric = new Metric(1, 1, 5, 5, BigInteger.valueOf(5)); assertEquals(0.0, metric.getVariance()); }
FeatureRegistry { public AccumuloFeatureConfig transformForClass(Class<? extends Feature> clazz) { AccumuloFeatureConfig featureConfig = classToTransform.get(clazz); if(featureConfig == null) { for(Map.Entry<Class, AccumuloFeatureConfig> clazzes : classToTransform.entrySet()) { if(clazzes.getKey().isAssignableFrom(clazz)) { featureConfig = clazzes.getValue(); classToTransform.put(clazz, featureConfig); } } } return featureConfig; } FeatureRegistry(AccumuloFeatureConfig... transforms); AccumuloFeatureConfig transformForClass(Class<? extends Feature> clazz); Iterable<AccumuloFeatureConfig> getConfigs(); static final FeatureRegistry BASE_FEATURES; }
@Test public void testMyTestFeatureReturns() { FeatureRegistry registry = new FeatureRegistry(new MetricFeatureConfig()); assertNotNull(registry.transformForClass(MyTestFeature.class)); }
MetricFeatureConfig implements AccumuloFeatureConfig<MetricFeature> { @Override public MetricFeature buildFeatureFromValue(long timestamp, String group, String type, String name, String visibility, Value value) { Metric metricFeatureVector = valueToVector.apply(value); return new MetricFeature(timestamp, group, type, name, visibility, metricFeatureVector); } @Override Class<MetricFeature> transforms(); @Override Value buildValue(MetricFeature feature); @Override MetricFeature buildFeatureFromValue(long timestamp, String group, String type, String name, String visibility, Value value); @Override String featureName(); @Override List<IteratorSetting> buildIterators(int priority); static final Function<Value, Metric> valueToVector; static final Function<Metric, Value> vectorToValue; }
@Test public void testBuildFeatureFromValue() { Value value = new Value("1,2,3,4,5".getBytes()); long timestamp = currentTimeMillis(); String group = "group"; String type = "type"; String name = "name"; String vis = "vis"; MetricFeature feature = new MetricFeatureConfig().buildFeatureFromValue( timestamp, group, type, name, vis, value ); assertEquals(group, feature.getGroup()); assertEquals(timestamp, feature.getTimestamp()); assertEquals(type, feature.getType()); assertEquals(name, feature.getName()); assertEquals(vis, feature.getVisibility()); assertEquals(1, feature.getVector().getMin()); assertEquals(2, feature.getVector().getMax()); assertEquals(3, feature.getVector().getSum()); assertEquals(4, feature.getVector().getCount()); assertEquals(BigInteger.valueOf(5), feature.getVector().getSumSquare()); }
MetricFeatureConfig implements AccumuloFeatureConfig<MetricFeature> { @Override public Value buildValue(MetricFeature feature) { return vectorToValue.apply(feature.getVector()); } @Override Class<MetricFeature> transforms(); @Override Value buildValue(MetricFeature feature); @Override MetricFeature buildFeatureFromValue(long timestamp, String group, String type, String name, String visibility, Value value); @Override String featureName(); @Override List<IteratorSetting> buildIterators(int priority); static final Function<Value, Metric> valueToVector; static final Function<Metric, Value> vectorToValue; }
@Test public void testBuildValueFromFeature() { long currentTime = currentTimeMillis(); MetricFeature feature = new MetricFeature(currentTimeMillis(), "group", "type", "name", "vis", new Metric(1)); Value value = new MetricFeatureConfig().buildValue(feature); assertEquals("1,1,1,1,1", new String(value.get())); }
AccumuloChangelogStore implements ChangelogStore { @Override public void put(Iterable<Event> changes) { EventWritable shared = new EventWritable(); checkNotNull(changes); try { for (Event change : changes) { shared.set(change); Mutation m = new Mutation(Long.toString(truncatedReverseTimestamp(change.getTimestamp(), bucketSize))); try { Text reverseTimestamp = new Text(Long.toString(reverseTimestamp(change.getTimestamp()))); m.put(reverseTimestamp, new Text(change.getType() + NULL_BYTE + change.getId()), change.getTimestamp(), new Value(serialize(shared))); writer.addMutation(m); } catch (Exception e) { throw new RuntimeException(e); } } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } AccumuloChangelogStore(Connector connector); AccumuloChangelogStore(Connector connector, String tableName, StoreConfig config); AccumuloChangelogStore(Connector connector, BucketSize bucketSize); AccumuloChangelogStore(Connector connector, String tableName, StoreConfig config, BucketSize bucketSize); @Override void put(Iterable<Event> changes); @Override void flush(); @Override MerkleTree getChangeTree(Date start, Date stop, Auths auths); @Override MerkleTree getChangeTree(Date start, Date stop, int dimensions, Auths auths); @Override CloseableIterable<Event> getChanges(Iterable<Date> buckets, Auths auths); }
@Test public void singleChange() throws Exception { long currentTime = currentTimeMillis(); MerkleTree sourceTree = buildTree(); Event entry = createStoreEntry("1", currentTime); store.put(asList(entry)); MerkleTree targetTree = buildTree(); assertEquals(sourceTree.getNumLeaves(), targetTree.getNumLeaves()); assertEquals(sourceTree.getDimensions(), targetTree.getDimensions()); List<BucketHashLeaf> diffLeaves = targetTree.diff(sourceTree); assertEquals(1, diffLeaves.size()); long expectedBucket = currentTime - (currentTime % BucketSize.FIVE_MINS.getMs()); assertEquals(expectedBucket, diffLeaves.get(0).getTimestamp()); } @Test public void multipleChanges() throws Exception { long currentTime = currentTimeMillis(); MerkleTree sourceTree = buildTree(); Event entry = createStoreEntry("1", currentTime); Event entry2 = createStoreEntry("2", currentTime - 900000); Event entry3 = createStoreEntry("3", currentTime - 50000000); Event entry4 = createStoreEntry("4", currentTime); Event entry5 = createStoreEntry("5", currentTime + 5000000); store.put(asList(entry, entry2, entry3, entry4, entry5)); MerkleTree targetTree = buildTree(); assertEquals(sourceTree.getNumLeaves(), targetTree.getNumLeaves()); assertEquals(sourceTree.getDimensions(), targetTree.getDimensions()); List<BucketHashLeaf> diffLeaves = targetTree.diff(sourceTree); assertEquals(4, diffLeaves.size()); long expectedTime1 = (currentTime + 5000000) - ((currentTime + 5000000) % BucketSize.FIVE_MINS.getMs()); assertEquals(expectedTime1, diffLeaves.get(0).getTimestamp()); long expectedTime2 = (currentTime) - ((currentTime) % BucketSize.FIVE_MINS.getMs()); assertEquals(expectedTime2, diffLeaves.get(1).getTimestamp()); long expectedTime3 = (currentTime - 900000) - ((currentTime - 900000) % BucketSize.FIVE_MINS.getMs()); assertEquals(expectedTime3, diffLeaves.get(2).getTimestamp()); long expectedTime4 = (currentTime - 50000000) - ((currentTime - 50000000) % BucketSize.FIVE_MINS.getMs()); assertEquals(expectedTime4, diffLeaves.get(3).getTimestamp()); }
MerkleTree implements Serializable { public Node getTopHash() { return topHash; } MerkleTree(List<T> leaves); MerkleTree(List<T> leaves, int dimensions); Node getTopHash(); Integer getDimensions(); Integer getNumLeaves(); @SuppressWarnings("rawtypes") List<T> diff(MerkleTree other); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testTreeBuilds() throws NoSuchAlgorithmException, IOException, ClassNotFoundException { List<MockLeaf> leaves = asList(leaf1, leaf2, leaf8, leaf7, leaf4); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); assertEquals("17a19db32d969668fb08f9a5491eb4fe", tree.getTopHash().getHash()); assertEquals(2, tree.getTopHash().getChildren().size()); }
MerkleTree implements Serializable { @SuppressWarnings("rawtypes") public List<T> diff(MerkleTree other) { if (dimensions != other.dimensions || numLeaves != other.numLeaves) { throw new IllegalStateException("Trees need to have the same size & dimension to diff."); } List<T> differences = new ArrayList<>(); if (!other.getTopHash().getHash().equals(getTopHash().getHash())) { List<Node> nodes1 = topHash.getChildren(); List<Node> nodes2 = other.getTopHash().getChildren(); if (nodes1 == null) { return differences; } else if (nodes2 == null) { differences.addAll(getLeaves(nodes1)); } else { for (int i = 0; i < nodes1.size(); i++) { if (i < nodes1.size() && nodes2.size() == i) { differences.addAll(getLeaves(nodes1.get(i).getChildren())); } else { differences.addAll(diff(nodes1.get(i), nodes2.get(i))); } } } } return differences; } MerkleTree(List<T> leaves); MerkleTree(List<T> leaves, int dimensions); Node getTopHash(); Integer getDimensions(); Integer getNumLeaves(); @SuppressWarnings("rawtypes") List<T> diff(MerkleTree other); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testDiff_differentDimensionsFails() { List<MockLeaf> leaves = asList(leaf1, leaf2); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); MerkleTree<MockLeaf> tree2 = new MerkleTree<>(leaves, 4); try { tree.diff(tree2); fail("Should have thrown exception"); } catch (IllegalStateException ignored) { } } @Test public void testDiff_differentSizesFails() { List<MockLeaf> leaves = asList(leaf1, leaf2); List<MockLeaf> leaves2 = asList(leaf1, leaf2, leaf3); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); MerkleTree<MockLeaf> tree2 = new MerkleTree<>(leaves2, 2); try { tree.diff(tree2); fail("Should have thrown exception"); } catch (IllegalStateException ignored) { } } @Test public void testDiff() { List<MockLeaf> leaves = asList(leaf1, leaf2); List<MockLeaf> leaves2 = asList(leaf1, leaf3); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); MerkleTree<MockLeaf> tree2 = new MerkleTree<>(leaves2, 2); List<MockLeaf> diffs = tree.diff(tree2); assertEquals(leaf2, diffs.get(0)); assertEquals(1, diffs.size()); diffs = tree2.diff(tree); assertEquals(leaf3, diffs.get(0)); assertEquals(1, diffs.size()); }
MerkleTree implements Serializable { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MerkleTree<?> that = (MerkleTree<?>) o; return dimensions == that.dimensions && numLeaves == that.numLeaves && Objects.equals(topHash, that.topHash); } MerkleTree(List<T> leaves); MerkleTree(List<T> leaves, int dimensions); Node getTopHash(); Integer getDimensions(); Integer getNumLeaves(); @SuppressWarnings("rawtypes") List<T> diff(MerkleTree other); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testEquals_false() { List<MockLeaf> leaves = asList(leaf1, leaf2); List<MockLeaf> leaves2 = asList(leaf1, leaf3); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); MerkleTree<MockLeaf> tree2 = new MerkleTree<>(leaves2, 2); assertFalse(tree.equals(tree2)); assertFalse(tree2.equals(tree)); } @Test public void testEquals_true() { List<MockLeaf> leaves = asList(leaf1, leaf2); List<MockLeaf> leaves2 = asList(leaf1, leaf2); MerkleTree<MockLeaf> tree = new MerkleTree<>(leaves, 2); MerkleTree<MockLeaf> tree2 = new MerkleTree<>(leaves2, 2); assertTrue(tree.equals(tree2)); assertTrue(tree2.equals(tree)); }
CollectionSizeAdjuster { public void adjustSizeIfNeed(int requiredNumber) { if (requiredNumber < 0) { throw new ArrayIndexOutOfBoundsException("index out of bounds"); } if (requiredNumber > collection.size() - 1) { addUnits(requiredNumber); } } CollectionSizeAdjuster(Collection<T> collection, UnitFactory<T> unitFactory); void adjustSizeIfNeed(int requiredNumber); }
@Test public void adjustSizeIfNeed() throws Exception { for (int i = 0; i < 100; i++) { useAdjuster(i); } }
OffsetAnimator { protected float computeValueByOffset(float positionOffset) { positionOffset = computeByTimeShift(positionOffset); positionOffset = computeByInterpolator(positionOffset); return computeExactPosition(x1, x2, positionOffset); } protected OffsetAnimator(float x1, float x2); void animate(float positionOffset); void setParams(AnimatorParams params); OffsetAnimator setStartThreshold(float startThreshold); OffsetAnimator setDuration(float duration); OffsetAnimator setInterpolator(Interpolator interpolator); OffsetAnimator setListener(ValueListener valueListener); }
@Test public void getCurrentValue() throws Exception { OffsetAnimator offsetAnimator = new OffsetAnimator(0, 100); float[] positionOffsets = PositionGenerator.generatePositionOffsets(); final float[] expectedValues = new float[100]; for (int i = 1; i < 100; i++) { expectedValues[i] = i; } final float[] actualValues = new float[100]; for (int i = 0; i < positionOffsets.length; i++) { actualValues[i] = offsetAnimator.computeValueByOffset(positionOffsets[i]); } assertArrayEquals(expectedValues, actualValues, 0.00001f); }
ImagesPresenter implements ImagesContract.Presenter { @Override public void openImage(String path) { mView.showImage(path); } ImagesPresenter(ImagesRepository imagesRepository, ImagesContract.View imagesView); @Override void start(); @Override void openTakePhoto(); @Override void openImportPhoto(); @Override void openImage(String path); @Override void onImportImage(Bitmap image); @Override void onPhotoTaken(Bitmap image); @Override void setPictureTaker(PictureTaker pictureTaker); @Override void clearPictureTaker(); @Override void setImageImporter(ImageImporter imageImporter); @Override void clearImageImporter(); @Override void onPermissionRequestResult(boolean isGranted); }
@Test public void openImage() throws Exception { final String image = "1.png"; mPresenter.openImage(image); verify(mView).showImage(image); }
ImageViewerPresenter implements ImageViewerContract.Presenter { @Override public void showImage() { Bitmap bitmap = mImagesRepository.getImage(mImage); mView.displayImage(bitmap); } ImageViewerPresenter(@NonNull ImageViewerContract.View view, @NonNull ImagesRepository repository, @NonNull ImageSharer imageSharer, @NonNull String image); @Override void start(); @Override void showImage(); @Override void deleteImage(); @Override void shareImage(); }
@Test public void openImage() throws Exception { final String image = "1.png"; mPresenter.showImage(); verify(mView).displayImage(any(Bitmap.class)); }
ImageViewerPresenter implements ImageViewerContract.Presenter { @Override public void deleteImage() { mImagesRepository.deleteImage(mImage); mView.displayImageDeleted(); } ImageViewerPresenter(@NonNull ImageViewerContract.View view, @NonNull ImagesRepository repository, @NonNull ImageSharer imageSharer, @NonNull String image); @Override void start(); @Override void showImage(); @Override void deleteImage(); @Override void shareImage(); }
@Test public void deleteImage() throws Exception { mPresenter.deleteImage(); verify(mRepository).deleteImage(anyString()); }
ImageViewerPresenter implements ImageViewerContract.Presenter { @Override public void shareImage() { mImageSharer.shareImage(mImage); } ImageViewerPresenter(@NonNull ImageViewerContract.View view, @NonNull ImagesRepository repository, @NonNull ImageSharer imageSharer, @NonNull String image); @Override void start(); @Override void showImage(); @Override void deleteImage(); @Override void shareImage(); }
@Test public void shareImage() throws Exception { mPresenter.shareImage(); verify(mSharer).shareImage(anyString()); }
MainPresenter implements MainContract.Presenter { @Override public void loadPosts() { mView.setLoadingPosts(true); mData.getPosts(new DataSource.GetPostsCallback() { @Override public void onPostsLoaded(Post[] posts) { mView.setLoadingPosts(false); mView.hideError(); if (posts != null && posts.length > 0) { mView.showNoPostsMessage(false); mView.setPosts(posts); } else { mView.showNoPostsMessage(true); } } @Override public void onPostsNotAvailable(String error, Throwable cause) { String fullError = error; if (cause != null) { StringBuilder buffer = new StringBuilder(); buffer.append(error); buffer.append('\n'); buffer.append(cause.toString()); fullError = buffer.toString(); } mView.showError(error, fullError); mView.setLoadingPosts(false); mView.showNoPostsMessage(true); mView.setPosts(null); } }); } MainPresenter(DataSource mData, MainContract.View mView); @Override void start(); @Override void loadPosts(); @Override void onLoadPostImageError(String title, Exception e); }
@Test public void loadPostsSuccess() throws Exception { Post[] posts = new Post[]{ new Post("Annie", "Hello", null), new Post("Ann", "World", null), new Post("Droid", "Test", null) }; mPresenter.loadPosts(); verify(mData).getPosts(mGetPostsCallbackbackCaptor.capture()); verify(mView).setLoadingPosts(true); mGetPostsCallbackbackCaptor.getValue().onPostsLoaded(posts); verify(mView).setLoadingPosts(false); verify(mView).setPosts(posts); verify(mView).showNoPostsMessage(false); verify(mView).hideError(); } @Test public void loadPostsError() throws Exception { String errorText = "Error!"; mPresenter.loadPosts(); verify(mData).getPosts(mGetPostsCallbackbackCaptor.capture()); verify(mView).setLoadingPosts(true); mGetPostsCallbackbackCaptor.getValue().onPostsNotAvailable(errorText, null); verify(mView).setLoadingPosts(false); verify(mView).showError(anyString(), anyString()); verify(mView).showNoPostsMessage(true); verify(mView).setPosts(null); }
CardTemplate { private String updateImagesPath(String template) { return template.replaceAll(IMAGE_PATH_REGEX, IMAGE_PATH_REPLACEMENT); } CardTemplate(String frontTemplate, String rearTemplate, int ord); String getFrontTemplate(); String getRearTemplate(); int getOrd(); }
@Test public void updateImagesPathTest() throws Exception { String sampleText = "Che cos'è un latch SR?\n<hr id=answer>\n<div>Un circuito elettronico capace di memorizzare informazioni</div><img src=\"paste-9921374453761.jpg\" /> oppure <img src=\"paste-9921374453761.jpg\" />"; String expectedText = "Che cos'è un latch SR?\n<hr id=answer>\n<div>Un circuito elettronico capace di memorizzare informazioni</div><img src=\"anki-images/paste-9921374453761.jpg\" /> oppure <img src=\"anki-images/paste-9921374453761.jpg\" />"; String result = sampleText.replaceAll("(<img.+?src=\")([^\"]+)\"", "$1anki-images/$2\""); Assert.assertEquals(null, expectedText, result); String sample2 = "<img class=\"latex\" src=\"latex-6a3ac365210c170e4573d6f669410f5812e87aff.png\">"; String expected2 = "<img class=\"latex\" src=\"anki-images/latex-6a3ac365210c170e4573d6f669410f5812e87aff.png\">"; String result2 = sample2.replaceAll("(<img.+?src=\")([^\"]+)\"", "$1anki-images/$2\""); Assert.assertEquals(null, expected2, result2); }
DialogsDataSource extends SlingSafeMethodsServlet { @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { try { Resource resource = request.getResource(); ResourceResolver resolver = request.getResourceResolver(); ValueMap properties = resource.getValueMap(); String itemResourceType = properties.get("itemResourceType", String.class); String path = properties.get("path", String.class); if (StringUtils.isEmpty(path)) { log.warn("Path unavailable"); return; } path = expressionResolver.resolve(path, request.getLocale(), String.class, request); setDataSource(resource, path, resolver, request, itemResourceType); } catch (RepositoryException e) { log.warn("Unable to list classic dialogs", e.getMessage()); } } }
@Test public void testDoGet() throws Exception { List<String> expectedDialogPaths = new ArrayList<String>(); expectedDialogPaths.addAll(Arrays.asList( DIALOGS_ROOT + "/classic/dialog", DIALOGS_ROOT + "/classic/design_dialog", DIALOGS_ROOT + "/coral2/cq:dialog", DIALOGS_ROOT + "/coral2/cq:design_dialog", DIALOGS_ROOT + "/level1/classicandcoral2/cq:dialog", DIALOGS_ROOT + "/level1/classicandcoral2/cq:design_dialog", DIALOGS_ROOT + "/level1/converted/dialog", DIALOGS_ROOT + "/level1/converted/cq:design_dialog.coral2", DIALOGS_ROOT + "/level1/coral2andbackup/cq:dialog")); dialogsDataSource.doGet(request, response); ArgumentCaptor<DataSource> dataSourceArgumentCaptor = ArgumentCaptor.forClass(DataSource.class); Mockito.verify(request).setAttribute(Mockito.anyString(), dataSourceArgumentCaptor.capture()); DataSource dialogsDataSource = dataSourceArgumentCaptor.getValue(); @SuppressWarnings("unchecked") List<Resource> dialogsList = IteratorUtils.toList(dialogsDataSource.iterator()); assertEquals(expectedDialogPaths.size(), dialogsList.size()); for (Resource dialogResource : dialogsList) { ValueMap valueMap = dialogResource.getValueMap(); assertNotNull(valueMap.get("dialogPath")); assertNotNull(valueMap.get("type")); assertNotNull(valueMap.get("href")); assertNotNull(valueMap.get("converted")); assertNotNull(valueMap.get("crxHref")); expectedDialogPaths.remove(valueMap.get("dialogPath")); } assertEquals(0, expectedDialogPaths.size()); }
NodeBasedRewriteRule implements DialogRewriteRule { public Node applyTo(Node root, Set<Node> finalNodes) throws DialogRewriteException, RepositoryException { if (!ruleNode.hasNode("replacement")) { throw new DialogRewriteException("The rule does not define a replacement node"); } Node replacement = ruleNode.getNode("replacement"); if (!replacement.hasNodes()) { root.remove(); return null; } boolean treeIsFinal = false; if (replacement.hasProperty(PROPERTY_IS_FINAL)) { treeIsFinal = replacement.getProperty(PROPERTY_IS_FINAL).getBoolean(); } Node parent = root.getParent(); String rootName = root.getName(); DialogRewriteUtils.rename(root); Node replacementNext = replacement.getNodes().nextNode(); Node copy = JcrUtil.copy(replacementNext, parent, rootName); if (replacement.hasProperty(PROPERTY_COMMON_ATTRS)) { addCommonAttrMappings(root, copy); } if (replacement.hasProperty(PROPERTY_RENDER_CONDITION)) { if (root.hasNode(NN_GRANITE_RENDER_CONDITION) || root.hasNode(NN_RENDER_CONDITION)) { Node renderConditionRoot = root.hasNode(NN_GRANITE_RENDER_CONDITION) ? root.getNode(NN_GRANITE_RENDER_CONDITION) : root.getNode(NN_RENDER_CONDITION); Node renderConditionCopy = JcrUtil.copy(renderConditionRoot, copy, NN_GRANITE_RENDER_CONDITION); TreeTraverser renderConditionTraverser = new TreeTraverser(renderConditionCopy); Iterator<Node> renderConditionIterator = renderConditionTraverser.iterator(); while (renderConditionIterator.hasNext()) { Node renderConditionNode = renderConditionIterator.next(); String resourceType = renderConditionNode.getProperty(ResourceResolver.PROPERTY_RESOURCE_TYPE).getString(); if (resourceType.startsWith(RENDER_CONDITION_CORAL2_RESOURCE_TYPE_PREFIX)) { resourceType = resourceType.replace(RENDER_CONDITION_CORAL2_RESOURCE_TYPE_PREFIX, RENDER_CONDITION_CORAL3_RESOURCE_TYPE_PREFIX); renderConditionNode.setProperty(ResourceResolver.PROPERTY_RESOURCE_TYPE, resourceType); } } } } Map<String, String> mappings = new HashMap<String, String>(); TreeTraverser traverser = new TreeTraverser(copy); Iterator<Node> nodeIterator = traverser.iterator(); while (nodeIterator.hasNext()) { Node node = nodeIterator.next(); PropertyIterator propertyIterator = node.getProperties(); Node rewritePropertiesNode = null; if (node.hasNode(NN_CQ_REWRITE_PROPERTIES)) { rewritePropertiesNode = node.getNode(NN_CQ_REWRITE_PROPERTIES); } while (propertyIterator.hasNext()) { Property property = propertyIterator.nextProperty(); if (property.getDefinition().isProtected()) { continue; } if (PROPERTY_MAP_CHILDREN.equals(property.getName())) { mappings.put(property.getString(), node.getPath()); property.remove(); continue; } if (PROPERTY_IS_FINAL.equals(property.getName())) { if (!treeIsFinal) { finalNodes.add(node); } property.remove(); continue; } Property mappedProperty = mapProperty(root, property); if (mappedProperty != null && rewritePropertiesNode != null) { if (rewritePropertiesNode.hasProperty("./" + mappedProperty.getName())) { rewriteProperty(property, rewritePropertiesNode.getProperty("./" + mappedProperty.getName())); } } } if (rewritePropertiesNode != null) { rewritePropertiesNode.remove(); } } Session session = root.getSession(); for (Map.Entry<String, String> mapping : mappings.entrySet()) { if (!root.hasNode(mapping.getKey())) { continue; } Node source = root.getNode(mapping.getKey()); Node destination = session.getNode(mapping.getValue()); NodeIterator iterator = source.getNodes(); while (iterator.hasNext()) { Node child = iterator.nextNode(); JcrUtil.copy(child, destination, child.getName()); } } if (treeIsFinal) { traverser = new TreeTraverser(copy); nodeIterator = traverser.iterator(); while (nodeIterator.hasNext()) { finalNodes.add(nodeIterator.next()); } } root.remove(); return copy; } NodeBasedRewriteRule(Node ruleNode); boolean matches(Node root); Node applyTo(Node root, Set<Node> finalNodes); @Override String toString(); int getRanking(); }
@Test public void testRewriteCommonAttrs() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/rewriteCommonAttrs").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/rewriteCommonAttrs").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNodes = new LinkedHashSet<Node>(); Node rewrittenNode = rule.applyTo(rootNode, finalNodes); final String[] expectedPropertyNames = {"granite:id", "granite:rel", "granite:class", "granite:title", "granite:hidden", "granite:itemscope", "granite:itemtype", "granite:itemprop"}; for (String expectedPropertyName: expectedPropertyNames) { assertTrue(rewrittenNode.hasProperty(expectedPropertyName)); } assertEquals("id", rewrittenNode.getProperty("granite:id").getValue().getString()); assertEquals(true, rewrittenNode.getProperty("granite:hidden").getValue().getBoolean()); } @Test public void testRewriteCommonAttrsData() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/rewriteCommonAttrsData").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/rewriteCommonAttrsData").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNodes = new LinkedHashSet<Node>(); Node rewrittenNode = rule.applyTo(rootNode, finalNodes); assertTrue(rewrittenNode.hasNode("granite:data")); Node dataNode = rewrittenNode.getNode("granite:data"); assertTrue(dataNode.hasProperty("attr-1")); assertTrue(dataNode.hasProperty("attr-2")); assertEquals("attr-1-value", dataNode.getProperty("attr-1").getValue().getString()); assertEquals("attr-2-value", dataNode.getProperty("attr-2").getValue().getString()); } @Test public void testRewriteRenderCondition() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/rewriteRenderCondition").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/rewriteRenderCondition").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNodes = new LinkedHashSet<Node>(); Node rewrittenNode = rule.applyTo(rootNode, finalNodes); assertTrue(rewrittenNode.hasNode("granite:rendercondition")); } @Test public void testMapProperties() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/mapProperties").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/mapProperties").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNodes = new LinkedHashSet<Node>(); Node rewrittenNode = rule.applyTo(rootNode, finalNodes); assertEquals("map-property-1", rewrittenNode.getProperty("map-property-simple").getValue().getString()); } @Test public void testMapPropertiesNested() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/mapProperties").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/mapProperties").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNodes = new LinkedHashSet<Node>(); Node rewrittenNode = rule.applyTo(rootNode, finalNodes); assertEquals("map-property-3", rewrittenNode.getProperty("map-property-nested").getValue().getString()); } @Test public void testMapPropertiesNegation() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/mapProperties").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/mapProperties").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNodes = new LinkedHashSet<Node>(); Node rewrittenNode = rule.applyTo(rootNode, finalNodes); assertFalse(rewrittenNode.getProperty("map-property-negation").getValue().getBoolean()); } @Test public void testMapPropertiesDefault() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/mapProperties").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/mapProperties").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNodes = new LinkedHashSet<Node>(); Node rewrittenNode = rule.applyTo(rootNode, finalNodes); assertEquals("default", rewrittenNode.getProperty("map-property-default").getValue().getString()); assertEquals("default", rewrittenNode.getProperty("map-property-default-quoted").getValue().getString()); } @Test public void testMapPropertiesMultiple() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/mapProperties").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/mapProperties").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNodes = new LinkedHashSet<Node>(); Node rewrittenNode = rule.applyTo(rootNode, finalNodes); assertEquals("map-property-1", rewrittenNode.getProperty("map-property-multiple").getValue().getString()); assertEquals("default", rewrittenNode.getProperty("map-property-multiple-default").getValue().getString()); assertFalse(rewrittenNode.getProperty("map-property-multiple-negation").getValue().getBoolean()); } @Test public void testRewriteProperties() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/rewriteProperties").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/rewriteProperties").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNodes = new LinkedHashSet<Node>(); Node rewrittenNode = rule.applyTo(rootNode, finalNodes); String removePrefix = rewrittenNode.getProperty("rewrite-remove-prefix").getValue().getString(); String removeSuffix = rewrittenNode.getProperty("rewrite-remove-suffix").getValue().getString(); String concatTokens = rewrittenNode.getProperty("rewrite-concat-tokens").getValue().getString(); String singleOperand = rewrittenNode.getProperty("rewrite-single-operand").getValue().getString(); String rewriteBoolean = rewrittenNode.getProperty("rewrite-boolean").getValue().getString(); assertFalse(rewrittenNode.hasNode("cq:rewriteProperties")); assertEquals("token", removePrefix); assertEquals("token", removeSuffix); assertEquals("token1token2", concatTokens); assertEquals("prefix-token", singleOperand); assertEquals("true", rewriteBoolean); } @Test public void testRewriteFinal() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/rewriteFinal").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/simple").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNodes = new LinkedHashSet<Node>(); rule.applyTo(rootNode, finalNodes); Node[] finalNodesArray = finalNodes.toArray(new Node[0]); assertEquals(1, finalNodesArray.length); assertEquals("simple", finalNodesArray[0].getName()); } @Test public void testRewriteFinalOnReplacement() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/rewriteFinalOnReplacement").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/simple").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNodes = new LinkedHashSet<Node>(); rule.applyTo(rootNode, finalNodes); Node[] finalNodesArray = finalNodes.toArray(new Node[0]); assertEquals(2, finalNodesArray.length); assertEquals("simple", finalNodesArray[0].getName()); assertEquals("items", finalNodesArray[1].getName()); } @Test public void testRewriteMapChildren() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/rewriteMapChildren").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/rewriteMapChildren").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); Set<Node> finalNodes = new LinkedHashSet<Node>(); Node rewrittenNode = rule.applyTo(rootNode, finalNodes); Node itemsNode = rewrittenNode.getNode("items"); assertTrue(itemsNode.hasNodes()); NodeIterator nodeIterator = itemsNode.getNodes(); int itemCount = 0; while(nodeIterator.hasNext()) { itemCount++; nodeIterator.next(); } assertEquals(2, itemCount); }
NodeBasedRewriteRule implements DialogRewriteRule { @Override public String toString() { String path = null; try { path = ruleNode.getPath(); } catch (RepositoryException e) { } return "NodeBasedRewriteRule[" + (path == null ? "" : "path=" +path + ",") + "ranking=" + getRanking() + "]"; } NodeBasedRewriteRule(Node ruleNode); boolean matches(Node root); Node applyTo(Node root, Set<Node> finalNodes); @Override String toString(); int getRanking(); }
@Test public void testToString() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/simple").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/simple").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); String expected = "NodeBasedRewriteRule[path=" + RULES_PATH + "/simple,ranking=" + Integer.MAX_VALUE + "]"; assertEquals(expected, rule.toString()); }
DialogRewriteUtils { public static DialogType getDialogType(Node node) throws RepositoryException { DialogType type = DialogType.UNKNOWN; if (node == null) { return type; } String name = node.getName(); if (Arrays.asList(CLASSIC_DIALOG_NAMES).contains(name) && NT_DIALOG.equals(node.getPrimaryNodeType().getName())) { type = DialogType.CLASSIC; } else if (Arrays.asList(DIALOG_NAMES).contains(name) && node.hasNode("content")) { Node contentNode = node.getNode("content"); type = DialogType.CORAL_2; if (contentNode != null) { if (contentNode.hasProperty(ResourceResolver.PROPERTY_RESOURCE_TYPE)) { String resourceType = contentNode.getProperty(ResourceResolver.PROPERTY_RESOURCE_TYPE).getString(); type = resourceType.startsWith(DIALOG_CONTENT_RESOURCETYPE_PREFIX_CORAL3) ? DialogType.CORAL_3 : DialogType.CORAL_2; } } } return type; } static boolean hasXtype(Node node, String xtype); static boolean hasType(Node node, String type); static boolean hasPrimaryType(Node node, String typeName); static void rename(Node node); static Property copyProperty(Node source, String relPropertyPath, Node destination, String name); static DialogType getDialogType(Node node); static boolean isDesignDialog(Node node); static final String CORAL_2_BACKUP_SUFFIX; static final String NT_DIALOG; static final String NN_CQ_DIALOG; static final String NN_CQ_DESIGN_DIALOG; static final String DIALOG_CONTENT_RESOURCETYPE_PREFIX_CORAL3; }
@Test public void testGetDialogTypeClassic() throws Exception { boolean allClassic = false; String[] classicDialogPaths = { DIALOGS_ROOT + "/classic/dialog", DIALOGS_ROOT + "/classic/design_dialog" }; for (String path: classicDialogPaths) { Resource resource = context.resourceResolver().getResource(path); Node node = resource.adaptTo(Node.class); DialogType type = DialogRewriteUtils.getDialogType(node); allClassic = (type == DialogType.CLASSIC); if (!allClassic) { break; } } assertTrue(allClassic); } @Test public void testGetDialogTypeCoral2() throws Exception { boolean allCoral2 = false; String[] coral2DialogPaths = { DIALOGS_ROOT + "/coral2/cq:dialog", DIALOGS_ROOT + "/coral2/cq:design_dialog", DIALOGS_ROOT + "/backupsnoreplacementdiscarded/cq:dialog.coral2", DIALOGS_ROOT + "/backupsnoreplacementdiscarded/cq:design_dialog.coral2", DIALOGS_ROOT + "/level1/classicandcoral2/cq:dialog", DIALOGS_ROOT + "/level1/classicandcoral2/cq:design_dialog" }; for (String path: coral2DialogPaths) { Resource resource = context.resourceResolver().getResource(path); Node node = resource.adaptTo(Node.class); DialogType type = DialogRewriteUtils.getDialogType(node); allCoral2 = (type == DialogType.CORAL_2); if (!allCoral2) { break; } } assertTrue(allCoral2); } @Test public void testGetDialogTypeCoral3() throws Exception { boolean allCoral3 = false; String[] coral3DialogPaths = { DIALOGS_ROOT + "/level1/converted/cq:dialog", DIALOGS_ROOT + "/level1/converted/cq:design_dialog" }; for (String path: coral3DialogPaths) { Resource resource = context.resourceResolver().getResource(path); Node node = resource.adaptTo(Node.class); DialogType type = DialogRewriteUtils.getDialogType(node); allCoral3 = (type == DialogType.CORAL_3); if (!allCoral3) { break; } } assertTrue(allCoral3); }
NodeBasedRewriteRule implements DialogRewriteRule { public int getRanking() { if (ranking == null) { try { if (ruleNode.hasProperty(PROPERTY_RANKING)) { long ranking = ruleNode.getProperty(PROPERTY_RANKING).getLong(); this.ranking = new Long(ranking).intValue(); } else { this.ranking = Integer.MAX_VALUE; } } catch (RepositoryException e) { logger.warn("Caught exception while reading the " + PROPERTY_RANKING + " property"); } } return this.ranking; } NodeBasedRewriteRule(Node ruleNode); boolean matches(Node root); Node applyTo(Node root, Set<Node> finalNodes); @Override String toString(); int getRanking(); }
@Test public void testGetRanking() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/simple").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/simple").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); assertEquals(Integer.MAX_VALUE, rule.getRanking()); }
DialogRewriteUtils { public static boolean isDesignDialog(Node node) throws RepositoryException { if (node == null) { return false; } String name = node.getName(); return name.equals(NameConstants.NN_DESIGN_DIALOG) || name.equals(NN_CQ_DESIGN_DIALOG) || name.equals(NN_CQ_DESIGN_DIALOG + CORAL_2_BACKUP_SUFFIX); } static boolean hasXtype(Node node, String xtype); static boolean hasType(Node node, String type); static boolean hasPrimaryType(Node node, String typeName); static void rename(Node node); static Property copyProperty(Node source, String relPropertyPath, Node destination, String name); static DialogType getDialogType(Node node); static boolean isDesignDialog(Node node); static final String CORAL_2_BACKUP_SUFFIX; static final String NT_DIALOG; static final String NN_CQ_DIALOG; static final String NN_CQ_DESIGN_DIALOG; static final String DIALOG_CONTENT_RESOURCETYPE_PREFIX_CORAL3; }
@Test public void testIsDesignDialog() throws Exception { boolean allDesignDialogs = false; String[] designDialogPaths = { DIALOGS_ROOT + "/classic/design_dialog", DIALOGS_ROOT + "/coral2/cq:design_dialog", DIALOGS_ROOT + "/backupsnoreplacementdiscarded/cq:design_dialog.coral2", DIALOGS_ROOT + "/level1/classicandcoral2/design_dialog", DIALOGS_ROOT + "/level1/classicandcoral2/cq:design_dialog" }; for (String path: designDialogPaths) { Resource resource = context.resourceResolver().getResource(path); Node node = resource.adaptTo(Node.class); allDesignDialogs = DialogRewriteUtils.isDesignDialog(node); if (!allDesignDialogs) { break; } } assertTrue(allDesignDialogs); }
DialogConversionServlet extends SlingAllMethodsServlet { private List<DialogRewriteRule> getRules(ResourceResolver resolver) throws ServletException { final List<DialogRewriteRule> rules = new LinkedList<DialogRewriteRule>(); synchronized (this.rules) { rules.addAll(this.rules); } int nb = rules.size(); Resource resource = resolver.getResource(RULES_SEARCH_PATH); if (resource != null) { try { Node rulesContainer = resource.adaptTo(Node.class); NodeIterator iterator = rulesContainer.getNodes(); while (iterator.hasNext()) { Node nextNode = iterator.nextNode(); if (isFolder(nextNode)) { NodeIterator nodeIterator = nextNode.getNodes(); while (nodeIterator.hasNext()) { Node nestedNode = nodeIterator.nextNode(); if (!isFolder(nestedNode)) { rules.add(new NodeBasedRewriteRule(nestedNode)); } } } else { rules.add(new NodeBasedRewriteRule(nextNode)); } } } catch (RepositoryException e) { throw new ServletException("Caught exception while collecting rewrite rules", e); } } Collections.sort(rules, new RuleComparator()); logger.debug("Found {} rules ({} Java-based, {} node-based)", nb, rules.size() - nb); for (DialogRewriteRule rule : rules) { logger.debug(rule.toString()); } return rules; } @SuppressWarnings("unused") void bindRule(DialogRewriteRule rule); @SuppressWarnings("unused") void unbindRule(DialogRewriteRule rule); static final String RULES_SEARCH_PATH; static final String PARAM_PATHS; }
@Test public void testGetRules() throws Exception { List<String> expectedRulePaths = new ArrayList<String>(); expectedRulePaths.addAll(Arrays.asList( RULES_PATH + "/rewriteRanking", RULES_PATH + "/simple", RULES_PATH + "/rewriteOptional", RULES_PATH + "/rewriteFinal", RULES_PATH + "/rewriteFinalOnReplacement", RULES_PATH + "/rewriteMapChildren", RULES_PATH + "/rewriteCommonAttrs", RULES_PATH + "/rewriteCommonAttrsData", RULES_PATH + "/rewriteRenderCondition", RULES_PATH + "/mapProperties", RULES_PATH + "/rewriteProperties", RULES_PATH + "/nested1/rule1", RULES_PATH + "/nested1/rule2", RULES_PATH + "/nested2/rule1")); Class[] cArgs = new Class[1]; cArgs[0] = ResourceResolver.class; Method method = dialogConversionServlet.getClass().getDeclaredMethod("getRules", cArgs); method.setAccessible(true); Object[] args = new Object[1]; args[0] = context.resourceResolver(); List<DialogRewriteRule> rules = (List<DialogRewriteRule>) method.invoke(dialogConversionServlet, args); assertEquals(expectedRulePaths.size(), rules.size()); int index = 0; for (DialogRewriteRule rule : rules) { String path = expectedRulePaths.get(index); assertTrue(rule.toString().contains("path=" + path + ",")); index++; } }
NodeBasedRewriteRule implements DialogRewriteRule { public boolean matches(Node root) throws RepositoryException { if (!ruleNode.hasNode("patterns")) { return false; } Node patterns = ruleNode.getNode("patterns"); if (!patterns.hasNodes()) { return false; } NodeIterator iterator = patterns.getNodes(); while (iterator.hasNext()) { Node pattern = iterator.nextNode(); if (matches(root, pattern)) { return true; } } return false; } NodeBasedRewriteRule(Node ruleNode); boolean matches(Node root); Node applyTo(Node root, Set<Node> finalNodes); @Override String toString(); int getRanking(); }
@Test public void testRewriteOptional() throws Exception { Node ruleNode = context.resourceResolver().getResource(RULES_PATH + "/rewriteOptional").adaptTo(Node.class); Node rootNode = context.resourceResolver().getResource(ROOTS_PATH + "/simple").adaptTo(Node.class); NodeBasedRewriteRule rule = new NodeBasedRewriteRule(ruleNode); assertTrue(rule.matches(rootNode)); Node itemsNode = ruleNode.getNode("patterns/pattern/items"); itemsNode.getProperty("cq:rewriteOptional").remove(); rule = new NodeBasedRewriteRule(ruleNode); assertFalse(rule.matches(rootNode)); }
StringUtils { public static int tokenOverlap(String[] tokens1, String[] tokens2) { Set<String> tokenSet2 = new HashSet<String>(Arrays.asList(tokens2)); int score = 0; for (String word : tokens1) if (tokenSet2.contains(word)) score++; return score; } static int tokenOverlap(String[] tokens1, String[] tokens2); static int tokenOverlapExp(String[] tokens1, String[] tokens2); static int findOverlap(String[] tokens1, int i, String[] tokens2, int j); }
@Test public void testTokenOverlapDouble() { String[] tokens1 = {"the", "cat", "has", "a", "brown", "bag"}; String[] tokens2 = {"bag", "dog", "was", "the", "blah", "bag"}; assertEquals(2, StringUtils.tokenOverlap(tokens1, tokens2)); } @Test public void testTokenOverlapSingle() { String[] tokens1 = {"the", "cat", "has", "a", "brown", "bag"}; String[] tokens2 = {"chicken", "dog", "was", "the", "blah", "bag"}; assertEquals(2, StringUtils.tokenOverlap(tokens1, tokens2)); } @Test public void testTokenOverlapMixed() { String[] tokens1 = {"the", "cat", "has", "a", "brown", "bag"}; String[] tokens2 = {"bag", "dog", "was", "cat", "blah", "bag"}; assertEquals(2, StringUtils.tokenOverlap(tokens1, tokens2)); }
StringPair implements Comparable, WritableComparable { public int compareTo(Object o) { return compareTo((StringPair) o); } StringPair(); StringPair(String x, String y); int compareTo(Object o); void write(DataOutput out); void readFields(DataInput in); int compareTo(StringPair w); boolean equals(Object o); int hashCode(); static StringPair fromString(String text); String toString(); public String x; public String y; }
@Test public void testCompareToFirstEqual() { StringPair pair1 = new StringPair("cat", "alpha"); StringPair pair2 = new StringPair("cat", "dog"); assertTrue(pair1.compareTo(pair2) < 0); } @Test public void testCompareToBothEqual() { StringPair pair1 = new StringPair("cat", "dog"); StringPair pair2 = new StringPair("cat", "dog"); assertTrue(pair1.compareTo(pair2) == 0); } @Test public void testCompareToFirstDiffer() { StringPair pair1 = new StringPair("cat", "alpha"); StringPair pair2 = new StringPair("cats", "dog"); assertTrue(pair1.compareTo(pair2) < 0); }
StringPair implements Comparable, WritableComparable { public boolean equals(Object o) { if (o == null || !(o instanceof StringPair)) return false; StringPair p = (StringPair)o; return (x == p.x || (x != null && x.equals(p.x))) && (y == p.y || (y != null && y.equals(p.y))); } StringPair(); StringPair(String x, String y); int compareTo(Object o); void write(DataOutput out); void readFields(DataInput in); int compareTo(StringPair w); boolean equals(Object o); int hashCode(); static StringPair fromString(String text); String toString(); public String x; public String y; }
@Test public void testEqualsNull() { StringPair pair1 = new StringPair(); StringPair pair2 = new StringPair(); assertTrue(pair1.equals(pair2)); } @Test public void testEqualsBothMatch() { StringPair pair1 = new StringPair("cat", "dog"); StringPair pair2 = new StringPair("cat", "dog"); assertTrue(pair1.equals(pair2)); } @Test public void testEqualsBothDiffer() { StringPair pair1 = new StringPair("cat", "dog"); StringPair pair2 = new StringPair("dog", "cat"); assertFalse(pair1.equals(pair2)); } @Test public void testEqualsFirstMatchSecondNull() { StringPair pair1 = new StringPair("cat", null); StringPair pair2 = new StringPair("cat", null); assertTrue(pair1.equals(pair2)); } @Test public void testEqualsFirstMatchSecondDiffer() { StringPair pair1 = new StringPair("cat", "cat"); StringPair pair2 = new StringPair("cat", "c"); assertFalse(pair1.equals(pair2)); } @Test public void testEqualsFirstNullSecondMatch() { StringPair pair1 = new StringPair(null, "cat"); StringPair pair2 = new StringPair(null, "cat"); assertTrue(pair1.equals(pair2)); } @Test public void testEqualsFirstNullSecondDiffer() { StringPair pair1 = new StringPair(null, "c"); StringPair pair2 = new StringPair(null, "cat"); assertFalse(pair1.equals(pair2)); }
StringPair implements Comparable, WritableComparable { public String toString() { return "{" + x.replaceAll(",", "&comma;") + ", " + y.replaceAll(",", "&comma;") + "}"; } StringPair(); StringPair(String x, String y); int compareTo(Object o); void write(DataOutput out); void readFields(DataInput in); int compareTo(StringPair w); boolean equals(Object o); int hashCode(); static StringPair fromString(String text); String toString(); public String x; public String y; }
@Test public void testToString() { StringPair pair = new StringPair("c,at", "dog,"); assertEquals("{c&comma;at, dog&comma;}", pair.toString()); }
StringPair implements Comparable, WritableComparable { public static StringPair fromString(String text) { text = text.trim(); text = text.substring(1, text.length() - 1); String[] parts = text.split(", ", 2); return new StringPair(parts[0].replaceAll("&comma;", ","), parts[1].replaceAll("&comma;", ",")); } StringPair(); StringPair(String x, String y); int compareTo(Object o); void write(DataOutput out); void readFields(DataInput in); int compareTo(StringPair w); boolean equals(Object o); int hashCode(); static StringPair fromString(String text); String toString(); public String x; public String y; }
@Test public void testFromString() { StringPair pair = StringPair.fromString( "{c&comma;at, dog&comma;}"); assertEquals("c,at", pair.x); assertEquals("dog,", pair.y); }
ExtendedList extends AbstractList<T> { public boolean add(T e) { return extendedItems.add(e); } ExtendedList(List<T> baseItems); boolean add(T e); T get(int index); int size(); }
@Test public void testAdd() { List<String> extendedList = new ExtendedList<String>(array1); for (String s : array2) assertTrue(extendedList.add(s)); assertEquals(3, array1.size()); } @Test public void testIterator() { List<String> extendedList = new ExtendedList<String>(array1); for (String s : array2) extendedList.add(s); Iterator<String> comboIter = extendedList.iterator(); Iterator<String> iter1 = array1.iterator(); Iterator<String> iter2 = array2.iterator(); while (iter1.hasNext()) { assertTrue(comboIter.hasNext()); assertEquals(iter1.next(), comboIter.next()); } while (iter2.hasNext()) { assertTrue(comboIter.hasNext()); assertEquals(iter2.next(), comboIter.next()); } }
ExtendedList extends AbstractList<T> { public int size() { return baseItems.size() + extendedItems.size(); } ExtendedList(List<T> baseItems); boolean add(T e); T get(int index); int size(); }
@Test public void testSize() { List<String> extendedList = new ExtendedList<String>(array1); assertEquals(array1.size(), extendedList.size()); int size = array1.size(); for (String s : array2) { extendedList.add(s); assertEquals(++size, extendedList.size()); } }
ExtendedList extends AbstractList<T> { public T get(int index) { return (index < baseItems.size()) ? baseItems.get(index) : extendedItems.get(index - baseItems.size()); } ExtendedList(List<T> baseItems); boolean add(T e); T get(int index); int size(); }
@Test public void testGet() { List<String> extendedList = new ExtendedList<String>(array1); for (int i = 0; i < array1.size(); ++i) assertEquals(array1.get(i), extendedList.get(i)); for (String s : array2) extendedList.add(s); for (int i = 0; i < array1.size(); ++i) assertEquals(array1.get(i), extendedList.get(i)); for (int i = 0; i < array2.size(); ++i) assertEquals(array2.get(i), extendedList.get(i + array1.size())); }
SenseEval2007DocumentReader implements DocumentReader { public Document readDocument(String doc) { return readDocument(doc, corpusName()); } String corpusName(); Document readDocument(String doc); Document readDocument(String doc, String corpusName); static final String CORPUS_NAME; }
@Test public void testReadDocument() { DocumentReader reader = new SenseEval2007DocumentReader(); Document doc = reader.readDocument(TEST_SENT); assertEquals("explain.v.4", doc.key()); assertEquals("explain", doc.title()); assertEquals(3, doc.id()); assertEquals(TEST_SENT, doc.originalText()); assertEquals("senseEval2007", doc.sourceCorpus()); assertTrue(doc.rawText().contains("explain ")); assertFalse(doc.rawText().contains("head")); }
SemEval2010TrainDocumentReader implements DocumentReader { public Document readDocument(String doc) { return readDocument(doc, corpusName()); } SemEval2010TrainDocumentReader(); String corpusName(); Document readDocument(String doc); Document readDocument(String doc, String corpusName); static final String CORPUS_NAME; }
@Test public void testRead() { DocumentReader reader = new SemEval2010TrainDocumentReader(); Document doc = reader.readDocument(TEST_SENT); assertEquals("class.n.4", doc.key()); assertFalse(doc.rawText().contains("class.n.4")); assertTrue(doc.rawText().contains("Ltd.")); assertEquals("semeval2010_train", doc.sourceCorpus()); }
UkWacDocumentReader implements DocumentReader { public gov.llnl.ontology.text.Document readDocument(String doc) { return readDocument(doc, corpusName()); } String corpusName(); gov.llnl.ontology.text.Document readDocument(String doc); gov.llnl.ontology.text.Document readDocument(String doc, String corpusName); static final String CORPUS_NAME; }
@Test public void testReader() { DocumentReader reader = new UkWacDocumentReader(); Document doc = reader.readDocument(INPUT); assertEquals("ukwac:http: assertEquals("ukwac:http: assertEquals(22, doc.rawText().split("\\s+").length); assertEquals(INPUT, doc.originalText()); assertEquals(UkWacDocumentReader.CORPUS_NAME, doc.sourceCorpus()); }
PubMedDocumentReader extends DefaultHandler implements DocumentReader { public Document readDocument(String originalText, String corpusName) { inAbstract = false; inTitle = false; inPMID = false; inTitle = false; labels.clear(); b.setLength(0); try { saxParser.parse(new InputSource(new StringReader(originalText)), this); } catch (SAXException se) { throw new RuntimeException(se); } catch (IOException ioe) { throw new IOError(ioe); } return new SimpleDocument(corpusName, docText, originalText, key, id, title, labels); } PubMedDocumentReader(); Document readDocument(String originalText, String corpusName); Document readDocument(String originalText); @Override void startElement(String uri, String localName, String name, Attributes atts); @Override void characters(char[] ch, int start, int length); @Override void endElement(String uri, String localName, String name); }
@Test public void readDocument() { DocumentReader reader = new PubMedDocumentReader(); Document doc = reader.readDocument(DOCUMENT_ONE); assertEquals("pubmed", doc.sourceCorpus()); assertEquals(12345, doc.id()); assertEquals("12345", doc.key()); assertEquals("CHICKEN", doc.title()); assertEquals("And once there was a chicken.", doc.rawText()); assertEquals(DOCUMENT_ONE, doc.originalText()); assertEquals(2, doc.categories().size()); assertTrue(doc.categories().contains("Anit-Chicken Agents")); assertTrue(doc.categories().contains("Non-geese")); doc = reader.readDocument(DOCUMENT_TWO); assertEquals("pubmed", doc.sourceCorpus()); assertEquals(62345, doc.id()); assertEquals("62345", doc.key()); assertEquals("CHICKENS ATTACK", doc.title()); assertEquals("A flock of chickens have attacked new york.", doc.rawText()); assertEquals(DOCUMENT_TWO, doc.originalText()); assertEquals(2, doc.categories().size()); assertTrue(doc.categories().contains("Human-Chicken Resistance")); assertTrue(doc.categories().contains("Pro-Fowl")); }
TextUtil { public static String cleanTerm(String term) { term = term.toLowerCase().trim(); if (term.matches("[0-9\\-\\.:]+")) return "<NUM>"; if (term.startsWith("http:") || term.startsWith("ftp:")) return "<URL>"; while (term.length() > 0 && term.startsWith("-")) term = term.substring(1, term.length()); while (term.length() > 0 && term.endsWith("-")) term = term.substring(0, term.length()-1); term = term.replaceAll("\"", ""); term = term.replaceAll("\'", ""); term = term.replaceAll("\\[", ""); term = term.replaceAll("\\]", ""); term = term.replaceAll("\\?", ""); term = term.replaceAll("\\*", ""); term = term.replaceAll("\\(", ""); term = term.replaceAll("\\)", ""); term = term.replaceAll("\\^", ""); term = term.replaceAll("\\+", ""); term = term.replaceAll(" term = term.replaceAll(";", ""); term = term.replaceAll("%", ""); term = term.replaceAll(",", ""); term = term.replaceAll("!", ""); return term.trim(); } static String cleanTerm(String term); }
@Test public void testNumClean() { String[] numbers = { "1900", ":123", "1-2", "1.2", "10000:", "125121", ".123", "123.", }; for (String number : numbers) assertEquals("<NUM>", TextUtil.cleanTerm(number)); }
Sentence implements Serializable, Iterable<Annotation> { public String sentenceText() { return (text == null) ? null : text.substring(start, end); } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText, String tokenText); static StringPair writeSentences(List<Sentence> sentences); }
@Test public void testSentenceText() { Sentence sent = new Sentence(2, 10, 8); String text = "abcdefghijlkmop"; sent.setText(text); assertEquals(text.substring(2, 10), sent.sentenceText()); }
Sentence implements Serializable, Iterable<Annotation> { public Annotation getAnnotation(int index) { return tokenAnnotations[index]; } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText, String tokenText); static StringPair writeSentences(List<Sentence> sentences); }
@Test public void testEmptyGet() { Sentence sent = new Sentence(0, 100, 1); assertEquals(null, sent.getAnnotation(0)); } @Test (expected=IndexOutOfBoundsException.class) public void testNegativeGet() { Sentence sent = new Sentence(0, 100, 1); sent.getAnnotation(-1); } @Test (expected=IndexOutOfBoundsException.class) public void testTooLargeGet() { Sentence sent = new Sentence(0, 100, 1); sent.getAnnotation(1); }
Sentence implements Serializable, Iterable<Annotation> { public void addAnnotation(int index, Annotation annotation) { tokenAnnotations[index] = annotation; } private Sentence(); Sentence(int start, int end, int numTokens); void setText(String text); String sentenceText(); void addAnnotation(int index, Annotation annotation); Annotation getAnnotation(int index); DependencyTreeNode[] dependencyParseTree(); StringPair[] taggedTokens(); Iterator<Annotation> iterator(); int start(); int end(); int numTokens(); static List<Sentence> readSentences(String sentenceText, String tokenText); static StringPair writeSentences(List<Sentence> sentences); }
@Test (expected=IndexOutOfBoundsException.class) public void testNegativeSet() { Sentence sent = new Sentence(0, 100, 1); Annotation annot = new SimpleAnnotation("blah"); sent.addAnnotation(-1, annot); } @Test (expected=IndexOutOfBoundsException.class) public void testTooLargeSet() { Sentence sent = new Sentence(0, 100, 1); Annotation annot = new SimpleAnnotation("blah"); sent.addAnnotation(1, annot); }