private GetObjectStub(boolean withTypeMapping) { this.withTypeMapping = withTypeMapping; storIOSQLite = mock(StorIOSQLite.class); internal = mock(StorIOSQLite.Internal.class); when(storIOSQLite.internal()).thenReturn(internal); query = Query.builder().table("test_table").build(); rawQuery = RawQuery.builder().query("select * from who_cares").observesTables("test_table").build(); //noinspection unchecked getResolver = mock(GetResolver.class); cursor = mock(Cursor.class); item = new TestItem(); when(cursor.getCount()).thenReturn(1); when(cursor.moveToNext()) .thenAnswer( new Answer<Boolean>() { int invocationsCount = 0; @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { return invocationsCount++ < 1; } }); when(storIOSQLite.get()).thenReturn(new PreparedGet.Builder(storIOSQLite)); when(storIOSQLite.observeChangesInTables(eq(singleton(query.table())))) .thenReturn(Observable.<Changes>empty()); assertThat(rawQuery.observesTables()).isNotNull(); when(storIOSQLite.observeChangesInTables(rawQuery.observesTables())) .thenReturn(Observable.<Changes>empty()); when(getResolver.performGet(storIOSQLite, query)).thenReturn(cursor); when(getResolver.performGet(storIOSQLite, rawQuery)).thenReturn(cursor); when(getResolver.mapFromCursor(cursor)).thenReturn(item); //noinspection unchecked typeMapping = mock(SQLiteTypeMapping.class); if (withTypeMapping) { when(internal.typeMapping(TestItem.class)).thenReturn(typeMapping); when(typeMapping.getResolver()).thenReturn(getResolver); } }
@Test public void testFirstOrDefault() throws Exception { Observable.empty() .firstOrDefault(99) .subscribe( next -> print("next: %s", next), Throwable::printStackTrace, () -> print("complete!")); }
@Test public void testDistinctOfNoneWithKeySelector() { Observable<String> src = Observable.empty(); Observable.create(distinct(src, TO_UPPER_WITH_EXCEPTION)).subscribe(w); verify(w, never()).onNext(anyString()); verify(w, never()).onError(any(Throwable.class)); verify(w, times(1)).onCompleted(); }
@Test public void testDistinctOfNone() { Observable<String> src = Observable.empty(); Observable.create(distinct(src)).subscribe(w); verify(w, never()).onNext(anyString()); verify(w, never()).onError(any(Throwable.class)); verify(w, times(1)).onCompleted(); }
private Observable<V> fromMemory(User user, K key) { UserMemoryCache<K, V> userMemoryCache = userMemoryCaches.get(user); if (!userMemoryCache.containsKey(key)) { return Observable.empty(); } else { Pair<Long, V> cachedValue = userMemoryCache.get(key); long cachedSince = DateUtils.getCurrentTimestamp() - cachedValue.first; if (cachedSince < staleThreshold) { return Observable.just(userMemoryCache.get(key).second); } else { // Value has expired userMemoryCache.remove(key); return Observable.empty(); } } }
public static void main(String... args) { // initialize DiscoveryAndLoadBalancer.getFactory(); // hystrix stream => http://localhost:9999 startHystrixMetricsStream(); System.out.println("Server => Starting at http://localhost:8080/"); System.out.println(" Sample URLs: "); System.out.println(" - http://localhost:8080/device/home?userId=123"); System.out.println("----------------------------------------------------------------"); // start web services => http://localhost:8080 RxNetty.createHttpServer( 8080, (request, response) -> { if (request.getPath().contains("favicon.ico")) { return Observable.empty(); } // System.out.println("Server => Request: " + request.getPath()); return Observable.defer( () -> { HystrixRequestContext.initializeContext(); try { return handleRoutes(request, response); } catch (Throwable e) { System.err.println("Server => Error [" + request.getPath() + "] => " + e); response.setStatus(HttpResponseStatus.BAD_REQUEST); return response.writeStringAndFlush( "Error 500: Bad Request\n" + e.getMessage() + "\n"); } }) .onErrorResumeNext( error -> { System.err.println("Server => Error: " + error.getMessage()); error.printStackTrace(); return writeError(request, response, "Failed: " + error.getMessage()); }) .doOnTerminate( () -> { if (HystrixRequestContext.isCurrentThreadInitialized()) { System.out.println( "Server => Request [" + request.getPath() + "] => " + HystrixRequestLog.getCurrentRequest() .getExecutedCommandsAsString()); HystrixRequestContext.getContextForCurrentThread().shutdown(); } else { System.err.println( "HystrixRequestContext not initialized for thread: " + Thread.currentThread()); } response.close(); }); }) .startAndWait(); }
@Test public void loadEmptyRepo() { when(repo.getModificationId()).thenReturn("modif id"); when(repo.getEventsSubscribedOnProperScheduler()).thenReturn(Observable.empty()); sut.loadEvents(false, callback); List<IEvent> emptyList = new ArrayList<>(); verify(callback).onEventsLoadingStarted("modif id"); verify(callback).onEventsLoadingFinished(emptyList, "modif id"); }
@Test public void testSingleWithEmpty() { Observable<Integer> observable = Observable.<Integer>empty().single(); @SuppressWarnings("unchecked") Observer<Integer> observer = (Observer<Integer>) mock(Observer.class); observable.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onError(isA(NoSuchElementException.class)); inOrder.verifyNoMoreInteractions(); }
@Override public Observable<Message> getMessages(final ExtractionParameters parameters) { // validate parameters try { validateParameters(parameters); } catch (SocialException e) { logger.error(e); e.printStackTrace(); return Observable.empty(); } return getRunnerInstance().getMessages(parameters); }
@Test public void testSingleOrDefaultWithEmpty() { Observable<Integer> observable = Observable.<Integer>empty().singleOrDefault(1); @SuppressWarnings("unchecked") Observer<Integer> observer = (Observer<Integer>) mock(Observer.class); observable.subscribe(observer); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onNext(1); inOrder.verify(observer, times(1)).onCompleted(); inOrder.verifyNoMoreInteractions(); }
/** * @param webPageEntity * @return * @throws Exception */ @Override public Observable<ProductEntity> parse(WebPageEntity webPageEntity) { HashSet<ProductEntity> result = new HashSet<>(); try { ProductEntity product; String productName = null; String url = null; String regularPrice = null; String specialPrice = null; String productImage = null; String description = null; Map<String, String> attr = new HashMap<>(); String[] category = null; url = webPageEntity.getUrl(); Document document = Jsoup.parse(webPageEntity.getContent(), webPageEntity.getUrl()); productName = document.select(".naitem").text(); LOGGER.info("Parsing {}, page={}", productName, webPageEntity.getUrl()); if (!document.select(".outofstock").isEmpty()) { return Observable.empty(); } productImage = document.select(".itemImgDiv img.itemDetailImg").attr("abs:src"); String priceText = document.select(".itemDetailPrice").text().replace("\\xEF\\xBF\\xBD", " "); Matcher matcher = pricePattern.matcher(priceText); if (matcher.find()) { regularPrice = matcher.group().replace(",", ""); } description = document.select(".itemDescription").text(); category = getNormalizedCategories(webPageEntity); product = new ProductEntity( productName, url, regularPrice, specialPrice, productImage, description, attr, category); result.add(product); } catch (Exception e) { LOGGER.error("Failed to parse: {}", webPageEntity, e); } return Observable.from(result).doOnNext(e -> parseResultCounter.inc()); }
public Observable<SoftwareUpdateData> makeUpdate() { Observable<SoftwareUpdateData> observable = updateHandler .triggerUpdate() .flatMap( new Func1<Boolean, Observable<SoftwareUpdateData>>() { @Override public Observable<SoftwareUpdateData> call(Boolean ignored) { return refresh(); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .share(); observable.onErrorResumeNext(Observable.<SoftwareUpdateData>empty()).subscribe(); return observable; }
@Test public void testSingleDoesNotRequestMoreThanItNeedsToEmitErrorFromEmpty() { final AtomicLong request = new AtomicLong(); try { Observable.empty() .doOnRequest( new Action1<Long>() { @Override public void call(Long n) { request.addAndGet(n); } }) .toBlocking() .single(); } catch (NoSuchElementException e) { assertEquals(2, request.get()); } }
private void displayTags(List<Tag> tags_) { List<Tag> tags = inMemoryCacheService.enhanceTags(feedItem.getId(), tags_); this.tags = ImmutableList.copyOf(tags); // show tags now infoLineView.setTags(toMap(tags, tag -> Vote.NEUTRAL)); // and update tags with votes later. voteService .getTagVotes(tags) .filter(votes -> !votes.isEmpty()) .onErrorResumeNext(Observable.<Map<Long, Vote>>empty()) .compose(bindToLifecycle()) .subscribe( votes -> infoLineView.setTags( toMap(tags, tag -> firstNonNull(votes.get(tag.getId()), Vote.NEUTRAL)))); hideProgressIfLoop(tags); }
@Test public void testNextWithEmpty() { Observable<String> obs = Observable.<String>empty().observeOn(Schedulers.newThread()); Iterator<String> it = next(obs).iterator(); assertFalse(it.hasNext()); try { it.next(); fail("At the end of an iterator should throw a NoSuchElementException"); } catch (NoSuchElementException e) { } // If the observable is completed, hasNext always returns false and next always throw a // NoSuchElementException. assertFalse(it.hasNext()); try { it.next(); fail("At the end of an iterator should throw a NoSuchElementException"); } catch (NoSuchElementException e) { } }
@Override public Observable<? extends Thing<?>> findThingForId(String id) { if (!id.startsWith("projectId:")) { return Observable.empty(); } try { String id_string = id.split(":")[1]; Integer id_int = Integer.parseInt(id_string); String projectName = um.getGroup(id_int); Group g = um.getAllGroups().get(projectName); Thing<Group> groupThing = wrapGroup(g); return Observable.just(groupThing); } catch (Exception e) { throw new ThingRuntimeException( "Can't parse group id " + id + ": " + e.getLocalizedMessage()); } }
@Override public final Observable<SqlSchema> definition() { return Observable.empty(); }
@Override public Observable<ProductEntity> parse(WebPageEntity webPageEntity) { HashSet<ProductEntity> result = new HashSet<>(); try { ProductEntity product; String productName = null; String url = null; String regularPrice = null; String specialPrice = null; String productImage = null; String description = null; Map<String, String> attr = new HashMap<>(); String[] category = null; url = webPageEntity.getUrl(); Document document = Jsoup.parse(webPageEntity.getContent(), webPageEntity.getUrl()); if (!document.select(".saleImage").isEmpty()) { return Observable.empty(); } productName = document.select("div.innercontentDiv > div > div > h2").text(); if (productName.isEmpty()) { return Observable.empty(); } LOGGER.info("Parsing {}, page={}", productName, webPageEntity.getUrl()); String manufacturer = document.select(".product-details__title .product__manufacturer").text(); if (!manufacturer.isEmpty()) { attr.put("manufacturer", manufacturer); } productImage = document.select("div.imgLiquidNoFill a").attr("abs:src"); if (productImage.isEmpty()) { productImage = document.select(".es-carousel img").attr("abs:src"); } regularPrice = parsePrice( webPageEntity, document.select("#desPrice > li:nth-child(1) > span.pricetag.show").text()); specialPrice = document.select("#desPrice > li:nth-child(2) > span.pricetag.show").text(); if (!specialPrice.isEmpty()) { specialPrice = parsePrice(webPageEntity, specialPrice); } description = document.select("#TabbedPanels1 > div > div:nth-child(1)").text(); Iterator<Element> labels = document.select("table.productTbl > tbody > tr > td:nth-child(1)").iterator(); Iterator<Element> values = document.select("table.productTbl > tbody > tr > td:nth-child(2)").iterator(); while (labels.hasNext()) { String specName = CaseFormat.LOWER_UNDERSCORE.to( CaseFormat.LOWER_CAMEL, labels.next().text().replace(' ', '_').replace(":", "").trim()); String specValue = values.next().text(); if (specName.contains("department")) { category = getNormalizedCategories(webPageEntity, specValue); } else { attr.put(specName, specValue); } } if (category == null) { LOGGER.warn("Category not found"); } product = new ProductEntity( productName, url, regularPrice, specialPrice, productImage, description, attr, category); result.add(product); } catch (Exception e) { LOGGER.error("Failed to parse: {}", webPageEntity, e); } return Observable.from(result).doOnNext(e -> parseResultCounter.inc()); }
@NonNull @Override public Observable<Changes> observeChangesOfUris(@NonNull Set<Uri> uris) { return Observable.empty(); }
private Observable<Navajo> processNavajoEvent( NavajoStreamEvent n, Subscriber<? super Navajo> subscriber) { switch (n.type()) { case NAVAJO_STARTED: createHeader((NavajoHead) n.body()); return Observable.<Navajo>empty(); case MESSAGE_STARTED: Message prMessage = null; if (!messageStack.isEmpty()) { prMessage = messageStack.peek(); } String mode = (String) n.attribute("mode"); Message msg = NavajoFactory.getInstance().createMessage(assemble, n.path(), Message.MSG_TYPE_SIMPLE); msg.setMode(mode); if (prMessage == null) { assemble.addMessage(msg); } else { prMessage.addMessage(msg); } messageStack.push(msg); tagStack.push(n.path()); return Observable.<Navajo>empty(); case MESSAGE: Message msgParent = messageStack.pop(); tagStack.pop(); Msg mm = (Msg) n.body(); List<Prop> msgProps = mm.properties(); for (Prop e : msgProps) { msgParent.addProperty(createTmlProperty(e)); } for (Entry<String, Binary> e : pushBinaries.entrySet()) { msgParent.addProperty(createBinaryProperty(e.getKey(), e.getValue())); } pushBinaries.clear(); return Observable.<Navajo>empty(); case ARRAY_STARTED: tagStack.push(n.path()); String path = currentPath(); AtomicInteger cnt = arrayCounts.get(path); if (cnt == null) { cnt = new AtomicInteger(); arrayCounts.put(path, cnt); } // cnt.incrementAndGet(); Message parentMessage = null; if (!messageStack.isEmpty()) { parentMessage = messageStack.peek(); } Message arr = NavajoFactory.getInstance().createMessage(assemble, n.path(), Message.MSG_TYPE_ARRAY); if (parentMessage == null) { assemble.addMessage(arr); } else { parentMessage.addMessage(arr); } messageStack.push(arr); return Observable.<Navajo>empty(); case ARRAY_DONE: String apath = currentPath(); arrayCounts.remove(apath); this.messageStack.pop(); return Observable.<Navajo>empty(); case ARRAY_ELEMENT_STARTED: String arrayElementName = tagStack.peek(); String arrayPath = currentPath(); AtomicInteger currentCount = arrayCounts.get(arrayPath); String ind = "@" + currentCount.getAndIncrement(); tagStack.push(ind); arrayPath = currentPath(); Message newElt = NavajoFactory.getInstance() .createMessage(assemble, arrayElementName, Message.MSG_TYPE_ARRAY_ELEMENT); Message arrParent = messageStack.peek(); arrParent.addElement(newElt); messageStack.push(newElt); return Observable.<Navajo>empty(); case ARRAY_ELEMENT: tagStack.pop(); Message elementParent = messageStack.pop(); Msg msgElement = (Msg) n.body(); List<Prop> elementProps = msgElement.properties(); for (Prop e : elementProps) { elementParent.addProperty(createTmlProperty(e)); } for (Entry<String, Binary> e : pushBinaries.entrySet()) { elementParent.addProperty(createBinaryProperty(e.getKey(), e.getValue())); } pushBinaries.clear(); return Observable.<Navajo>empty(); case MESSAGE_DEFINITION_STARTED: // TODO return Observable.<Navajo>empty(); case MESSAGE_DEFINITION: // TODO // tagStack.push(n.path()); // deferredMessages.get(stripIndex(n.path())).setDefinitionMessage((Message) n.body()); return Observable.<Navajo>empty(); case NAVAJO_DONE: if (subscriber != null) { subscriber.onNext(assemble); } return Observable.<Navajo>just(assemble); case BINARY_STARTED: try { String name = n.path(); this.currentBinary = new Binary(); this.currentBinary.startPushRead(); this.pushBinaries.put(name, currentBinary); return Observable.<Navajo>empty(); } catch (IOException e1) { return Observable.error(e1); } case BINARY_CONTENT: try { if (this.currentBinary == null) { // whoops; } this.currentBinary.pushContent((String) n.body()); return Observable.<Navajo>empty(); } catch (IOException e1) { return Observable.error(e1); } case BINARY_DONE: try { this.currentBinary.finishPushContent(); return Observable.<Navajo>empty(); } catch (IOException e1) { return Observable.error(e1); } default: return Observable.<Navajo>empty(); } }
@Override public final Observable<Model> mapping() { return Observable.empty(); }