Repository: nurkiewicz/completablefuture Branch: master Commit: ca32c78fc1bc Files: 33 Total size: 471.3 KB Directory structure: gitextract_nam_xqsx/ ├── .gitignore ├── README.md ├── pom.xml └── src/ └── test/ ├── java/ │ └── com/ │ └── nurkiewicz/ │ └── reactive/ │ ├── S00_About.java │ ├── S01_Introduction.java │ ├── S02_Creating.java │ ├── S03_Map.java │ ├── S04_FlatMap.java │ ├── S05_Zip.java │ ├── S06_AllAny.java │ ├── S07_AsyncCallback.java │ ├── S08_ErrorHandling.java │ ├── S09_Promises.java │ ├── S10_AsyncHttp.java │ ├── S11_Cancelling.java │ ├── S12_RxJava.java │ ├── stackoverflow/ │ │ ├── ArtificialSleepWrapper.java │ │ ├── FallbackStubClient.java │ │ ├── HttpStackOverflowClient.java │ │ ├── InjectErrorsWrapper.java │ │ ├── LoadFromStackOverflowTask.java │ │ ├── LoggingWrapper.java │ │ ├── Question.java │ │ └── StackOverflowClient.java │ └── util/ │ ├── AbstractFuturesTest.java │ ├── Futures.java │ └── InterruptibleTask.java └── resources/ ├── clojure-questions.html ├── groovy-questions.html ├── java-questions.html ├── logback-test.xml ├── scala-questions.html └── twitter4j.properties ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ target .idea *.iml .idea ================================================ FILE: README.md ================================================ # CompletableFuture in Java 8 - asynchronous processing done right ## Tomasz Nurkiewicz Twitter: [@tnurkiewicz](https://twitter.com/tnurkiewicz) Works for: [@4financeit](https://twitter.com/4financeit) E-mail: my last name `@gmail.com` Home: [www.nurkiewicz.com](http://www.nurkiewicz.com) Source code: [www.github.com/nurkiewicz/completablefuture](http://www.github.com/nurkiewicz/completablefuture) ================================================ FILE: pom.xml ================================================ 4.0.0 com.nurkiewicz completablefuture 0.0.1-SNAPSHOT UTF-8 commons-io commons-io 2.4 com.google.guava guava 18.0 org.jsoup jsoup 1.7.3 ch.qos.logback logback-classic 1.1.3 org.slf4j jul-to-slf4j 1.7.5 org.slf4j log4j-over-slf4j 1.7.5 org.slf4j jcl-over-slf4j 1.7.5 commons-logging commons-logging 1.1.3 provided com.ning async-http-client 1.8.8 io.reactivex rxjava 1.0.11 junit junit 4.11 test org.assertj assertj-core 3.0.0 test org.mockito mockito-all 1.9.5 org.springframework spring-web 3.2.4.RELEASE maven-compiler-plugin 3.1 1.8 1.8 org.apache.maven.plugins maven-release-plugin 2.4 ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S00_About.java ================================================ package com.nurkiewicz.reactive; /** * * Tomasz Nurkiewicz * * @tnurkiewicz | @4financeit * * www.nurkiewicz.com * * www.github.com/nurkiewicz/completablefuture * */ public class S00_About { } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S01_Introduction.java ================================================ package com.nurkiewicz.reactive; import com.nurkiewicz.reactive.stackoverflow.LoadFromStackOverflowTask; import com.nurkiewicz.reactive.util.AbstractFuturesTest; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Callable; import java.util.concurrent.Future; public class S01_Introduction extends AbstractFuturesTest { private static final Logger log = LoggerFactory.getLogger(S01_Introduction.class); /** * Broken abstraction - blocking method calls */ @Test public void blockingCall() throws Exception { final String title = client.mostRecentQuestionAbout("java"); log.debug("Most recent Java question: '{}'", title); } @Test public void executorService() throws Exception { final Callable task = () -> client.mostRecentQuestionAbout("java"); final Future javaQuestionFuture = executorService.submit(task); //... final String javaQuestion = javaQuestionFuture.get(); log.debug("Found: '{}'", javaQuestion); } /** * Composing is impossible */ @Test public void waitForFirstOrAll() throws Exception { final Future java = findQuestionsAbout("java"); final Future scala = findQuestionsAbout("scala"); //??? } private Future findQuestionsAbout(String tag) { final Callable task = new LoadFromStackOverflowTask(client, tag); return executorService.submit(task); } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S02_Creating.java ================================================ package com.nurkiewicz.reactive; import com.nurkiewicz.reactive.util.AbstractFuturesTest; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CompletableFuture; public class S02_Creating extends AbstractFuturesTest { private static final Logger log = LoggerFactory.getLogger(S02_Creating.class); /** * Already completed future */ @Test public void completed() throws Exception { final CompletableFuture answer = CompletableFuture.completedFuture(42); final int fortyTwo = answer.get(); //does not block } /** * Built-in thread pool */ @Test public void supplyAsync() throws Exception { final CompletableFuture java = CompletableFuture.supplyAsync(() -> client.mostRecentQuestionAbout("java") ); log.debug("Found: '{}'", java.get()); } /** * Custom thread pool, equivalent (*) to submit() */ @Test public void supplyAsyncWithCustomExecutor() throws Exception { final CompletableFuture java = CompletableFuture.supplyAsync( () -> client.mostRecentQuestionAbout("java"), executorService ); log.debug("Found: '{}'", java.get()); } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S03_Map.java ================================================ package com.nurkiewicz.reactive; import com.nurkiewicz.reactive.util.AbstractFuturesTest; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CompletableFuture; public class S03_Map extends AbstractFuturesTest { private static final Logger log = LoggerFactory.getLogger(S03_Map.class); @Test public void oldSchool() throws Exception { final CompletableFuture java = CompletableFuture.supplyAsync(() -> client.mostRecentQuestionsAbout("java"), executorService ); final Document document = java.get(); //blocks final Element element = document. select("a.question-hyperlink").get(0); final String title = element.text(); final int length = title.length(); log.debug("Length: {}", length); } /** * Callback hell, doesn't compose */ @Test public void callbacksCallbacksEverywhere() throws Exception { final CompletableFuture java = CompletableFuture.supplyAsync(() -> client.mostRecentQuestionsAbout("java"), executorService ); java.thenAccept(document -> log.debug("Downloaded: {}", document)); } @Test public void thenApply() throws Exception { final CompletableFuture java = CompletableFuture.supplyAsync(() -> client.mostRecentQuestionsAbout("java"), executorService ); final CompletableFuture titleElement = java.thenApply((Document doc) -> doc.select("a.question-hyperlink").get(0)); final CompletableFuture titleText = titleElement.thenApply(Element::text); final CompletableFuture length = titleText.thenApply(String::length); log.debug("Length: {}", length.get()); } @Test public void thenApplyChained() throws Exception { final CompletableFuture java = CompletableFuture.supplyAsync(() -> client.mostRecentQuestionsAbout("java"), executorService ); final CompletableFuture length = java. thenApply(doc -> doc.select("a.question-hyperlink").get(0)). thenApply(Element::text). thenApply(String::length); log.debug("Length: {}", length.get()); } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S04_FlatMap.java ================================================ package com.nurkiewicz.reactive; import com.nurkiewicz.reactive.stackoverflow.Question; import com.nurkiewicz.reactive.util.AbstractFuturesTest; import org.jsoup.nodes.Document; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import java.util.concurrent.CompletableFuture; public class S04_FlatMap extends AbstractFuturesTest { private static final Logger log = LoggerFactory.getLogger(S04_FlatMap.class); @Test public void thenApplyIsWrong() throws Exception { final CompletableFuture> future = javaQuestions() .thenApply(doc -> findMostInterestingQuestion(doc)); } @Test public void thenAcceptIsPoor() throws Exception { javaQuestions().thenAccept(document -> { findMostInterestingQuestion(document).thenAccept(question -> { googleAnswer(question).thenAccept(answer -> { postAnswer(answer).thenAccept(status -> { if (status == HttpStatus.OK.value()) { log.debug("OK"); } else { log.error("Wrong status code: {}", status); } }); }); }); }); } @Test public void thenCompose() throws Exception { final CompletableFuture java = javaQuestions(); final CompletableFuture questionFuture = java.thenCompose(doc -> findMostInterestingQuestion(doc)); final CompletableFuture answerFuture = questionFuture.thenCompose(question -> googleAnswer(question)); final CompletableFuture httpStatusFuture = answerFuture.thenCompose(answer -> postAnswer(answer)); httpStatusFuture.thenAccept(status -> { if (status == HttpStatus.OK.value()) { log.debug("OK"); } else { log.error("Wrong status code: {}", status); } }); } @Test public void chained() throws Exception { javaQuestions(). thenCompose(doc -> findMostInterestingQuestion(doc)). thenCompose(question -> googleAnswer(question)). thenCompose(answer -> postAnswer(answer)). thenAccept(status -> { if (status == HttpStatus.OK.value()) { log.debug("OK"); } else { log.error("Wrong status code: {}", status); } }); } private CompletableFuture javaQuestions() { return CompletableFuture.supplyAsync(() -> client.mostRecentQuestionsAbout("java"), executorService ); } private CompletableFuture findMostInterestingQuestion(Document document) { return CompletableFuture.completedFuture(new Question()); } private CompletableFuture googleAnswer(Question q) { return CompletableFuture.completedFuture("42"); } private CompletableFuture postAnswer(String answer) { return CompletableFuture.completedFuture(200); } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S05_Zip.java ================================================ package com.nurkiewicz.reactive; import com.nurkiewicz.reactive.util.AbstractFuturesTest; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CompletableFuture; public class S05_Zip extends AbstractFuturesTest { private static final Logger log = LoggerFactory.getLogger(S05_Zip.class); @Test public void thenCombine() throws Exception { final CompletableFuture java = questions("java"); final CompletableFuture scala = questions("scala"); final CompletableFuture both = java. thenCombine(scala, (String javaTitle, String scalaTitle) -> javaTitle.length() + scalaTitle.length() ); both.thenAccept(length -> log.debug("Total length: {}", length)); } @Test public void either() throws Exception { final CompletableFuture java = questions("java"); final CompletableFuture scala = questions("scala"); final CompletableFuture both = java. applyToEither(scala, title -> title.toUpperCase()); both.thenAccept(title -> log.debug("First: {}", title)); } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S06_AllAny.java ================================================ package com.nurkiewicz.reactive; import com.nurkiewicz.reactive.util.AbstractFuturesTest; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class S06_AllAny extends AbstractFuturesTest { private static final Logger log = LoggerFactory.getLogger(S06_AllAny.class); @Test public void allOf() throws Exception { final CompletableFuture java = questions("java"); final CompletableFuture scala = questions("scala"); final CompletableFuture clojure = questions("clojure"); final CompletableFuture groovy = questions("groovy"); final CompletableFuture allCompleted = CompletableFuture.allOf( java, scala, clojure, groovy ); allCompleted.thenRun(() -> { try { log.debug("Loaded: {}", java.get()); log.debug("Loaded: {}", scala.get()); log.debug("Loaded: {}", clojure.get()); log.debug("Loaded: {}", groovy.get()); } catch (InterruptedException | ExecutionException e) { log.error("", e); } }); } @Test public void anyOf() throws Exception { final CompletableFuture java = questions("java"); final CompletableFuture scala = questions("scala"); final CompletableFuture clojure = questions("clojure"); final CompletableFuture groovy = questions("groovy"); final CompletableFuture firstCompleted = CompletableFuture.anyOf( java, scala, clojure, groovy ); firstCompleted.thenAccept((Object result) -> { log.debug("First: {}", result); }); } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S07_AsyncCallback.java ================================================ package com.nurkiewicz.reactive; import com.nurkiewicz.reactive.util.AbstractFuturesTest; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class S07_AsyncCallback extends AbstractFuturesTest { private static final Logger log = LoggerFactory.getLogger(S07_AsyncCallback.class); protected final ExecutorService poolAlpha = Executors.newFixedThreadPool(10, threadFactory("Alpha")); protected final ExecutorService poolBeta = Executors.newFixedThreadPool(10, threadFactory("Beta")); protected final ExecutorService poolGamma = Executors.newFixedThreadPool(10, threadFactory("Gamma")); @Test public void whichThreadInvokesCallbacks() throws Exception { final CompletableFuture java = CompletableFuture .supplyAsync( () -> client.mostRecentQuestionAbout("java"), poolAlpha); final CompletableFuture scala = CompletableFuture .supplyAsync( () -> client.mostRecentQuestionAbout("scala"), poolBeta); final CompletableFuture first = java .applyToEither(scala, question -> { log.debug("First: {}", question); return question.toUpperCase(); }); first.thenAccept(q -> log.debug("Sync: {}", q)); first.thenAcceptAsync(q -> log.debug("Async: {}", q)); first.thenAcceptAsync(q -> log.debug("Async (pool): {}", q), poolGamma); first.get(); //block } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S08_ErrorHandling.java ================================================ package com.nurkiewicz.reactive; import com.nurkiewicz.reactive.util.AbstractFuturesTest; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CompletableFuture; public class S08_ErrorHandling extends AbstractFuturesTest { private static final Logger log = LoggerFactory.getLogger(S08_ErrorHandling.class); @Test public void exceptionsShortCircuitFuture() throws Exception { final CompletableFuture questions = questions("php"); questions.thenApply(r -> { log.debug("Success!"); return r; }); questions.get(); } @Test public void handleExceptions() throws Exception { //given final CompletableFuture questions = questions("php"); //when final CompletableFuture recovered = questions .handle((result, throwable) -> { if (throwable != null) { return "No PHP today due to: " + throwable; } else { return result.toUpperCase(); } }); //then log.debug("Handled: {}", recovered.get()); } @Test public void shouldHandleExceptionally() throws Exception { //given final CompletableFuture questions = questions("php"); //when final CompletableFuture recovered = questions .exceptionally(throwable -> "Sorry, try again later"); //then log.debug("Done: {}", recovered.get()); } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S09_Promises.java ================================================ package com.nurkiewicz.reactive; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.nurkiewicz.reactive.util.AbstractFuturesTest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class S09_Promises extends AbstractFuturesTest { private static final Logger log = LoggerFactory.getLogger(S09_Promises.class); private static final ScheduledExecutorService pool = Executors.newScheduledThreadPool(10, new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("FutureOps-%d") .build() ); public static CompletableFuture never() { return new CompletableFuture<>(); } public static CompletableFuture timeoutAfter( Duration duration) { final CompletableFuture promise = new CompletableFuture<>(); pool.schedule( () -> promise.completeExceptionally(new TimeoutException()), duration.toMillis(), TimeUnit.MILLISECONDS); return promise; } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S10_AsyncHttp.java ================================================ package com.nurkiewicz.reactive; import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.Response; import com.nurkiewicz.reactive.util.AbstractFuturesTest; import org.junit.AfterClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public class S10_AsyncHttp extends AbstractFuturesTest { private static final Logger log = LoggerFactory.getLogger(S10_AsyncHttp.class); private static final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); @AfterClass public static void closeClient() { asyncHttpClient.close(); } @Test public void asyncHttpWithCallbacks() throws Exception { loadTag( "java", response -> log.debug("Got: {}", response), throwable -> log.error("Mayday!", throwable) ); TimeUnit.SECONDS.sleep(5); } public void loadTag( String tag, Consumer onSuccess, Consumer onError) throws IOException { asyncHttpClient .prepareGet("http://stackoverflow.com/questions/tagged/" + tag) .execute( new AsyncCompletionHandler() { @Override public Void onCompleted(Response response) throws Exception { onSuccess.accept(response.getResponseBody()); return null; } @Override public void onThrowable(Throwable t) { onError.accept(t); } } ); } public CompletableFuture loadTag(String tag) throws IOException { final CompletableFuture promise = new CompletableFuture<>(); asyncHttpClient.prepareGet("http://stackoverflow.com/questions/tagged/" + tag).execute( new AsyncCompletionHandler() { @Override public Void onCompleted(Response response) throws Exception { promise.complete(response.getResponseBody()); return null; } @Override public void onThrowable(Throwable t) { promise.completeExceptionally(t); } } ); return promise; } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S11_Cancelling.java ================================================ package com.nurkiewicz.reactive; import com.nurkiewicz.reactive.util.AbstractFuturesTest; import com.nurkiewicz.reactive.util.InterruptibleTask; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import java.util.concurrent.*; public class S11_Cancelling extends AbstractFuturesTest { private static ExecutorService myThreadPool; @BeforeClass public static void init() { myThreadPool = Executors.newFixedThreadPool(10); } @AfterClass public static void close() { myThreadPool.shutdownNow(); } @Test public void shouldCancelFuture() throws InterruptedException, TimeoutException { //given InterruptibleTask task = new InterruptibleTask(); Future future = myThreadPool.submit(task); task.blockUntilStarted(); //when future.cancel(true); //then task.blockUntilInterrupted(); } @Ignore("Fails with CompletableFuture") @Test public void shouldCancelCompletableFuture() throws InterruptedException, TimeoutException { //given InterruptibleTask task = new InterruptibleTask(); CompletableFuture future = CompletableFuture.supplyAsync(task, myThreadPool); task.blockUntilStarted(); //when future.cancel(true); //then task.blockUntilInterrupted(); } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/S12_RxJava.java ================================================ package com.nurkiewicz.reactive; import com.nurkiewicz.reactive.util.AbstractFuturesTest; import com.nurkiewicz.reactive.util.Futures; import org.junit.Test; import rx.Observable; import java.util.List; import java.util.concurrent.CompletableFuture; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; public class S12_RxJava extends AbstractFuturesTest { public static final String MSG = "Don't panic"; @Test public void shouldConvertCompletedFutureToCompletedObservable() throws Exception { //given CompletableFuture future = CompletableFuture.completedFuture("Abc"); //when Observable observable = Futures.toObservable(future); //then assertThat(observable.toList().toBlocking().single()).containsExactly("Abc"); } @Test public void shouldConvertFailedFutureIntoObservableWithFailure() throws Exception { //given CompletableFuture future = failedFuture(new IllegalStateException(MSG)); //when Observable observable = Futures.toObservable(future); //then final List result = observable .onErrorReturn(Throwable::getMessage) .toList() .toBlocking() .single(); assertThat(result).containsExactly(MSG); } @Test public void shouldConvertObservableWithManyItemsToFutureOfList() throws Exception { //given Observable observable = Observable.just(1, 2, 3); //when CompletableFuture> future = Futures.fromObservable(observable); //then assertThat(future.get(1, SECONDS)).containsExactly(1, 2, 3); } @Test public void shouldConvertObservableWithSingleItemToFuture() throws Exception { //given Observable observable = Observable.just(1); //when CompletableFuture future = Futures.fromSingleObservable(observable); //then assertThat(future.get(1, SECONDS)).isEqualTo(1); } CompletableFuture failedFuture(Exception error) { CompletableFuture future = new CompletableFuture<>(); future.completeExceptionally(error); return future; } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/stackoverflow/ArtificialSleepWrapper.java ================================================ package com.nurkiewicz.reactive.stackoverflow; import org.jsoup.nodes.Document; import java.util.Random; import java.util.concurrent.TimeUnit; public class ArtificialSleepWrapper implements StackOverflowClient { private static final Random RANDOM = new Random(); private final StackOverflowClient target; public ArtificialSleepWrapper(StackOverflowClient target) { this.target = target; } @Override public String mostRecentQuestionAbout(String tag) { final long start = System.currentTimeMillis(); final String result = target.mostRecentQuestionAbout(tag); artificialSleep(1000 - (System.currentTimeMillis() - start)); return result; } @Override public Document mostRecentQuestionsAbout(String tag) { artificialSleep(1000); final long start = System.currentTimeMillis(); final Document result = target.mostRecentQuestionsAbout(tag); artificialSleep(1000 - (System.currentTimeMillis() - start)); return result; } protected static void artificialSleep(long expected) { try { TimeUnit.MILLISECONDS.sleep((long) (expected + RANDOM.nextGaussian() * expected / 2)); } catch (InterruptedException e) { throw new RuntimeException(e); } } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/stackoverflow/FallbackStubClient.java ================================================ package com.nurkiewicz.reactive.stackoverflow; import com.google.common.base.Throwables; import org.apache.commons.io.IOUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URL; public class FallbackStubClient implements StackOverflowClient { private static final Logger log = LoggerFactory.getLogger(FallbackStubClient.class); private final StackOverflowClient target; public FallbackStubClient(StackOverflowClient target) { this.target = target; } @Override public String mostRecentQuestionAbout(String tag) { try { return target.mostRecentQuestionAbout(tag); } catch (Exception e) { log.warn("Problem retrieving tag {}", tag, e); switch(tag) { case "java": return "How to generate xml report with maven depencency?"; case "scala": return "Update a timestamp SettingKey in an sbt 0.12 task"; case "groovy": return "Reusing Grails variables inside Config.groovy"; case "clojure": return "Merge two comma delimited strings in Clojure"; default: throw e; } } } @Override public Document mostRecentQuestionsAbout(String tag) { try { return target.mostRecentQuestionsAbout(tag); } catch (Exception e) { log.warn("Problem retrieving recent question {}", tag, e); return loadStubHtmlFromDisk(tag); } } private Document loadStubHtmlFromDisk(String tag) { try { final URL resource = getClass().getResource("/" + tag + "-questions.html"); final String html = IOUtils.toString(resource); return Jsoup.parse(html); } catch (IOException e) { throw Throwables.propagate(e); } } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/stackoverflow/HttpStackOverflowClient.java ================================================ package com.nurkiewicz.reactive.stackoverflow; import com.google.common.base.Throwables; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; public class HttpStackOverflowClient implements StackOverflowClient { @Override public String mostRecentQuestionAbout(String tag) { return fetchTitleOnline(tag); } @Override public Document mostRecentQuestionsAbout(String tag) { try { return Jsoup. connect("http://stackoverflow.com/questions/tagged/" + tag). get(); } catch (IOException e) { throw Throwables.propagate(e); } } private String fetchTitleOnline(String tag) { return mostRecentQuestionsAbout(tag).select("a.question-hyperlink").get(0).text(); } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/stackoverflow/InjectErrorsWrapper.java ================================================ package com.nurkiewicz.reactive.stackoverflow; import org.jsoup.nodes.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class InjectErrorsWrapper implements StackOverflowClient { private static final Logger log = LoggerFactory.getLogger(InjectErrorsWrapper.class); private final StackOverflowClient target; private final Set blackList; public InjectErrorsWrapper(StackOverflowClient target, String... blackList) { this.target = target; this.blackList = new HashSet<>(Arrays.asList(blackList)); } @Override public String mostRecentQuestionAbout(String tag) { throwIfBlackListed(tag); return target.mostRecentQuestionAbout(tag); } @Override public Document mostRecentQuestionsAbout(String tag) { throwIfBlackListed(tag); return target.mostRecentQuestionsAbout(tag); } private void throwIfBlackListed(String tag) { if (blackList.contains(tag)) { ArtificialSleepWrapper.artificialSleep(400); log.warn("About to throw artifical exception due to: {}", tag); throw new IllegalArgumentException("Unsupported " + tag); } } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/stackoverflow/LoadFromStackOverflowTask.java ================================================ package com.nurkiewicz.reactive.stackoverflow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Callable; public class LoadFromStackOverflowTask implements Callable { private static final Logger log = LoggerFactory.getLogger(LoadFromStackOverflowTask.class); private final StackOverflowClient client; private final String tag; public LoadFromStackOverflowTask(StackOverflowClient client, String tag) { this.client = client; this.tag = tag; } @Override public String call() throws Exception { return client.mostRecentQuestionAbout(tag); } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/stackoverflow/LoggingWrapper.java ================================================ package com.nurkiewicz.reactive.stackoverflow; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import org.jsoup.nodes.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoggingWrapper implements StackOverflowClient { private static final Logger log = LoggerFactory.getLogger(LoggingWrapper.class); private final StackOverflowClient target; public LoggingWrapper(StackOverflowClient target) { this.target = target; } @Override public String mostRecentQuestionAbout(String tag) { log.debug("Entering mostRecentQuestionAbout({})", tag); final String title = target.mostRecentQuestionAbout(tag); log.debug("Leaving mostRecentQuestionAbout({}): {}", tag, title); return title; } @Override public Document mostRecentQuestionsAbout(String tag) { log.debug("Entering mostRecentQuestionsAbout({})", tag); final Document document = target.mostRecentQuestionsAbout(tag); if (log.isTraceEnabled()) { log.trace("Leaving mostRecentQuestionsAbout({}): {}", tag, htmlExcerpt(document)); } return document; } private String htmlExcerpt(Document document) { final String outerHtml = document.outerHtml(); final Iterable lines = Splitter.onPattern("\r?\n").split(outerHtml); final Iterable firstLines = Iterables.limit(lines, 4); final String excerpt = Joiner.on(' ').join(firstLines); final int remainingBytes = Math.max(outerHtml.length() - excerpt.length(), 0); return excerpt + " [...and " + remainingBytes + " chars]"; } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/stackoverflow/Question.java ================================================ package com.nurkiewicz.reactive.stackoverflow; public class Question { } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/stackoverflow/StackOverflowClient.java ================================================ package com.nurkiewicz.reactive.stackoverflow; import org.jsoup.nodes.Document; public interface StackOverflowClient { String mostRecentQuestionAbout(String tag); Document mostRecentQuestionsAbout(String tag); } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/util/AbstractFuturesTest.java ================================================ package com.nurkiewicz.reactive.util; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.nurkiewicz.reactive.stackoverflow.*; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.*; public class AbstractFuturesTest { private static final Logger log = LoggerFactory.getLogger(AbstractFuturesTest.class); protected final ExecutorService executorService = Executors.newFixedThreadPool(10, threadFactory("Custom")); @Rule public TestName testName = new TestName(); protected ThreadFactory threadFactory(String nameFormat) { return new ThreadFactoryBuilder().setNameFormat(nameFormat + "-%d").build(); } protected final StackOverflowClient client = new FallbackStubClient( new InjectErrorsWrapper( new LoggingWrapper( new ArtificialSleepWrapper( new HttpStackOverflowClient() ) ), "php" ) ); @Before public void logTestStart() { log.debug("Starting: {}", testName.getMethodName()); } @After public void stopPool() throws InterruptedException { executorService.shutdown(); executorService.awaitTermination(10, TimeUnit.SECONDS); } protected CompletableFuture questions(String tag) { return CompletableFuture.supplyAsync(() -> client.mostRecentQuestionAbout(tag), executorService); } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/util/Futures.java ================================================ package com.nurkiewicz.reactive.util; import rx.Observable; import java.util.List; import java.util.concurrent.CompletableFuture; public class Futures { public static CompletableFuture fromSingleObservable(Observable observable) { final CompletableFuture future = new CompletableFuture<>(); observable .doOnError(future::completeExceptionally) .single() .forEach(future::complete); return future; } public static CompletableFuture> fromObservable(Observable observable) { final CompletableFuture> future = new CompletableFuture<>(); observable .doOnError(future::completeExceptionally) .toList() .forEach(future::complete); return future; } public static Observable toObservable(CompletableFuture future) { return Observable.create(subscriber -> future.whenComplete((result, error) -> { if (error != null) { subscriber.onError(error); } else { subscriber.onNext(result); subscriber.onCompleted(); } })); } } ================================================ FILE: src/test/java/com/nurkiewicz/reactive/util/InterruptibleTask.java ================================================ package com.nurkiewicz.reactive.util; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Supplier; public class InterruptibleTask implements Runnable, Supplier { private final CountDownLatch started = new CountDownLatch(1); private final CountDownLatch interrupted = new CountDownLatch(1); @Override public Void get() { run(); return null; } @Override public void run() { started.countDown(); try { Thread.sleep(10_000); } catch (InterruptedException ignored) { interrupted.countDown(); } } public void blockUntilStarted() throws InterruptedException { started.await(); } public void blockUntilInterrupted() throws InterruptedException, TimeoutException { if (!interrupted.await(1, TimeUnit.SECONDS)) { throw new TimeoutException("Not interrupted within 1 second"); } } } ================================================ FILE: src/test/resources/clojure-questions.html ================================================ Newest 'clojure' Questions - Stack Overflow

Clojure is a modern Lisp dialect for the Java Virtual Machine (with versions for the CLR and JavaScript).

learn more… | top users | synonyms (1)

-4
votes
0answers
30 views

Secure web sockets with Clojure [on hold]

Can anybody tell me how to implement secure websockets with Clojure (HttpKit)? Thanks
1
vote
1answer
40 views

Clojure - Using agents slows down execution too much

I am writing a benchmark for a program in Clojure. I have n threads accessing a cache at the same time. Each thread will access the cache x times. Each request should be logged inside a file. To this ...
-3
votes
2answers
33 views

Merge two comma delimited strings in Clojure

I have two comma-delimited strings as below: stringA "a,b,c,d" stringB "w,x,y,z" How can I merge the strings as below in clojure: stringResult "aw,bx,cy,dz" Note: The comma-delimited values are ...
0
votes
0answers
13 views

How to set a timeout on a Hystrix command in Clojure?

I'm learning about Hystrix and Clojure and don't understand how to (properly) set a timeout on a Hystrix command in Clojure. I searched StackOverflow and the web more generally. I looked at Hystrix's ...
0
votes
1answer
16 views

Use of other protocol method in extend-type

I'm building a graph editor with Piccolo2D and want to implement Loom's Graph protocol. However I run into problem Unable to resolve symbol: out-edges in this context What really confusing is that ...
0
votes
2answers
29 views

How to write a macro used in cond in clojure?

I have the following macro to ensure the data containing specific keys. (defmacro with-correct-format [data & body] `(cond (nil? ~data) (throw (IllegalArgumentException. ...
1
vote
1answer
18 views

ClassNotFoundException when importing record from other namespace

I have following files: src/my_proj/myns.clj: (ns my-proj.myns) (defrecord MyRecord [a b c]) test/my_proj/myns_test.clj: (ns my-proj.myns-test (:require [clojure.test :refer :all] ...
0
votes
0answers
27 views

Getting modulus from seq->stream

The code below draws me the sine wave throughout the screen, and beyond. However, I want that x never exceeds (width). At that point, the window should be cleared, and the wave should be drawn again, ...
0
votes
1answer
61 views

More functional way to do this?

This post of mine discusses Thomson's paradox, and simulates it in Clojure. The state function returns the state of the lamp at time = t. (defn thomsons-lamp [] (iterate (fn [[onoff dur]] ...
0
votes
2answers
22 views

Casting an ArraySeq as an IFn

Elementary question here.. I am a little confused. (((fn [_ & y] y) 'blah +) 3 4) will result in the error: "java.lang.ClassCastException: clojure.lang.ArraySeq cannot be cast to ...
0
votes
2answers
50 views

how to sort map based on keys

I have the following map: MyVals {12 -3, 24 -9, 36 -777, 48 -3037, 180 0, 360 0, 240 0, 120 0, 0 0, 144 0, 3 0, 6 -1, 9 -1, 108 0, 60 0, 72 0, 84 0, 96 0} I am removing zero values then I need to ...
1
vote
1answer
21 views

Clojure local maven repo with JNI dependency

I am trying to create a local Maven repository for my Clojure/leiningen project, as for instance described here: Use Leiningen With Local M2 Repository I have also found out that more recent ...
2
votes
1answer
31 views

How to expand the `Classname/staticField` macro syntax

From the Clojure docs, this is how to access a static field of a Java class: Classname/staticField Math/PI -> 3.141592653589793 And this is the expansion: The expansions are as follows: ...
0
votes
1answer
38 views

Clojure printing lazy sequence

I'm trying to print out my binary tree but Clojure is giving me a hard time printing out the sequences properly. So, I have a list of nodes '(1 2 3) for example. In each iteration I want to print ...
2
votes
1answer
27 views

How to package up a leiningen project for recompilation with all the libraries included? [for users without an internet connection]

I'm giving a Clojure workshop and I want people to be able to modify and recompile the Clojure project. The challenge is that they won't have internet connections - so I need to give them the project ...

15 30 50 per page
================================================ FILE: src/test/resources/groovy-questions.html ================================================ Newest 'groovy' Questions - Stack Overflow

Groovy is an object-oriented, agile and dynamic language for the Java Virtual Machine. It builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk. It makes modern programming features available to Java developers with almost zero ...

learn more… | top users | synonyms

0
votes
0answers
6 views

Trim domain field by default

What is the best way to trim field value in domain? My suggestion is to use beforeSave(), but would work something like this? class Book { String name = name?.trim() }
0
votes
0answers
14 views

Get testname in Integration test

In my grails integration test, how do I get the the currently executing test name? I want to do this for logging purposes.
1
vote
1answer
18 views

Reusing Grails variables inside Config.groovy

In my Config.groovy I have: // Lots of other stuff up here... environments { development { myapp.port = 7500 } production { myapp.port = 7600 } } fizz { buzz { ...
0
votes
1answer
12 views

groovy script + run CLI command + WIN XP

I have the following command in my groovy script println "cmd /c remove_files.bat".execute().text Groovy runs the BAT file - remove_files.bat , but the BAT file stop on the question: do you ...
0
votes
1answer
15 views

Define a method in DSLD (Parameter types)

I already have defined a DSL in Groovy. Now I'm working on the Eclipse integration so that I have auto completion and other fancy stuff. This doesn't work: method name:"myMethod", params : [param1: ...
0
votes
2answers
22 views

Parsing wikipedia xml dump in Groovy

recently I wanted to work on wikipedia data. In that case I downloaded its en-lang XML dump. It was over 44GB. I thought I would parse it with XmlSlurper that, according to documentation, is good ...
0
votes
1answer
25 views

Pagination on a ArrayList

There are a lot of possibilities to make pagination with domain classes, but what about existing ArrayList of objects? Is it possible?
0
votes
0answers
8 views

Groovy execute process hangs

In a groovy script I execute an application on linux and windows with: def proc = command.execute() proc.consumeProcessOutput( System.out, System.err) println "here" proc.waitFor() println ...
-2
votes
0answers
22 views

Issue in saving the list in mongdb

Domain Class: class Questionairre { static hasMany = [Questions: String] } Controller Class: Map CONFIG_BOOK_COLUMN_MAP = [ sheet:'Sheet1', startRow: 1, columnMap: [ ...
0
votes
2answers
31 views

How to test that a created value is unique?

In my Java class I have a method that creates an object and implements certain logic to assign random values to some of its variables, using one static instance of Random (static Random rn = new ...
0
votes
0answers
23 views

How can a Grails plugin modify the app's default mappings/constraints config?

I'm creating a Grails plugin which will modify the value of the following config property: grails.gorm.default.constraints The problem is that by the time my plugin descriptor starts running ...
0
votes
1answer
12 views

SOAP UI - Split HTTP Response Header and transfer to property

I am obtaining the following response to a HTTP Request in SOAP UI TTP/1.1 201 Created X-Content-Type-Options: nosniff X-XSS-Protection: 1; mode=block Cache-Control: no-cache, no-store, max-age=0, ...
-1
votes
0answers
29 views

how to run expect from groovy script

First I am very new in groovy I am trying to learn how groovy can work with expect so I take this groovy script “nslookup in interactive mode to test a DNS server” from the link below ...
0
votes
1answer
24 views

Pass a list as an argument to Groovy BuilderSupport createNode

I have a Groovy class that creates another classes dynamically: package javainterop3 import groovy.lang.Closure; import groovy.lang.GroovyClassLoader; class DynamicClass { GroovyClassLoader ...
0
votes
0answers
8 views

Groovy: How to call a restful web service with post method , if I have endpoint, path and xml as argument

I have tried hard to access the service but couldn't get. The uri is a secure one. a end point/URI https://www.localhost:8080/test Method Path: login/new session and XML argument: 123xxx

15 30 50 per page
================================================ FILE: src/test/resources/java-questions.html ================================================ Newest 'java' Questions - Stack Overflow

Java (not to be confused with JavaScript) is a class-based, object-oriented, strongly typed, reflective language and runtime environment (JRE). Java programs are compiled to bytecode and run in a virtual machine (JVM) enabling a "write once, run anywhere" (WORA) methodology.

learn more… | top users | synonyms (6) | java jobs

-1
votes
0answers
9 views

Why don't common Map implementations cache the result of Map.containsKey() for Map.get()

A common pattern with a map is to check if a key exists and then act on the value only if it does, consider: if(!map.containsKey(key)) { map.put(key, new DefaultValue()); } return map.get(key); ...
0
votes
0answers
7 views

java.lang.ClassNotFoundException: org.hibernate.HibernateException for hibernate 4

I'm trying to set up a web application with tomcat 7.0, java6 and hibernate 4. Basically, you can say I have the same problem as in this thread: java.lang.ClassNotFoundException: ...
0
votes
0answers
11 views

How to generate xml report with maven depencency?

I would like to use the command mvn dependency:analyze-report to generate xml report. Actually the report generated is html format. The plug-in declaration : <plugin> ...
0
votes
0answers
3 views

How to test Handler callbacks from a Service in an Android JUnit Test?

I want to test the following (standard?) scenario An activity uses a Service object to do some stuff. The Service is bind to the activity with bindService(..). The service itself allows access via ...
-10
votes
2answers
39 views

What does the regex “[+0-9-'.']+$” do? [on hold]

Can someone explain to me what telreg will contain after the assignement ? String telReg = "[+0-9-'.']+$";
0
votes
1answer
25 views

Expanding a variable within Double Quotes in Java

I have a Java Application program that runs various Unix commands while the main application is executing. public static void shellExec(){ try{ System.out.println("Entering into the test ...
1
vote
1answer
17 views

How to prevent Java Generics forcing duplicate code?

I'm trying to write an AnimalGroup factory class that returns an instance which contains various different types of Animal. Unfortunately i'm being forced to duplicate code due to what seems like Java ...
-2
votes
0answers
23 views

Java cannot compile when using “extend”

i m trying to compile a .java file and it always give an error in "extend class".I can compile other .java without extend in the code.Also i can compile the file with the extend on another computer. I ...
0
votes
1answer
14 views

Does Thread.sleep reduce memory issues with reading and saving a big file

I am running a utility class as a java application. The class read a csv file with 5 million records and tries to save about 125k records in database. Half way through i got heap space error. Full ...
0
votes
0answers
7 views

Paypal Merchant Java SDK: How to get Recurring Payment amount to show up on Paypal?

I'm up and running with the Paypal Merchant SDK for Java. I followed the instructions here: ...
0
votes
0answers
9 views

Java, AVL tree, cannot rotate_right, cannot find the reason

I am implementing an AVLTree class using Java, and I have met some mysterious problems: The AVLTree class definition looks like this: (note that there is an embedded class AVLNode) public class ...
0
votes
2answers
31 views

RIA - Java banned everywhere

I am considering Java as a platform for development some rich internet application. As a developer I am pretty satisfied by abilities Java provides. But there is a problem - my application should be ...
0
votes
0answers
9 views

How to visualize a picture on the UI using Primeface

I want to make a toggleable form, where each agency from my list will be in a different toggleable panel which will contain photo + additional info. Toggleable panels work perfect. I successfully take ...
-3
votes
0answers
19 views

Explain in plain english algorithm to find a path on graph using hadoop [on hold]

I have a problem that involves finding path of a particular length on directed graph using hadoop and I found myself not been able to invent a solution. I found couple of existing solutions, in ...
0
votes
1answer
22 views

Concatenate String from BufferedReader and Pass to UI Thread

First off, this is my first Java project! Take a look at the method below. My goal is to receive multi-line text (actually xml in a wrapper) from a socket connection. I am trying to read each line and ...

15 30 50 per page
Newest 'java' Questions - Stack Overflow

Java (not to be confused with JavaScript) is a class-based, object-oriented, strongly typed, reflective language and runtime environment (JRE). Java programs are compiled to bytecode and run in a virtual machine (JVM) enabling a "write once, run anywhere" (WORA) methodology.

learn more… | top users | synonyms (6) | java jobs

-1
votes
0answers
9 views

Why don't common Map implementations cache the result of Map.containsKey() for Map.get()

A common pattern with a map is to check if a key exists and then act on the value only if it does, consider: if(!map.containsKey(key)) { map.put(key, new DefaultValue()); } return map.get(key); ...
0
votes
0answers
7 views

java.lang.ClassNotFoundException: org.hibernate.HibernateException for hibernate 4

I'm trying to set up a web application with tomcat 7.0, java6 and hibernate 4. Basically, you can say I have the same problem as in this thread: java.lang.ClassNotFoundException: ...
0
votes
0answers
11 views

How to generate xml report with maven depencency?

I would like to use the command mvn dependency:analyze-report to generate xml report. Actually the report generated is html format. The plug-in declaration : <plugin> ...
0
votes
0answers
3 views

How to test Handler callbacks from a Service in an Android JUnit Test?

I want to test the following (standard?) scenario An activity uses a Service object to do some stuff. The Service is bind to the activity with bindService(..). The service itself allows access via ...
-10
votes
2answers
39 views

What does the regex “[+0-9-'.']+$” do? [on hold]

Can someone explain to me what telreg will contain after the assignement ? String telReg = "[+0-9-'.']+$";
0
votes
1answer
25 views

Expanding a variable within Double Quotes in Java

I have a Java Application program that runs various Unix commands while the main application is executing. public static void shellExec(){ try{ System.out.println("Entering into the test ...
1
vote
1answer
17 views

How to prevent Java Generics forcing duplicate code?

I'm trying to write an AnimalGroup factory class that returns an instance which contains various different types of Animal. Unfortunately i'm being forced to duplicate code due to what seems like Java ...
-2
votes
0answers
23 views

Java cannot compile when using “extend”

i m trying to compile a .java file and it always give an error in "extend class".I can compile other .java without extend in the code.Also i can compile the file with the extend on another computer. I ...
0
votes
1answer
14 views

Does Thread.sleep reduce memory issues with reading and saving a big file

I am running a utility class as a java application. The class read a csv file with 5 million records and tries to save about 125k records in database. Half way through i got heap space error. Full ...
0
votes
0answers
7 views

Paypal Merchant Java SDK: How to get Recurring Payment amount to show up on Paypal?

I'm up and running with the Paypal Merchant SDK for Java. I followed the instructions here: ...
0
votes
0answers
9 views

Java, AVL tree, cannot rotate_right, cannot find the reason

I am implementing an AVLTree class using Java, and I have met some mysterious problems: The AVLTree class definition looks like this: (note that there is an embedded class AVLNode) public class ...
0
votes
2answers
31 views

RIA - Java banned everywhere

I am considering Java as a platform for development some rich internet application. As a developer I am pretty satisfied by abilities Java provides. But there is a problem - my application should be ...
0
votes
0answers
9 views

How to visualize a picture on the UI using Primeface

I want to make a toggleable form, where each agency from my list will be in a different toggleable panel which will contain photo + additional info. Toggleable panels work perfect. I successfully take ...
-3
votes
0answers
19 views

Explain in plain english algorithm to find a path on graph using hadoop [on hold]

I have a problem that involves finding path of a particular length on directed graph using hadoop and I found myself not been able to invent a solution. I found couple of existing solutions, in ...
0
votes
1answer
22 views

Concatenate String from BufferedReader and Pass to UI Thread

First off, this is my first Java project! Take a look at the method below. My goal is to receive multi-line text (actually xml in a wrapper) from a socket connection. I am trying to read each line and ...

15 30 50 per page
================================================ FILE: src/test/resources/logback-test.xml ================================================ %r | %thread | %m%n%rEx ================================================ FILE: src/test/resources/scala-questions.html ================================================ Newest 'scala' Questions - Stack Overflow

Scala is a general purpose programming language principally targeting the Java Virtual Machine. Designed to express common programming patterns in a concise, elegant, and type-safe way, it fuses both imperative and functional programming styles. Its key features are: advanced static type system ...

learn more… | top users | synonyms

0
votes
0answers
5 views

Update a timestamp SettingKey in an sbt 0.12 task

I need a way to update a SettingKey[String] in my sbt build each time the compile task executes. A SettingKey is necessary so it can be injected into application via sbt-buildinfo. Creating a ...
0
votes
0answers
11 views

request-reply with akka-camel and ActiveMQ

I'm trying to implement a very simple request-reply pattern using akka-camel. Here's my (testbench) code which is trying to use activeMQ directly to send a message and expect a response: val ...
0
votes
0answers
12 views

If I load my database connection pool does it affect the main netty thread?

Say I have a action method that connects to the database like this: @Singleton class Users @Inject()(userService: UserService) extends Controller { def dbtest = Action { val user = ...
0
votes
0answers
20 views

scalding NoClassDefFoundError

after installing java, scala scalding on OSX i have the following error when i try to run the WordCountJob file $ scripts/scald.rb --local WordCountJob.scala --input someInputfile.txt --output ...
1
vote
0answers
17 views

Kafka Consumer not consuming full message

I have written a kafka consumer process in scala as - executor = endpoint.getCamelContext().getExecutorServiceManager().newFixedThreadPool( this, endpoint.getEndpointUri, concurrentConsumers) ec = ...
3
votes
1answer
41 views

How to understand “The variance position of a method parameter is the opposite of the variance position of the enclosing parameter clause.”

I see this sentence is scala specification (pdf): The variance position of a method parameter is the opposite of the variance position of the enclosing parameter clause. Which is on page 44. ...
2
votes
2answers
38 views

Generating all possible combinations from a List[List[Int]] in Scala

Given the following list: List(List(1,2,3), List(4,5)) I would like to generate all the possible combinations. Using yield, it can be done as follows: scala> for (x <- l.head; y <- ...
5
votes
0answers
105 views

Java 8 parallel sorting vs Scala parallel sorting

So i was just learning new Java 8, specially lamdas and date and time api. I was comparing it with scala. My basic idea was to find the execution time difference between imperative, Stream and ...
0
votes
0answers
10 views

JSON4S + Jackson does not serialize properties of the superclass

I'm using json4s with the jackson serializer in a scala project. My transfer objects are defined in a regular Java library. I'm also using Lombok to generate constructors/getter/setter/etc. They look ...
0
votes
2answers
65 views

What is == mechanism in Scala?

Just would like to get some detail on how scala == works when comparing two strings. How does object comaparision works in scala?
1
vote
2answers
33 views

Is it possible to do variables with local scoping in c#?

In Scala I can do something like this: val result = { val a = 4 val b = 16 a + b } Which is basically just a (in this case immutable) variable that has its own local scoping like a method. ...
1
vote
1answer
48 views

Can't understand why `trait Hello[+A] { def test[B<:A] }` can't be compiled

I can understand why the following code can't be compiled: trait Hello[+A] { def test[B<:A](x: B) } Because: val child: Hello[String] = new Hello[String] { def test[B <: String](x: ...
0
votes
1answer
16 views

Deduplication in build.sbt

There are conflicting jline jar files in the includes path that need to be deduplicated. I have attempted to do so as follows: I am building a combined spark and kafka fat jar and the jline jar file ...
2
votes
1answer
43 views

Scala return value not what is expected

I am learning Scala as a personal interest and I'm perplexed by the return value of the following, of which I expect to eventually print 52: def lexicalTest(a: Int) = { (b: Int) => { (c: ...
3
votes
1answer
33 views

Passing values from request to all the layers below controller

If a Play controller retrieves a values from the Request (e.g. logged in user and his role) and those values need to be passed to all the layers down to controllers (e.g. service layer, DAO layer etc) ...

15 30 50 per page
================================================ FILE: src/test/resources/twitter4j.properties ================================================ loggerFactory=twitter4j.internal.logging.SLF4JLoggerFactory debug=true