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 current community chat blog Stack Overflow Meta Stack Overflow Careers 2.0 your communities Sign up or log in to customize your list. more stack exchange communities Stack Exchange sign up log in tour help Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site careers 2.0 Stack Overflow Questions Tags Tour Users Ask Question Tagged Questions info newest frequent votes active unanswered 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 https clojure websocket asked 3 hours ago Harikrishnan 996824 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 ... multithreading clojure agents asked 4 hours ago Christophe De Troyer 560311 -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 ... string clojure asked 5 hours ago Rajul Gupta 12 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 ... clojure timeout asked 8 hours ago Oliver Baier 11 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 ... clojure asked 11 hours ago tungd 2,693814 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. ... macros clojure asked 13 hours ago DANG Fan 615 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] ... clojure namespaces leiningen asked 13 hours ago Viktor K. 427210 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, ... clojure quil asked 18 hours ago barerd 1751113 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]] ... clojure functional-programming asked 19 hours ago divs1210 778 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 ... clojure evaluation asked 23 hours ago user3043408 1 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 ... sorting clojure asked yesterday redhands 424 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 ... java maven clojure jni dependencies asked yesterday ems 62 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: ... macros clojure static interop expand asked yesterday Matt Fenwick 16.5k437102 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 ... clojure lazy-sequences asked yesterday Christophe De Troyer 560311 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 ... maven clojure libraries leiningen asked yesterday hawkeye 5,787435105 1 2 3 4 5 … 490 next 15 30 50 per page newest clojure questions feed 7,337 questions tagged clojure about » Related Tags java × 571 leiningen × 501 functional-programming × 272 lisp × 261 macros × 241 clojurescript × 206 compojure × 200 emacs × 190 ring × 158 read-eval-print-loop × 110 map × 98 scala × 97 jvm × 91 clojure-contrib × 89 recursion × 82 noir × 79 concurrency × 77 vector × 75 namespaces × 74 lazy-evaluation × 73 slime × 71 clojure-java-interop × 71 scheme × 69 haskell × 65 function × 63 more related tags Hot Network Questions 3D - How to make this photo wall effect in Photoshop? What to do with students who think they "already know it," but actually don't? Lexing: One token per operator, or one universal operator token? What food / drink affects vocal characteristics? How to deal with a misnamed function in production code? Why does the history command do nothing in a script file? What etiquette should a new player observe at the gaming table? difference between `names(df[1]) <- ` and `names(df)[1] <- ` ln|x| vs. ln(x)? When is the ln antiderivative marked as an absolute value? Why does the water in a Powerade bottle tastes a little like Powerade after many refills? Is there independent oversight of Journal Impact Factors? How slow is python really? (Or how fast is your language?) Does water have surface tension in a vacuum? Returning all positions for all different occurences of elements in a list Do I have to relinquish my PC password to my former boss? What are the rules for ability score maximums? Why is an engine like Unity3D emphasized over a native library like OpenGL for beginners? When I travel next, I want to reach the point on the earth that is exactly opposite my home, how can I discover where that is? Is there any way to check the Governor's daughters' beauty level? Can I simplify this recursive grid search? Secular pro-life argument Labeling a grid What can I do if my supervisor does not publish my research results? tikz incorrect node placement : gap between nodes more hot questions Stack Overflow works best with JavaScript enabled ================================================ FILE: src/test/resources/groovy-questions.html ================================================ Newest 'groovy' Questions - Stack Overflow current community chat blog Stack Overflow Meta Stack Overflow Careers 2.0 your communities Sign up or log in to customize your list. more stack exchange communities Stack Exchange sign up log in tour help Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site careers 2.0 Stack Overflow Questions Tags Tour Users Ask Question Tagged Questions info newest 1 featured frequent votes active unanswered 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() } grails groovy asked 1 hour ago baxxabit 7181616 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. grails groovy asked 3 hours ago More Than Five 928723 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 { ... grails groovy configuration asked 3 hours ago AdjustingForInflation 98 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 ... windows command-line groovy asked 4 hours ago Eytan 5171821 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: ... eclipse groovy dsl dsld asked 6 hours ago Morten Schwarzkopf 11 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 ... xml groovy asked 6 hours ago hexin 706 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? grails groovy asked 6 hours ago baxxabit 7181616 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 ... groovy process asked 8 hours ago u123 94133370 -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: [ ... mongodb grails groovy asked 9 hours ago user3584616 12 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 ... java unit-testing groovy spock asked 15 hours ago PM 77-1 3,35131232 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 ... grails plugins groovy grails-plugin grails-config asked 16 hours ago Vahid Pazirandeh 10016 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, ... soap groovy http-headers soapui asked 18 hours ago Sasanka Panguluri 1,120415 -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 ... windows groovy expect asked 22 hours ago Eytan 5171821 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 ... java design-patterns groovy asked 22 hours ago uros calakovic 245 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 groovy groovy-console groovyws asked 23 hours ago user2355711 1 1 2 3 4 5 … 568 next 15 30 50 per page newest groovy questions feed 8,510 questions tagged groovy about » Related Tags grails × 2859 java × 1554 xml × 303 gradle × 288 gorm × 264 eclipse × 225 soapui × 221 unit-testing × 170 spock × 167 closures × 166 hibernate × 165 spring × 159 regex × 151 json × 143 jenkins × 130 maven × 128 sql × 123 intellij-idea × 119 gsp × 117 geb × 98 string × 96 metaprogramming × 95 xmlslurper × 95 ant × 86 list × 85 more related tags Hot Network Questions How do I create a user-defined literal for a signed integer type? How is calculus helpful for biology majors? Why evolution does not make our life longer? Running numbers for comments Regression - How do I know if my residuals are normally distributed? How slow is python really? (Or how fast is your language?) Replacement for ability to "send tab to remote device" as removed from Firefox 29 What can I do if my supervisor does not publish my research results? If null is evil (and it is) why do modern languages implement it? Table marked as crashed and repair failed How to know running platform is Ubuntu or Centos with help of bash script ? Is using the phrase "... is left as an exercise for the reader" considered good style in academic papers/theses? Why does the water in a Powerade bottle tastes a little like Powerade after many refills? Why is an engine like Unity3D emphasized over a native library like OpenGL for beginners? Singular of "dice" How do I verify the Coq proof of Feit-Thompson? Code execution does not stop even after an excepton thrown. Any suggestions? How can I extract the numbers in the file using sed or any other tool? Can't set SSH port to something other than 22 What to do with students who think they "already know it," but actually don't? Why does the history command do nothing in a script file? ln|x| vs. ln(x)? When is the ln antiderivative marked as an absolute value? How to get only one symbol from a symbol package? Why is an actor sometimes called 'ham'? more hot questions Stack Overflow works best with JavaScript enabled ================================================ FILE: src/test/resources/java-questions.html ================================================ Newest 'java' Questions - Stack Overflow current community chat blog Stack Overflow Meta Stack Overflow Careers 2.0 your communities Sign up or log in to customize your list. more stack exchange communities Stack Exchange sign up log in tour help Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site careers 2.0 Stack Overflow Questions Tags Tour Users Ask Question Tagged Questions info newest 33 featured frequent votes active unanswered 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); ... java collections guava short-circuiting asked 1 min ago dimo414 6,18812559 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: ... java hibernate tomcat servlets asked 2 mins ago user3596405 1 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> ... java xml maven reporting pom.xml asked 5 mins ago user2931656 283 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 ... java android unit-testing junit handler asked 6 mins ago user3596747 1 -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-'.']+$"; java regex asked 7 mins ago user3596731 1 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 ... java shell variables jdbc command-line-arguments asked 10 mins ago Smruti 155 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 ... java variables generics duplicates asked 10 mins ago Ben 1469 -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 ... java compilation extend asked 11 mins ago user3596756 1 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 ... java multithreading spring jpa spring-data asked 14 mins ago Affan 781614 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: ... java paypal paypal-sandbox paypalmerchantsdk asked 15 mins ago user3596713 1 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 ... java object reference binary-tree avl-tree asked 16 mins ago user3187464 112 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 ... java security java-web-start jnlp rich-internet-application asked 16 mins ago tmporaries 152113 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 ... java jsf primefaces asked 20 mins ago Tot 113 -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 ... java algorithm hadoop graph mapreduce asked 20 mins ago Timofey 496 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 ... java android sockets asked 22 mins ago user10001110101 124213 1 2 3 4 5 … 42167 next 15 30 50 per page newest java questions feed 632,492 questions tagged java about » Related Tags android × 79031 swing × 40023 eclipse × 25749 spring × 23448 hibernate × 18263 multithreading × 14108 xml × 13382 arrays × 13168 jsp × 12856 string × 11582 servlets × 11115 java-ee × 10398 mysql × 9020 regex × 9017 maven × 8862 tomcat × 8642 jpa × 8403 spring-mvc × 8323 jdbc × 8172 json × 8165 javascript × 7734 web-services × 7572 arraylist × 6922 generics × 6710 sql × 6636 more related tags Hot Network Questions How can an e-mail get lost? Evaluation of expectation values Why do SSDs have weird sizes? Singular of "dice" Why does auto a=1; compile in C? Regression - How do I know if my residuals are normally distributed? How to identify key changes? Is there any perfect squares that are also binomial coefficients? How can I create a template for 2048 game situations? Why evolution does not make our life longer? A word for the heart-wrenching pain of wanting someone you can't have Why does the filename contains question marks when I run a script on my remote machine? The unreasonable power of non-uniformity Use of "always" and "am" Had miscarriage, how to deal with coworkers What was the nominal strength of a company in a British Regiment during the American war of Independence? Gods have summon sickness? Why I can not directly get the content of `.bss` section? ln|x| vs. ln(x)? When is the ln antiderivative marked as an absolute value? How attached should players be to the characters they make? Why is an actor sometimes called 'ham'? Find all the missing number(s) How slow is python really? (Or how fast is your language?) Difference between 'crow's feet' and 'worry lines' more hot questions Stack Overflow works best with JavaScript enabled Newest 'java' Questions - Stack Overflow current community chat blog Stack Overflow Meta Stack Overflow Careers 2.0 your communities Sign up or log in to customize your list. more stack exchange communities Stack Exchange sign up log in tour help Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site careers 2.0 Stack Overflow Questions Tags Tour Users Ask Question Tagged Questions info newest 33 featured frequent votes active unanswered 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); ... java collections guava short-circuiting asked 1 min ago dimo414 6,18812559 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: ... java hibernate tomcat servlets asked 2 mins ago user3596405 1 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> ... java xml maven reporting pom.xml asked 5 mins ago user2931656 283 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 ... java android unit-testing junit handler asked 6 mins ago user3596747 1 -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-'.']+$"; java regex asked 7 mins ago user3596731 1 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 ... java shell variables jdbc command-line-arguments asked 10 mins ago Smruti 155 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 ... java variables generics duplicates asked 10 mins ago Ben 1469 -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 ... java compilation extend asked 11 mins ago user3596756 1 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 ... java multithreading spring jpa spring-data asked 14 mins ago Affan 781614 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: ... java paypal paypal-sandbox paypalmerchantsdk asked 15 mins ago user3596713 1 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 ... java object reference binary-tree avl-tree asked 16 mins ago user3187464 112 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 ... java security java-web-start jnlp rich-internet-application asked 16 mins ago tmporaries 152113 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 ... java jsf primefaces asked 20 mins ago Tot 113 -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 ... java algorithm hadoop graph mapreduce asked 20 mins ago Timofey 496 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 ... java android sockets asked 22 mins ago user10001110101 124213 1 2 3 4 5 … 42167 next 15 30 50 per page newest java questions feed 632,492 questions tagged java about » Related Tags android × 79031 swing × 40023 eclipse × 25749 spring × 23448 hibernate × 18263 multithreading × 14108 xml × 13382 arrays × 13168 jsp × 12856 string × 11582 servlets × 11115 java-ee × 10398 mysql × 9020 regex × 9017 maven × 8862 tomcat × 8642 jpa × 8403 spring-mvc × 8323 jdbc × 8172 json × 8165 javascript × 7734 web-services × 7572 arraylist × 6922 generics × 6710 sql × 6636 more related tags Hot Network Questions How can an e-mail get lost? Evaluation of expectation values Why do SSDs have weird sizes? Singular of "dice" Why does auto a=1; compile in C? Regression - How do I know if my residuals are normally distributed? How to identify key changes? Is there any perfect squares that are also binomial coefficients? How can I create a template for 2048 game situations? Why evolution does not make our life longer? A word for the heart-wrenching pain of wanting someone you can't have Why does the filename contains question marks when I run a script on my remote machine? The unreasonable power of non-uniformity Use of "always" and "am" Had miscarriage, how to deal with coworkers What was the nominal strength of a company in a British Regiment during the American war of Independence? Gods have summon sickness? Why I can not directly get the content of `.bss` section? ln|x| vs. ln(x)? When is the ln antiderivative marked as an absolute value? How attached should players be to the characters they make? Why is an actor sometimes called 'ham'? Find all the missing number(s) How slow is python really? (Or how fast is your language?) Difference between 'crow's feet' and 'worry lines' more hot questions Stack Overflow works best with JavaScript enabled ================================================ FILE: src/test/resources/logback-test.xml ================================================ %r | %thread | %m%n%rEx ================================================ FILE: src/test/resources/scala-questions.html ================================================ Newest 'scala' Questions - Stack Overflow current community chat blog Stack Overflow Meta Stack Overflow Careers 2.0 your communities Sign up or log in to customize your list. more stack exchange communities Stack Exchange sign up log in tour help Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site careers 2.0 Stack Overflow Questions Tags Tour Users Ask Question Tagged Questions info newest 6 featured frequent votes active unanswered 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 ... scala sbt asked 39 mins ago joescii 2,176312 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 ... scala apache-camel activemq akka asked 1 hour ago gnathan 707 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 = ... scala playframework slick asked 2 hours ago Blankman 33.8k107370713 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 ... java scala sbt scalding asked 3 hours ago user416096 1011210 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 = ... scala apache-kafka asked 3 hours ago user3596090 61 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. ... scala type-systems asked 3 hours ago Freewind 26.7k16108246 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 <- ... scala asked 5 hours ago I.K. 1,1121213 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 ... java scala lambda java-parallelstream asked 6 hours ago Syam S 2276 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 ... java scala jackson lombok json4s asked 7 hours ago bertvh 1527 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? scala asked 8 hours ago BalaB 4622616 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. ... c# scala scope variable-scope asked 8 hours ago Electric Coffee 719317 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: ... scala contravariance type-systems asked 10 hours ago Freewind 26.7k16108246 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 ... scala sbt asked 11 hours ago javadba 1,360720 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: ... javascript scala functional-programming closures asked 11 hours ago biscuitsauce 133 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) ... scala playframework asked 13 hours ago Vikas Pandya 1236 1 2 3 4 5 … 1675 next 15 30 50 per page newest scala questions feed 25,118 questions tagged scala about » Related Tags java × 2297 playframework × 1791 playframework-2.0 × 1625 sbt × 1607 akka × 1076 lift × 873 functional-programming × 754 actor × 597 types × 584 scala-collections × 535 json × 517 generics × 468 slick × 423 intellij-idea × 423 eclipse × 413 scala-2.10 × 398 pattern-matching × 395 playframework-2.1 × 367 reflection × 362 mongodb × 347 scala-2.8 × 345 list × 316 scalaz × 306 collections × 301 playframework-2.2 × 291 more related tags Hot Network Questions Determine if a move exists in a Bejeweled/match 3 game Are these MLE estimates biased? Port mirroring just the Rx (or Tx) direction of a port? Why I can not directly get the content of `.bss` section? Is using the phrase "... is left as an exercise for the reader" considered good style in academic papers/theses? Secular pro-life argument Why would killing Darth Vader or the Emperor turn Luke to the Dark Side? How to identify key changes? Running numbers for comments How do I verify the Coq proof of Feit-Thompson? auto- or crosscorrelation for syncronisation in Matlab Gods have summon sickness? When I travel next, I want to reach the point on the earth that is exactly opposite my home, how can I discover where that is? Mathematicians ahead of their time? Teaching my 10 year old son appropriate bathroom manners difference between `names(df[1]) <- ` and `names(df)[1] <- ` How accurate is the Scale Line in OpenLayers Does water have surface tension in a vacuum? Is there independent oversight of Journal Impact Factors? What etiquette should a new player observe at the gaming table? Can anyone clarify the concept of a "sum of random variables" 3D - How to make this photo wall effect in Photoshop? Buying a Macbook Air Can we see our future? more hot questions Stack Overflow works best with JavaScript enabled ================================================ FILE: src/test/resources/twitter4j.properties ================================================ loggerFactory=twitter4j.internal.logging.SLF4JLoggerFactory debug=true
Clojure is a modern Lisp dialect for the Java Virtual Machine (with versions for the CLR and JavaScript).
learn more… | top users | synonyms (1)
questions tagged
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
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
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 ...